text
stringlengths
2
1.04M
meta
dict
#pragma once #include <cub/cub.cuh> #include <mgpuhost.cuh> #include <moderngpu.cuh> #include <nvbio/strings/string_set.h> #include <nvbio/basic/thrust_view.h> #include <nvbio/basic/cuda/sort.h> #include <nvbio/basic/cuda/timer.h> #include <nvbio/basic/cuda/ldg.h> #include <nvbio/basic/cuda/primitives.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/adjacent_difference.h> #include <thrust/binary_search.h> #include <thrust/iterator/constant_iterator.h> #if defined(PLATFORM_X86) #include <emmintrin.h> // SSE intrinsics #endif namespace nvbio { namespace priv { template <uint32 BITS> struct word_selector {}; template <> struct word_selector<4> { typedef uint8 type; }; template <> struct word_selector<6> { typedef uint8 type; }; template <> struct word_selector<8> { typedef uint8 type; }; template <> struct word_selector<10> { typedef uint8 type; }; template <> struct word_selector<12> { typedef uint16 type; }; template <> struct word_selector<14> { typedef uint16 type; }; template <> struct word_selector<16> { typedef uint16 type; }; template <> struct word_selector<18> { typedef uint16 type; }; template <> struct word_selector<20> { typedef uint32 type; }; template <> struct word_selector<22> { typedef uint32 type; }; template <> struct word_selector<24> { typedef uint32 type; }; template <> struct word_selector<26> { typedef uint32 type; }; template <> struct word_selector<28> { typedef uint32 type; }; template <> struct word_selector<30> { typedef uint32 type; }; template <> struct word_selector<32> { typedef uint32 type; }; template <> struct word_selector<48> { typedef uint64 type; }; template <> struct word_selector<64> { typedef uint64 type; }; typedef ConcatenatedStringSet< PackedStream<uint32*,uint8,2u,false,uint64>, uint64*> string_set_2bit; typedef ConcatenatedStringSet< PackedStream<uint32*,uint8,2u,false,uint64>, uint64*> string_set_4bit; typedef ConcatenatedStringSet< PackedStream<uint32*,uint8,8u,false,uint64>, uint64*> string_set_8bit; typedef ConcatenatedStringSet< PackedStream<uint32*,uint8,2u,true,uint64>, uint64*> string_set_2bit_be; typedef ConcatenatedStringSet< PackedStream<uint64*,uint8,2u,true,uint64>, uint64*> string_set_2bit_u64_be; typedef PackedStream<uint32*,uint8,2u,false,uint64> string_2bit_le; typedef PackedStream<uint32*,uint8,4u,false,uint64> string_4bit_le; typedef PackedStream<uint32*,uint8,8u,false,uint64> string_8bit_le; typedef PackedStream<uint32*,uint8,2u,true,uint64> string_2bit_be; typedef PackedStream<uint32*,uint8,4u,true,uint64> string_4bit_be; typedef PackedStream<uint32*,uint8,8u,true,uint64> string_8bit_be; void extract_radices( const priv::string_set_2bit_be string_set, const uint32 n_suffixes, const uint32 word_begin, const uint32 word_end, const uint32 word_bits, const uint2* suffixes, uint32* radices, uint8* symbols = NULL); void extract_radices( const priv::string_set_2bit_u64_be string_set, const uint32 n_suffixes, const uint32 word_begin, const uint32 word_end, const uint32 word_bits, const uint2* suffixes, uint64* radices, uint8* symbols = NULL); // make sure a given buffer is big enough // template <typename VectorType> void alloc_storage(VectorType& vec, const uint64 size) { if (vec.size() < size) { try { vec.clear(); vec.resize( size ); } catch (...) { log_error(stderr,"alloc_storage() : allocation failed!\n"); throw; } } } /// set the last n bits to 0 /// template <typename storage_type> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE storage_type clearmask(const uint32 n) { return ~((storage_type(1u) << n)-1u); } /// A functor to cast from one type into another /// struct in_range_functor { typedef uint32 argument_type; typedef bool result_type; /// constructor /// in_range_functor(const uint32 _begin, const uint32 _end) : begin(_begin), end(_end) {} /// return true if i is in the range /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE bool operator() (const uint32 i) const { return i >= begin && i < end; } const uint32 begin, end; }; /// A functor subtracting the second element of a pair from the first /// struct minus_one { typedef uint32 argument_type; typedef uint32 result_type; /// return the length of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 operator() (const uint32 i) const { return i - 1; } }; /// A functor adding the given constant to all intergers /// struct offset_functor { typedef uint32 argument_type; typedef uint32 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE offset_functor(const uint32 _offset) : offset(_offset) {} /// return the length of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 operator() (const uint32 i) const { return i + offset; } const uint32 offset; }; /// A functor dividing all integers by the given constant /// struct add_divide_functor { typedef uint32 argument_type; typedef uint32 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE add_divide_functor(const uint32 _a, const uint32 _k) : a(_a), k(_k) {} /// return the length of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 operator() (const uint32 i) const { return (i + a) / k; } const uint32 a; const uint32 k; }; /// A functor fetching the length of the i-th string in a set /// template <typename string_set_type> struct length_functor { typedef uint32 argument_type; typedef uint32 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE length_functor(const string_set_type _string_set, const bool _extended) : string_set(_string_set), extended(_extended) {} /// return the length of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 operator() (const uint32 i) const { return string_set[i].length() + (extended ? 1u : 0u); } string_set_type string_set; bool extended; }; /// A functor adding the given constant to the string id of a suffix /// struct suffix_offset_functor { typedef uint2 argument_type; typedef uint2 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE suffix_offset_functor(const uint32 _offset) : offset(_offset) {} /// return the length of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint2 operator() (const uint2 suffix) const { return make_uint2( suffix.x, suffix.y + offset ); } const uint32 offset; }; /// A functor returning the given component of a suffix /// enum SuffixComponent { SUFFIX_ID = 0, STRING_ID = 1 }; template <SuffixComponent COMP> struct suffix_component_functor { typedef uint2 argument_type; typedef uint32 result_type; /// return the length of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 operator() (const uint2 suffix) const { return COMP == STRING_ID ? suffix.y : suffix.x; } }; template <uint32 WORD_BITS, uint32 DOLLAR_BITS, uint32 SYMBOL_SIZE, typename string_type, typename index_type> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 extract_word_generic( const string_type string, const index_type string_len, const index_type suffix_idx, const uint32 w) { const uint32 SYMBOLS_PER_WORD = uint32(WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE; const uint32 SYMBOL_OFFSET = uint32(WORD_BITS) - SYMBOL_SIZE; uint32 word = 0u; for (uint32 j = 0; j < SYMBOLS_PER_WORD; ++j) { const index_type jj = suffix_idx + w*SYMBOLS_PER_WORD + j; const uint32 c = jj < string_len ? string[jj] : 0u; word |= (c << (SYMBOL_OFFSET - j*SYMBOL_SIZE)); } if (DOLLAR_BITS) { // encode the dollar's position in the least significant bits of the word const uint32 dollar_offset = string_len <= suffix_idx + w*SYMBOLS_PER_WORD + SYMBOLS_PER_WORD ? // is there a dollar sign? (string_len < suffix_idx + w*SYMBOLS_PER_WORD) ? 0u : uint32(string_len - suffix_idx - w*SYMBOLS_PER_WORD) : (1u << DOLLAR_BITS)-1u; // no dollar sign in this word return word | dollar_offset; } else return word; } /// return how many symbols are encoded per word /// template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE uint32 symbols_per_word() { const uint32 SYMBOLS_PER_WORD = (WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE; return SYMBOLS_PER_WORD; } template <uint32 WORD_BITS, uint32 DOLLAR_BITS, uint32 SYMBOL_SIZE, typename storage_type, typename index_type, typename sufindex_type> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE typename std::iterator_traits<storage_type>::value_type extract_word_packed( const storage_type base_words, const index_type string_len, const index_type string_off, const sufindex_type suffix_idx, const uint32 w) { typedef typename std::iterator_traits<storage_type>::value_type word_type; const uint32 STORAGE_BITS = uint32( 8u * sizeof(word_type) ); const uint32 STORAGE_SYMBOLS = STORAGE_BITS / SYMBOL_SIZE; const uint32 SYMBOLS_PER_WORD = uint32(WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE; //const uint32 SYMBOL_OFFSET = uint32(WORD_BITS) - SYMBOL_SIZE; const sufindex_type suffix_off = suffix_idx + w*SYMBOLS_PER_WORD; // suffix offset // do we have any symbols to encode? if (suffix_off >= string_len) return 0u; const index_type range_len = string_len - suffix_off; // partial suffix length const index_type range_off = string_off + suffix_off; // partial suffix offset const uint32 n_symbols = (uint32)nvbio::min( range_len, index_type(SYMBOLS_PER_WORD) ); // symbols to pack // // As SYMBOLS_PER_WORD is less than 32, we know that the symbols we are looking for // will span at most 2 32-bit words. // Of the n_symbols we want to read, there might be n1 in the first word, and n2 in the // second word. // As the beginning of our symbol stream (range_off) might stride the 32-bit word boundary, // the highest m1 = range_off % 16 symbols of the first word might have to be discarded, // and we'll find our n1 symbols in the following position: // // |-------------------------------------------| // |* * * * * *| x x x x x x x x x | * * * * * | // |-------------------------------------------| // | m1 | n1 | r1 | // // What we do is shifting the n1 symbols to the top of the 32-bit word (i.e. m1 to the left). // Clearing the remaining symbols is only needed if n1 == n_symbols; if n1 < n_symbols, r1 will // be necessarily zero. // // At this point, we might have n2 more symbols to read in the highest bits of the second word: // // |-------------------------------------------| // | y y y y y y y y | * * * * * * * * * * * * | // |-------------------------------------------| // | n2 | r2 | // // which we need to shift right by (n1*SYMBOL_SIZE) bits. // At the very end, we'll shift everything right by (32 - WORD_BITS) bits in order to have // our output tightly packed in the lowest WORD_BITS: // // 32 WORD_BITS DOLLAR_BITS 0 // |-----------|-----------------------|-------| // | * * * * * | x x x x | y y y | 0 0 | $ $ $ | // notice the possible presence of 0's before // |-------------------------------------------| // the $ sign: these are bits that need to be // | | n1 | n2 | | | // cleared if the suffix is short // const uint32 k1 = uint32( range_off/STORAGE_SYMBOLS ); // index of the first word const uint32 m1 = range_off & (STORAGE_SYMBOLS-1); // offset in the word const uint32 r1 = STORAGE_SYMBOLS - m1; // symbols to read const word_type word1 = (base_words[ k1 ] << (m1*SYMBOL_SIZE)); // fetch the first word, shifted left word_type word = word1; if (n_symbols > r1) // do we need to read another word? { const word_type word2 = base_words[ k1+1u ]; // fetch the second word word |= word2 >> (r1*SYMBOL_SIZE); // shift by n1 symbols to the right } word >>= (STORAGE_BITS - WORD_BITS); // align the top to WORD_BITS // clear every symbol we don't need among the word's LSD word &= clearmask<word_type>( WORD_BITS - n_symbols*SYMBOL_SIZE ); if (DOLLAR_BITS) { // encode the dollar's position in the least significant bits of the word const word_type dollar_offset = range_len <= SYMBOLS_PER_WORD ? // is there a dollar sign? range_len : (1u << DOLLAR_BITS)-1u; // no dollar sign in this word return word | dollar_offset; } else return word; } template <uint32 WORD_BITS, uint32 DOLLAR_BITS, uint32 SYMBOL_SIZE, typename storage_type, typename index_type, typename sufindex_type, typename output_iterator> NVBIO_FORCEINLINE NVBIO_HOST_DEVICE void extract_word_packed( const storage_type base_words, const index_type string_len, const index_type string_off, const sufindex_type suffix_idx, const uint32 word_begin, const uint32 word_end, output_iterator words) { typedef typename std::iterator_traits<storage_type>::value_type word_type; const uint32 STORAGE_BITS = uint32( 8u * sizeof(word_type) ); const uint32 STORAGE_SYMBOLS = STORAGE_BITS / SYMBOL_SIZE; const uint32 SYMBOLS_PER_WORD = uint32(WORD_BITS - DOLLAR_BITS)/SYMBOL_SIZE; //const uint32 SYMBOL_OFFSET = uint32(WORD_BITS) - SYMBOL_SIZE; sufindex_type suffix_off = suffix_idx + word_begin*SYMBOLS_PER_WORD; // suffix offset index_type range_len = string_len - suffix_off; // partial suffix length index_type range_off = string_off + suffix_off; // partial suffix offset const uint32 cache_begin = uint32( range_off / STORAGE_SYMBOLS ); #if defined(PLATFORM_X86) && !defined(NVBIO_DEVICE_COMPILATION) // use SSE to load all the words we need in a small cache const uint32 SSE_WORDS = 16u / sizeof( word_type ); const uint32 cache_end = uint32( (range_off + (word_end - word_begin)*SYMBOLS_PER_WORD) / STORAGE_SYMBOLS ); __m128i sse_cache[8]; for (uint32 w = cache_begin; w < cache_end; w += SSE_WORDS) sse_cache[ (w - cache_begin)/SSE_WORDS ] = _mm_loadu_si128( (const __m128i*)(base_words + w) ); const word_type* cached_words = (const word_type*)sse_cache; #elif 0 const_cached_iterator<storage_type> cached_words( base_words + cache_begin ); #else const storage_type cached_words = base_words + cache_begin; #endif for (uint32 w = word_begin; w < word_end; ++w) { // do we have any symbols to encode? if (suffix_off >= string_len) { words[w - word_begin] = 0u; continue; } const uint32 n_symbols = (uint32)nvbio::min( range_len, index_type(SYMBOLS_PER_WORD) ); // symbols to pack // // As SYMBOLS_PER_WORD is less than 32, we know that the symbols we are looking for // will span at most 2 32-bit words. // Of the n_symbols we want to read, there might be n1 in the first word, and n2 in the // second word. // As the beginning of our symbol stream (range_off) might stride the 32-bit word boundary, // the highest m1 = range_off % 16 symbols of the first word might have to be discarded, // and we'll find our n1 symbols in the following position: // // |-------------------------------------------| // |* * * * * *| x x x x x x x x x | * * * * * | // |-------------------------------------------| // | m1 | n1 | r1 | // // What we do is shifting the n1 symbols to the top of the 32-bit word (i.e. m1 to the left). // Clearing the remaining symbols is only needed if n1 == n_symbols; if n1 < n_symbols, r1 will // be necessarily zero. // // At this point, we might have n2 more symbols to read in the highest bits of the second word: // // |-------------------------------------------| // | y y y y y y y y | * * * * * * * * * * * * | // |-------------------------------------------| // | n2 | r2 | // // which we need to shift right by (n1*SYMBOL_SIZE) bits. // At the very end, we'll shift everything right by (32 - WORD_BITS) bits in order to have // our output tightly packed in the lowest WORD_BITS: // // 32 WORD_BITS DOLLAR_BITS 0 // |-----------|-----------------------|-------| // | * * * * * | x x x x | y y y | 0 0 | $ $ $ | // notice the possible presence of 0's before // |-------------------------------------------| // the $ sign: these are bits that need to be // | | n1 | n2 | | | // cleared if the suffix is short // const uint32 k1 = uint32( range_off/STORAGE_SYMBOLS ) - cache_begin; // index of the first word const uint32 m1 = range_off & (STORAGE_SYMBOLS-1); // offset in the word const uint32 r1 = STORAGE_SYMBOLS - m1; // symbols left in the word const word_type word1 = (cached_words[ k1 ] << (m1*SYMBOL_SIZE)); // fetch the first word, shifted left word_type word = word1; if (n_symbols > r1) // do we need to read another word? { const word_type word2 = cached_words[ k1+1u ]; // fetch the second word word |= word2 >> (r1*SYMBOL_SIZE); // shift by n1 symbols to the right } word >>= (STORAGE_BITS - WORD_BITS); // align the top to WORD_BITS // clear every symbol we don't need among the word's LSD word &= clearmask<word_type>( WORD_BITS - n_symbols*SYMBOL_SIZE ); if (DOLLAR_BITS) { // encode the dollar's position in the least significant bits of the word const word_type dollar_offset = range_len <= SYMBOLS_PER_WORD ? // is there a dollar sign? range_len : (1u << DOLLAR_BITS)-1u; // no dollar sign in this word word |= dollar_offset; } // write the word out words[ w - word_begin ] = word; suffix_off += SYMBOLS_PER_WORD; range_len -= SYMBOLS_PER_WORD; range_off += SYMBOLS_PER_WORD; } } /// A functor to localize suffixes, making the conversion: global-suffix-id -> (string-id,suffix-id) /// struct localize_suffix_functor { typedef uint32 argument_type; typedef uint2 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE localize_suffix_functor(const uint32* _cum_lengths, const uint32* _string_ids, const uint32 _string_offset = 0u) : cum_lengths(_cum_lengths), string_ids(_string_ids), string_offset( _string_offset ) {} /// return the localized suffix /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint32 global_suffix_idx) const { const uint32 string_idx = string_ids[ global_suffix_idx ]; const uint32 suffix_idx = global_suffix_idx - (string_idx ? cum_lengths[ string_idx-1u ] : 0u); return make_uint2( suffix_idx, string_offset + string_idx ); } const uint32* cum_lengths; const uint32* string_ids; const uint32 string_offset; }; /// A functor fetching the w'th word worth of 2-bit symbols from the i-th string in a set /// template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_set_type, typename word_type> struct local_set_suffix_word_functor { typedef uint2 argument_type; typedef word_type result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE local_set_suffix_word_functor(const string_set_type _string_set, const uint32 _w) : string_set(_string_set), w(_w) {} /// return the w'th word of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint2 local_suffix_idx) const { typedef typename string_set_type::string_type string_type; const uint32 string_idx = local_suffix_idx.y; const uint32 suffix_idx = local_suffix_idx.x; const string_type string = string_set[string_idx]; const uint32 string_len = string.length(); return result_type( extract_word_generic<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>( string, string_len, suffix_idx, w ) ); } string_set_type string_set; uint32 w; }; /// A functor fetching the w'th word worth of 2-bit symbols from the given (string,suffix) in a set /// template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename storage_type, typename word_type, typename offsets_iterator> struct local_set_suffix_word_functor< SYMBOL_SIZE, WORD_BITS, DOLLAR_BITS, ConcatenatedStringSet< PackedStream<storage_type,uint8,SYMBOL_SIZE,true,typename std::iterator_traits<offsets_iterator>::value_type>, offsets_iterator>, word_type> { typedef typename std::iterator_traits<offsets_iterator>::value_type index_type; typedef ConcatenatedStringSet< PackedStream<storage_type,uint8,SYMBOL_SIZE,true,index_type>, offsets_iterator> string_set_type; typedef uint2 argument_type; typedef word_type result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE local_set_suffix_word_functor(const string_set_type _string_set, const uint32 _w) : string_set(_string_set), w(_w) {} /// return the w'th word of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint2 local_suffix_idx) const { typedef typename string_set_type::string_type string_type; const uint32 string_idx = local_suffix_idx.y; const uint32 suffix_idx = local_suffix_idx.x; const index_type string_off = string_set.offsets()[ string_idx ]; const index_type string_end = string_set.offsets()[ string_idx+1u ]; const index_type string_len = uint32( string_end - string_off ); const storage_type base_words = string_set.base_string().stream(); return result_type( extract_word_packed<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>( base_words, string_len, string_off, suffix_idx, w ) ); } string_set_type string_set; uint32 w; }; /// A functor fetching the w'th word worth of 2-bit symbols from the i-th suffix in a set /// template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_set_type, typename word_type> struct global_set_suffix_word_functor { typedef uint32 argument_type; typedef word_type result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE global_set_suffix_word_functor(const string_set_type _string_set, const uint32* _cum_lengths, const uint32* _string_ids, const uint32 _w) : word_functor( _string_set, _w ), localizer( _cum_lengths, _string_ids ) {} /// return the w'th word of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint32 global_suffix_idx) const { return word_functor( localizer( global_suffix_idx ) ); } local_set_suffix_word_functor<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS,string_set_type,word_type> word_functor; localize_suffix_functor localizer; }; /// A functor fetching the w'th word worth of 2-bit symbols from the i-th string in a set /// template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_type, typename word_type> struct string_suffix_word_functor { typedef uint32 argument_type; typedef word_type result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE string_suffix_word_functor(const uint64 _string_len, const string_type _string, const uint32 _w) : string_len(_string_len), string(_string), w(_w) {} /// return the w'th word of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint64 suffix_idx) const { return result_type( extract_word_generic<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>( string, string_len, suffix_idx, w ) ); } const uint64 string_len; string_type string; uint32 w; }; /// A functor fetching the w'th word worth of 2-bit symbols from the i-th string in a set /// template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename storage_type, typename symbol_type, typename index_type, typename word_type> struct string_suffix_word_functor< SYMBOL_SIZE, WORD_BITS, DOLLAR_BITS, PackedStream<storage_type,symbol_type,SYMBOL_SIZE,true,index_type>, word_type> { typedef typename PackedStream<storage_type,symbol_type,SYMBOL_SIZE,true,index_type>::iterator string_type; typedef uint2 argument_type; typedef word_type result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE string_suffix_word_functor(const index_type _string_len, const string_type _string, const uint32 _w) : string_len(_string_len), string(_string), w(_w) {} /// return the w'th word of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const index_type suffix_idx) const { const storage_type base_words = string.stream(); return result_type( extract_word_packed<WORD_BITS,DOLLAR_BITS,SYMBOL_SIZE>( base_words, string_len, string.index(), suffix_idx, w ) ); } const index_type string_len; string_type string; uint32 w; }; /// A binary functor calculating whether two suffixes differ (returning 1) or not (returning 0) /// template <typename string_type> struct string_suffix_difference { typedef uint32 first_argument_type; typedef uint32 second_argument_type; typedef uint32 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE string_suffix_difference(const uint64 _string_len, const string_type _string, const uint32 _cmp_len) : string_len(_string_len), string(_string), cmp_len( _cmp_len ) {} /// return the w'th word of the i-th string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint64 suffix_idx1, const uint64 suffix_idx2) const { // if one of the two suffixes is less than cmp_len, then the two suffixes must // necessarily differ (because no two suffixes have the same length) if (string_len - suffix_idx1 < cmp_len || string_len - suffix_idx2 < cmp_len) return 1u; for (uint32 i = 0; i < cmp_len; ++i) { if (string[suffix_idx1 + i] != string[suffix_idx2 + i]) return 1u; } return 0u; } const uint64 string_len; string_type string; uint32 cmp_len; }; /// A binary functor comparing two suffixes lexicographically /// template <uint32 SYMBOL_SIZE, typename string_type> struct string_suffix_less { typedef uint32 first_argument_type; typedef uint32 second_argument_type; typedef uint32 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE string_suffix_less(const uint64 _string_len, const string_type _string) : string_len(_string_len), string(_string) {} /// return true if the first suffix is lexicographically smaller than the second, false otherwise /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint64 suffix_idx1, const uint64 suffix_idx2) const { const uint32 WORD_BITS = 32u; // use 32-bit words const uint32 DOLLAR_BITS = 4u; // 4 is the minimum number needed to encode up to 16 symbols per word const uint32 SYMBOLS_PER_WORD = symbols_per_word<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS>(); const uint32 n_words = uint32( nvbio::min( (string_len - suffix_idx1), (string_len - suffix_idx2) ) + SYMBOLS_PER_WORD-1 ) / SYMBOLS_PER_WORD; // loop through all string-words for (uint32 w = 0; w < n_words; ++w) { string_suffix_word_functor<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS,string_type,uint32> word_functor( string_len, string, w ); const uint32 w1 = word_functor( suffix_idx1 ); const uint32 w2 = word_functor( suffix_idx2 ); if (w1 < w2) return true; if (w1 > w2) return false; } return false; } const uint64 string_len; string_type string; }; /// given a string, return the symbol preceding each of its suffixes, or 255u to mark the /// special $ symbol used for the first suffix. /// template <typename string_type> struct string_bwt_functor { typedef uint64 argument_type; typedef uint8 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE string_bwt_functor(const uint64 _string_len, const string_type _string) : string_len(_string_len), string(_string) {} /// return the symbol preceding the given suffix /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const argument_type suffix_idx) const { return suffix_idx ? string[suffix_idx-1] : 255u; // use 255u to mark the dollar sign } const uint64 string_len; const string_type string; }; /// given a string set, return the symbol preceding each of its suffixes, or 255u to mark the /// special $ symbol used for the first suffix. /// template <typename string_set_type> struct string_set_bwt_functor { typedef uint2 argument_type; typedef uint8 result_type; /// constructor /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE string_set_bwt_functor(const string_set_type _string_set) : string_set(_string_set) {} /// return the symbol preceding the given suffix /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const argument_type local_suffix_idx) const { typedef typename string_set_type::string_type string_type; const uint32 string_idx = local_suffix_idx.y; const uint32 suffix_idx = local_suffix_idx.x; const string_type string = string_set[string_idx]; return suffix_idx ? string[suffix_idx-1] : 255u; // use 255u to mark the dollar sign } /// return the last symbol of a given string /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint32 string_idx) const { typedef typename string_set_type::string_type string_type; const string_type string = string_set[string_idx]; return string[ string.length()-1 ]; } const string_set_type string_set; }; /// A binary functor implementing some custom logic to remove singletons from a set of segment-flags /// struct remove_singletons { typedef uint32 first_argument_type; typedef uint32 second_argument_type; typedef uint32 result_type; /// functor operator /// /// \return flag1 && flag2 ? 0 : 1 /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const uint32 flag1, const uint32 flag2) const { return (flag1 && flag2) ? 0u : 1u; } }; /// A binary functor to merge keys with new radices /// struct merge_keys { typedef uint32 first_argument_type; typedef uint64 second_argument_type; typedef uint64 result_type; /// functor operator /// /// \return (key << 32u) | radix /// NVBIO_FORCEINLINE NVBIO_HOST_DEVICE result_type operator() (const first_argument_type radix, const second_argument_type key) const { return (key << 32u) | second_argument_type( radix ); } }; /* template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename string_set_type> struct dispatch_set_suffix_radices { template <typename radix_iterator> void enact( const string_set_type& string_set, const SetSuffixFlattener<SYMBOL_SIZE>& set_flattener, radix_iterator radices) { typedef typename std::iterator_traits<radix_iterator>::value_type word_type; thrust::transform( thrust::make_counting_iterator(0u), thrust::make_counting_iterator(0u) + set_flattener.n_suffixes, radices, global_set_suffix_word_functor<SYMBOL_SIZE,BITS,DOLLAR_BITS,string_set_type,word_type>( string_set, nvbio::device_view( set_flattener.cum_lengths ), nvbio::device_view( set_flattener.string_ids ), 0u ) ); } }; template <uint32 SYMBOL_SIZE, uint32 WORD_BITS, uint32 DOLLAR_BITS, typename storage_type, typename index_type> struct dispatch_set_suffix_radices< SYMBOL_SIZE, WORD_BITS, DOLLAR_BITS, ConcatenatedStringSet<PackedStream<storage_type,uint8,SYMBOL_SIZE,true,index_type>,index_type*>, word_type> { typedef ConcatenatedStringSet< PackedStream<storage_type,uint8,SYMBOL_SIZE,true,index_type>, index_type*> string_set_type; template <typename radix_iterator> void enact( const string_set_type& string_set, const SetSuffixFlattener<SYMBOL_SIZE>& set_flattener, radix_iterator radices) { typedef typename std::iterator_traits<radix_iterator>::value_type word_type; thrust::transform( thrust::make_counting_iterator(0u), thrust::make_counting_iterator(0u) + set_flattener.n_suffixes, radices, global_set_suffix_word_functor<SYMBOL_SIZE,BITS,DOLLAR_BITS,string_set_type,word_type>( string_set, nvbio::device_view( set_flattener.cum_lengths ), nvbio::device_view( set_flattener.string_ids ), word_idx ) ); } }; */ template <uint32 BITS, uint32 DOLLAR_BITS> struct Bits {}; /// A helper class allowing to "flatten" the suffixes in a given string-set, i.e. to extract /// all of them word-by-word in a flattened array. /// template <uint32 SYMBOL_SIZE> struct SetSuffixFlattener { SetSuffixFlattener(mgpu::ContextPtr _mgpu) : d_scan_time(0.0f), d_search_time(0.0f), m_mgpu( _mgpu ) {} /// clear internal timers /// void clear_timers() { d_scan_time = 0.0f; d_search_time = 0.0f; } /// reserve storage /// void reserve(const uint32 n_strings, const uint32 n_suffixes) { alloc_storage( cum_lengths, n_strings ); alloc_storage( string_ids, n_suffixes ); } /// return the amount of device memory needed /// uint64 needed_device_memory(const uint32 n_strings, const uint32 n_suffixes) const { return (n_strings + n_suffixes) * sizeof(uint32); } /// initialize this flattener, building the auxiliary data-structures needed /// to extract the radices /// template <typename string_set_type> void set(const string_set_type& string_set, const bool empty_suffixes = true) { const uint32 n = string_set.size(); cuda::Timer timer; timer.start(); // compute the cumulative sum of the string lengths in the set - we will use this for // building the map: (global suffix index -> string index) alloc_storage( cum_lengths, n ); cuda::inclusive_scan( n, thrust::make_transform_iterator( thrust::make_counting_iterator(0u), length_functor<string_set_type>( string_set, empty_suffixes ) ), cum_lengths.begin(), thrust::plus<uint32>(), temp_storage ); // compute the number of suffixes n_suffixes = cum_lengths[n-1]; timer.stop(); d_scan_time += timer.seconds(); timer.start(); // assign the string id to each suffix - this is done by a simple binary search on the suffix index // in the vector of cumulative string lengths alloc_storage( string_ids, n_suffixes ); // find the end of each bin of values mgpu::SortedSearch<mgpu::MgpuBoundsLower>( thrust::make_counting_iterator<uint32>(0u), n_suffixes, thrust::make_transform_iterator( cum_lengths.begin(), minus_one() ), n, string_ids.begin(), *m_mgpu ); timer.stop(); d_search_time += timer.seconds(); } /// extract the given radix of all suffixes /// template <uint32 BITS, uint32 DOLLAR_BITS, typename string_set_type, typename index_iterator, typename radix_iterator> void flatten( const string_set_type& string_set, const uint32 word_idx, const Bits<BITS,DOLLAR_BITS> word_bits, const index_iterator indices, radix_iterator radices) { typedef typename std::iterator_traits<radix_iterator>::value_type word_type; thrust::transform( indices, indices + n_suffixes, radices, global_set_suffix_word_functor<SYMBOL_SIZE,BITS,DOLLAR_BITS,string_set_type,word_type>( string_set, nvbio::device_view( cum_lengths ), nvbio::device_view( string_ids ), word_idx ) ); } /// compute the maximum suffix length among the specified range /// template <typename string_set_type> uint32 max_length( const string_set_type& string_set, const bool empty_suffixes = true) { // compute the maximum string length in the set return cuda::reduce( uint32( string_set.size() ), thrust::make_transform_iterator( thrust::make_counting_iterator<uint32>(0u), length_functor<string_set_type>( string_set, empty_suffixes ) ), thrust::maximum<uint32>(), temp_storage ); } /// compute the maximum suffix length among the specified range /// template <typename string_set_type, typename index_iterator> uint32 max_length( const string_set_type& string_set, const index_iterator indices_begin, const index_iterator indices_end) { // TODO: this function is conservative, in the sense it returns the maximum *string* length; // however, each suffix might be shorter than the string it belongs to. return indices_end <= indices_begin ? 0u : cuda::reduce( indices_end - indices_begin, thrust::make_transform_iterator( thrust::make_permutation_iterator( string_ids.begin(), indices_begin ), length_functor<string_set_type>( string_set, false ) ), thrust::maximum<uint32>(), temp_storage ); } /// return the amount of used device memory /// uint64 allocated_device_memory() const { return cum_lengths.size() * sizeof(uint32) + string_ids.size() * sizeof(uint32) + temp_storage.size() * sizeof(uint8); } uint32 n_suffixes; ///< number of suffixes in the string set thrust::device_vector<uint32> cum_lengths; ///< cumulative string lengths thrust::device_vector<uint32> string_ids; ///< a vector containing the string index corresponding /// to each flattened suffixes; i.e. if the set contains /// 3 strings of length (3, 2, 5), the string ids will be /// the vector (0,0,0,1,1,2,2,2,2,2). thrust::device_vector<uint8> temp_storage; float d_scan_time; float d_search_time; mgpu::ContextPtr m_mgpu; }; /// A helper class to load a chunk of a string_set from the host onto the device /// template <uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename storage_type, typename offsets_iterator, typename input_tag, typename output_tag> struct ChunkLoader {}; /// A helper class to load a chunk of a string_set from the host onto the device /// template <uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename storage_type, typename offsets_iterator> struct ChunkLoader<SYMBOL_SIZE,BIG_ENDIAN,storage_type,offsets_iterator,host_tag,device_tag> { // infer the word type typedef typename std::iterator_traits<storage_type>::value_type word_type; typedef typename std::iterator_traits<offsets_iterator>::value_type index_type; typedef cuda::load_pointer<word_type,cuda::LOAD_LDG> word_pointer; typedef PackedStream<word_pointer,uint8,SYMBOL_SIZE,BIG_ENDIAN> packed_stream_type; typedef typename packed_stream_type::iterator packed_stream_iterator; typedef ConcatenatedStringSet<packed_stream_iterator,uint32*> chunk_set_type; // infer the word size static const uint32 SYMBOLS_PER_WORD = uint32(8u*sizeof(word_type))/SYMBOL_SIZE; uint64 needed_device_memory(const uint32 max_strings, const uint32 max_symbols) const { const uint32 max_words = util::divide_ri( max_symbols, SYMBOLS_PER_WORD ) + 2; return (max_strings+1) * sizeof(uint32) + max_words * sizeof(word_type); } void reserve(const uint32 max_strings, const uint32 max_symbols) { const uint32 max_words = util::divide_ri( max_symbols, SYMBOLS_PER_WORD ) + 2; alloc_storage( h_chunk_offsets, max_strings+1 ); alloc_storage( d_chunk_offsets, max_strings+1 ); alloc_storage( d_chunk_string, max_words ); } chunk_set_type load( const ConcatenatedStringSet< typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::iterator, offsets_iterator> string_set, const uint32 chunk_begin, const uint32 chunk_end) { const uint32 chunk_size = chunk_end - chunk_begin; alloc_storage( h_chunk_offsets, chunk_size+1 ); alloc_storage( d_chunk_offsets, chunk_size+1 ); // find the words overlapped by the chunk const uint64 begin_index = string_set.offsets()[ chunk_begin ]; const uint64 end_index = string_set.offsets()[ chunk_end ]; const uint64 begin_word = (begin_index / SYMBOLS_PER_WORD); const uint64 end_word = (end_index + SYMBOLS_PER_WORD-1) / SYMBOLS_PER_WORD; const uint32 chunk_words = uint32( end_word - begin_word ); const word_type* base_words = string_set.base_string().stream(); alloc_storage( d_chunk_string, chunk_words ); // copy them to the device thrust::copy( base_words + begin_word, base_words + begin_word + chunk_words, d_chunk_string.begin() ); // build the host offsets uint32 chunk_symbols = uint32( begin_index % SYMBOLS_PER_WORD ); h_chunk_offsets[0] = chunk_symbols; for (uint32 i = 0; i < chunk_size; ++i) { chunk_symbols += string_set[ chunk_begin + i ].size(); h_chunk_offsets[i+1] = chunk_symbols; } // copy the offsets to the device thrust::copy( h_chunk_offsets.begin(), h_chunk_offsets.begin() + chunk_size+1, d_chunk_offsets.begin() ); // finally assemble the device chunk string-set packed_stream_type d_packed_stream( word_pointer( nvbio::plain_view( d_chunk_string ) ) ); return chunk_set_type( chunk_size, d_packed_stream.begin(), nvbio::plain_view( d_chunk_offsets ) ); } thrust::host_vector<uint32> h_chunk_offsets; thrust::device_vector<word_type> d_chunk_string; thrust::device_vector<uint32> d_chunk_offsets; }; /// A helper class to load a chunk of a string_set from the host onto the device /// template <uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename storage_type, typename offsets_iterator, typename system_tag> struct ChunkLoader<SYMBOL_SIZE,BIG_ENDIAN,storage_type,offsets_iterator,system_tag,system_tag> { typedef typename std::iterator_traits<offsets_iterator>::value_type index_type; typedef const ConcatenatedStringSet< typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::iterator, offsets_iterator> string_set_type; typedef string_set_type chunk_set_type; chunk_set_type load( const string_set_type string_set, const uint32 chunk_begin, const uint32 chunk_end) { // assemble the device chunk string-set return chunk_set_type( uint32( chunk_end - chunk_begin ), string_set.base_string(), string_set.offsets() + chunk_begin ); } }; /// extract the given radix from the given suffixes of a string /// template <uint32 SYMBOL_SIZE, uint32 BITS, uint32 DOLLAR_BITS, typename string_type, typename index_iterator, typename radix_iterator> void flatten_string_suffixes( const uint64 string_len, const string_type& string, const uint32 word_idx, const index_iterator indices_begin, const index_iterator indices_end, radix_iterator radices) { typedef typename std::iterator_traits<radix_iterator>::value_type word_type; thrust::transform( indices_begin, indices_end, radices, string_suffix_word_functor<SYMBOL_SIZE, BITS, DOLLAR_BITS,string_type,word_type>( string_len, string, word_idx ) ); } /// A context class to perform suffix bucketing /// template <uint32 SYMBOL_SIZE, uint32 N_BITS, uint32 DOLLAR_BITS> struct StringSuffixBucketer { typedef uint32 word_type; StringSuffixBucketer() : d_setup_time(0.0f), d_flatten_time(0.0f), d_count_sort_time(0.0f), d_collect_sort_time(0.0f), d_remap_time(0.0f), d_copy_time(0.0f), d_filter_time(0.0f) {} /// count the number of suffixes falling in each bucket, where the buckets /// are defined by the first n_bits of the suffix /// template <typename suffix_iterator, typename string_type> void count( const uint32 n_suffixes, const suffix_iterator suffixes, const uint32 string_length, const string_type& string) { cuda::Timer timer; const uint32 n_buckets = 1u << (N_BITS); // initialize the temporary and output vectors alloc_storage( d_indices, n_suffixes * 2u ); alloc_storage( d_radices, n_suffixes * 2u ); alloc_storage( d_buckets, n_buckets ); timer.start(); // extract the first radix word from each of the suffixes flatten_string_suffixes<SYMBOL_SIZE, N_BITS,DOLLAR_BITS>( string_length, string, 0u, // load the first word suffixes, suffixes + n_suffixes, d_radices.begin() ); timer.stop(); d_flatten_time += timer.seconds(); timer.start(); // sort the radices so as to make binning easy cuda::SortBuffers<word_type*> sort_buffers; cuda::SortEnactor sort_enactor; sort_buffers.selector = 0; sort_buffers.keys[0] = nvbio::device_view( d_radices ); sort_buffers.keys[1] = nvbio::device_view( d_radices ) + n_suffixes; sort_enactor.sort( n_suffixes, sort_buffers, 0u, N_BITS ); //thrust::sort( d_radices.begin(), d_radices.begin() + n_suffixes ); timer.stop(); d_count_sort_time += timer.seconds(); // initialize the bucket counters thrust::fill( d_buckets.begin(), d_buckets.end(), 0u ); // compute the number of effectively used buckets looking at the last non-empty one const uint32 n_used_buckets = d_radices[ sort_buffers.selector * n_suffixes + n_suffixes-1 ] + 1u; // find the end of each bin of values thrust::upper_bound( d_radices.begin() + sort_buffers.selector * n_suffixes, d_radices.begin() + sort_buffers.selector * n_suffixes + n_suffixes, thrust::make_counting_iterator<uint32>(0u), thrust::make_counting_iterator<uint32>(0u) + n_used_buckets, d_buckets.begin() ); // compute the histogram by taking differences of the cumulative histogram thrust::adjacent_difference( d_buckets.begin(), d_buckets.begin() + n_used_buckets, d_buckets.begin()); } /// collect the suffixes falling in a given set of buckets, where the buckets /// are defined by the first n_bits of the suffix /// template <typename suffix_iterator, typename string_type, typename bucketmap_iterator, typename output_iterator> uint32 collect( const uint32 n_suffixes, const suffix_iterator suffixes, const uint64 string_length, const string_type& string, const uint32 bucket_begin, const uint32 bucket_end, const bucketmap_iterator bucketmap, output_iterator output_radices, output_iterator output_indices) { cuda::Timer timer; const uint32 n_buckets = 1u << N_BITS; // initialize the temporary and output vectors alloc_storage( d_indices, n_suffixes * 2u ); alloc_storage( d_radices, n_suffixes * 2u ); alloc_storage( d_buckets, n_buckets ); timer.start(); // extract the first radix word from each of the suffixes flatten_string_suffixes<SYMBOL_SIZE,N_BITS,DOLLAR_BITS>( string_length, string, 0u, // load the first word suffixes, suffixes + n_suffixes, d_radices.begin() ); timer.stop(); d_flatten_time += timer.seconds(); timer.start(); // determine if a radix is in the given bucket range const priv::in_range_functor in_range = priv::in_range_functor( bucket_begin, bucket_end ); // retain only suffixes whose radix is between the specified buckets const uint32 n_collected = cuda::copy_flagged( n_suffixes, thrust::make_zip_iterator( thrust::make_tuple( suffixes, d_radices.begin() ) ), thrust::make_transform_iterator( d_radices.begin(), in_range ), thrust::make_zip_iterator( thrust::make_tuple( d_indices.begin(), d_radices.begin() ) ) + n_suffixes, d_temp_storage ); timer.stop(); d_filter_time += timer.seconds(); timer.start(); // remap the collected radices thrust::gather( d_radices.begin() + n_suffixes, d_radices.begin() + n_suffixes + n_collected, bucketmap, d_radices.begin() + n_suffixes ); timer.stop(); d_remap_time += timer.seconds(); timer.start(); // sort the radices so as to make binning easy cuda::SortBuffers<word_type*,uint64*> sort_buffers; cuda::SortEnactor sort_enactor; sort_buffers.selector = 0; //#define SORT_BY_BUCKETS #if defined(SORT_BY_BUCKETS) sort_buffers.keys[0] = nvbio::device_view( d_radices ) + n_suffixes; sort_buffers.keys[1] = nvbio::device_view( d_radices ); sort_buffers.values[0] = (uint64*)nvbio::device_view( d_indices ) + buffer_stride; sort_buffers.values[1] = (uint64*)nvbio::device_view( d_indices ); sort_enactor.sort( n_collected, sort_buffers, 0u, N_BITS ); #endif timer.stop(); d_collect_sort_time += timer.seconds(); // // copy all the indices inside the range to the output // //alloc_storage( output_suffixes, n_suffixes ); //alloc_storage( output_radices, n_suffixes ); timer.start(); // the buffer selector had inverted semantics sort_buffers.selector = 1 - sort_buffers.selector; // and copy everything to the output thrust::copy( d_indices.begin() + sort_buffers.selector * n_suffixes, d_indices.begin() + sort_buffers.selector * n_suffixes + n_collected, output_indices ); // and copy everything to the output thrust::copy( d_radices.begin() + sort_buffers.selector * n_suffixes, d_radices.begin() + sort_buffers.selector * n_suffixes + n_collected, output_radices ); timer.stop(); d_copy_time += timer.seconds(); return n_collected; } thrust::device_vector<uint32> d_indices; thrust::device_vector<word_type> d_radices; thrust::device_vector<uint32> d_buckets; thrust::device_vector<uint8> d_temp_storage; float d_setup_time; float d_flatten_time; float d_count_sort_time; float d_collect_sort_time; float d_remap_time; float d_copy_time; float d_filter_time; }; // // A host-side radix extractor context // template <typename string_set_type, uint32 SYMBOL_SIZE, uint32 DOLLAR_BITS, uint32 WORD_BITS> struct HostStringSetRadices { HostStringSetRadices(const string_set_type string_set) : m_string_set( string_set ) {} /// return the number of words needed to represent a given string length /// uint32 num_words(const uint32 max_string_len) const { const uint32 SYMBOLS_PER_WORD = priv::symbols_per_word<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS>(); return (max_string_len + SYMBOLS_PER_WORD-1) / SYMBOLS_PER_WORD; } /// needed amount of device storage /// uint64 needed_device_memory(const uint32 n_suffixes) const { return n_suffixes * sizeof(uint8) + // d_symbols n_suffixes * sizeof(uint32); // d_active_suffixes } /// reserve any temporary space for the given amount of suffixes /// void reserve(const uint32 n_suffixes, const uint32 block_size) { try { d_active_suffixes.resize( n_suffixes ); d_symbols.resize( n_suffixes ); h_symbols.resize( n_suffixes ); h_active_suffixes.resize( n_suffixes ); m_block.resize( n_suffixes * block_size ); } catch (...) { log_error(stderr, "HostStringSetRadices::reserve() : allocation failed!\n"); throw; } } /// initialize the suffixes to extract /// void init(const uint32 n_suffixes, const uint2* _h_suffixes, const uint2* _d_suffixes) { m_suffixes = _h_suffixes; d_suffixes = thrust::device_ptr<const uint2>( _d_suffixes ); } /// initialize extraction of a slice of words /// void init_slice( const uint32 n_indices, const uint32* d_indices, const uint32 word_block_begin, const uint32 word_block_end) { try { if (d_indices == NULL) { // extract the given radix word from each of the partially sorted suffixes on the host priv::extract_radices( m_string_set, n_indices, word_block_begin, word_block_end, WORD_BITS, m_suffixes, &m_block[0], word_block_begin == 0 ? &h_symbols[0] : NULL ); // on the first iteration, load the BWT symbols too } else { // gather the list of active suffixes thrust::gather( thrust::device_ptr<const uint32>( d_indices ), thrust::device_ptr<const uint32>( d_indices ) + n_indices, d_suffixes, d_active_suffixes.begin() ); // copy the list of active suffixes to the host thrust::copy( d_active_suffixes.begin(), d_active_suffixes.begin() + n_indices, h_active_suffixes.begin() ); // extract the given radix word from each of the partially sorted suffixes on the host priv::extract_radices( m_string_set, n_indices, word_block_begin, word_block_end, WORD_BITS, &h_active_suffixes[0], &m_block[0] ); } } catch (...) { log_error(stderr, "HostStringSetRadices::init_slice() : exception caught!\n"); throw; } } /// extract the radices corresponding to a given word of the given suffixes /// /// \param n_indices the input number of suffixes /// \param d_indices a device vector of the indices to extract /// \param word_idx the word index to extract /// \param word_begin the beginning of the current slice range /// \param word_idx the end of the current slice range /// \param d_radices the destination device array to hold the output /// void extract( const uint32 n_indices, const uint32* d_indices, const uint32 word_idx, const uint32 word_block_begin, const uint32 word_block_end, uint32* d_radices) const { try { // and copy them to the device thrust::copy( m_block.begin() + n_indices * (word_idx - word_block_begin), m_block.begin() + n_indices * (word_idx - word_block_begin) + n_indices, thrust::device_ptr<uint32>( d_radices ) ); } catch (...) { log_error(stderr, "HostStringSetRadices::extract() : exception caught!\n"); throw; } } /// extract the bwt of the given block /// void dollar_bwt( const uint32 begin, const uint32 end, uint8* h_bwt) { const int n_strings = int( end - begin ); // fetch the BWT symbols for the given strings #pragma omp parallel for for (int i = 0; i < n_strings; ++i) { const priv::string_set_bwt_functor<string_set_type> bwt( m_string_set ); h_bwt[i] = bwt( i + begin ); } } /// extract the bwt of the given block /// void bwt( const uint32 n_suffixes, const uint32* d_indices, uint8* h_bwt, uint8* d_bwt) { try { if (d_indices != NULL) { #if 0 // fetch the BWT symbols for this block of suffixes #pragma omp parallel for for (int i = 0; i < n_suffixes; ++i) { const priv::string_set_bwt_functor<string_set_type> bwt( m_string_set ); h_symbols[i] = bwt( m_suffixes[i] ); } #endif #if 0 alloc_storage( m_block, n_suffixes ); // re-purpose the radix-block storage uint32* h_indices = &m_block[0]; // copy the sorted indices to the host thrust::copy( thrust::device_ptr<const uint32>( d_indices ), thrust::device_ptr<const uint32>( d_indices ) + n_suffixes, h_indices ); // and compute the bwt of the block by gathering the symbols in suffix-sorted order thrust::gather( h_indices, h_indices + n_suffixes, h_symbols.begin(), h_bwt ); #else alloc_storage( d_symbols, n_suffixes ); // copy the symbols to the device thrust::copy( h_symbols.begin(), h_symbols.begin() + n_suffixes, d_symbols.begin() ); // gather the symbols in proper order thrust::gather( thrust::device_ptr<const uint32>( d_indices ), thrust::device_ptr<const uint32>( d_indices ) + n_suffixes, d_symbols.begin(), thrust::device_ptr<uint8>( d_bwt ) ); // and copy the sorted symbols back to the host thrust::copy( thrust::device_ptr<uint8>( d_bwt ), thrust::device_ptr<uint8>( d_bwt ) + n_suffixes, h_bwt ); #endif } else { // fetch the BWT symbols for this block of suffixes #pragma omp parallel for for (int i = 0; i < n_suffixes; ++i) { const priv::string_set_bwt_functor<string_set_type> bwt( m_string_set ); h_bwt[i] = bwt( m_suffixes[i] ); } // and copy the sorted symbols back to the device thrust::copy( h_bwt, h_bwt + n_suffixes, thrust::device_ptr<uint8>( d_bwt ) ); } } catch (...) { log_error(stderr, "HostStringSetRadices::bwt() : exception caught!\n"); throw; } } /// return the amount of used device memory /// uint64 allocated_device_memory() const { return d_active_suffixes.size() * sizeof(uint2) + d_symbols.size() * sizeof(uint8); } /// return the amount of used device memory /// uint64 allocated_host_memory() const { return m_block.size() * sizeof(uint2) + h_active_suffixes.size() * sizeof(uint2) + h_symbols.size() * sizeof(uint8); } string_set_type m_string_set; const uint2* m_suffixes; thrust::device_ptr<const uint2> d_suffixes; thrust::device_vector<uint2> d_active_suffixes; thrust::device_vector<uint8> d_symbols; thrust::host_vector<uint2> h_active_suffixes; thrust::host_vector<uint8> h_symbols; thrust::host_vector<uint32> m_block; }; // // A host-side radix extractor context // template <typename string_set_type, uint32 SYMBOL_SIZE, uint32 DOLLAR_BITS, uint32 WORD_BITS> struct DeviceStringSetRadices { DeviceStringSetRadices() {} DeviceStringSetRadices(const string_set_type string_set) : m_string_set( string_set ) {} /// return the number of words needed to represent a given string length /// uint32 num_words(const uint32 max_string_len) const { const uint32 SYMBOLS_PER_WORD = priv::symbols_per_word<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS>(); return (max_string_len + SYMBOLS_PER_WORD-1) / SYMBOLS_PER_WORD; } /// needed amount of device storage /// uint64 needed_device_memory(const uint32 n_suffixes) const { return n_suffixes; // d_symbols } /// reserve any temporary space for the given amount of suffixes /// void reserve(const uint32 n_suffixes, const uint32 slice_size) { d_symbols.resize( n_suffixes ); } /// set string set /// void set(const string_set_type string_set) { m_string_set = string_set; } /// initialize the suffixes to extract /// void init(const uint32 n_suffixes, const uint2* _h_suffixes, const uint2* _d_suffixes) { d_suffixes = thrust::device_ptr<const uint2>( _d_suffixes ); } /// initialize extraction of a slice of words /// void init_slice( const uint32 n_indices, const uint32* d_indices, const uint32 word_block_begin, const uint32 word_block_end) {} /// extract the radices corresponding to a given word of the given suffixes /// /// \param n_indices the input number of suffixes /// \param d_indices a device vector of the indices to extract /// \param word_idx the word index to extract /// \param word_begin the beginning of the current slice range /// \param word_idx the end of the current slice range /// \param d_radices the destination device array to hold the output /// void extract( const uint32 n_indices, const uint32* d_indices, const uint32 word_idx, const uint32 word_block_begin, const uint32 word_block_end, uint32* d_radices) const { // extract the given radix word from each of the partially sorted suffixes in a device temp buffer priv::local_set_suffix_word_functor<SYMBOL_SIZE,WORD_BITS,DOLLAR_BITS,string_set_type,uint32> word_functor( m_string_set, word_idx ); if (d_indices == NULL) { thrust::copy( thrust::make_transform_iterator( d_suffixes, word_functor ), thrust::make_transform_iterator( d_suffixes, word_functor ) + n_indices, thrust::device_ptr<uint32>( d_radices ) ); } else { thrust::copy( thrust::make_transform_iterator( thrust::make_permutation_iterator( d_suffixes, thrust::device_ptr<const uint32>( d_indices ) ), word_functor ), thrust::make_transform_iterator( thrust::make_permutation_iterator( d_suffixes, thrust::device_ptr<const uint32>( d_indices ) ), word_functor ) + n_indices, thrust::device_ptr<uint32>( d_radices ) ); } } /// extract the bwt of the given block /// void dollar_bwt( const uint32 begin, const uint32 end, uint8* h_bwt) { const int n_strings = end - begin; alloc_storage( d_symbols, n_strings ); // fetch the BWT symbols for the given strings thrust::transform( thrust::make_counting_iterator<uint32>(begin), thrust::make_counting_iterator<uint32>(end), d_symbols.begin(), priv::string_set_bwt_functor<string_set_type>( m_string_set ) ); // and copy the result to the host thrust::copy( d_symbols.begin(), d_symbols.begin() + n_strings, h_bwt ); } /// extract the bwt of the given block /// void bwt( const uint32 n_suffixes, const uint32* d_indices, uint8* h_bwt, uint8* d_bwt) { if (d_indices != NULL) { alloc_storage( d_symbols, n_suffixes ); // fetch the BWT symbols for this block of suffixes thrust::transform( d_suffixes, d_suffixes + n_suffixes, d_symbols.begin(), priv::string_set_bwt_functor<string_set_type>( m_string_set ) ); // and compute the bwt of the block by gathering the symbols in suffix-sorted order thrust::gather( thrust::device_ptr<const uint32>( d_indices ), thrust::device_ptr<const uint32>( d_indices ) + n_suffixes, d_symbols.begin(), thrust::device_ptr<uint8>( d_bwt ) ); } else { // fetch the BWT symbols for this block of suffixes thrust::transform( d_suffixes, d_suffixes + n_suffixes, thrust::device_ptr<uint8>( d_bwt ), priv::string_set_bwt_functor<string_set_type>( m_string_set ) ); } // and copy the result to the host thrust::copy( thrust::device_ptr<uint8>( d_bwt ), thrust::device_ptr<uint8>( d_bwt ) + n_suffixes, h_bwt ); } /// return the amount of used device memory /// uint64 allocated_device_memory() const { return d_symbols.size() * sizeof(uint8); } /// return the amount of used device memory /// uint64 allocated_host_memory() const { return 0u; } string_set_type m_string_set; thrust::device_ptr<const uint2> d_suffixes; thrust::device_vector<uint8> d_symbols; }; /// Collect dollar symbols out of a BWT + SA block /// struct DollarExtractor { /// constructor /// DollarExtractor() : offset(0), n_dollars(0) {} /// process a batch of BWT symbols /// uint32 extract( const uint32 n_suffixes, const uint8* h_bwt, const uint8* d_bwt, const uint2* h_suffixes, const uint2* d_suffixes, const uint32* d_indices); uint64 offset; uint32 n_dollars; thrust::device_vector<uint64> d_dollar_ranks; thrust::device_vector<uint32> d_dollar_indices; thrust::device_vector<uint64> d_dollars; thrust::host_vector<uint64> h_dollar_ranks; thrust::host_vector<uint64> h_dollars; thrust::device_vector<uint8> d_temp_storage; }; // ------------------------------------------------------------------------------------------------------------- // // the following functions implement device_copy() and device_scatter() - special-purpose functions to copy // and scatter a set of symbols to a packed stream. // ------------------------------------------------------------------------------------------------------------- // /// a simple auxiliary kernel to perform generic device-to-device copies, specialized for packed streams /// template <typename input_iterator, typename output_iterator, typename index_type> __global__ void simple_device_copy_kernel( const uint32 n, const input_iterator input, output_iterator output, const index_type offset) { const uint32 thread_id = threadIdx.x + blockIdx.x*blockDim.x; if (thread_id < n) output[offset + thread_id] = input[thread_id]; } /// a simple auxiliary kernel to perform generic device-to-device copies, specialized for packed streams /// template <typename input_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type> __global__ void packed_device_copy_kernel( const uint32 n, const input_iterator input, PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output, const index_type offset) { const uint32 thread_id = threadIdx.x + blockIdx.x*blockDim.x; // // care must be used to avoid write-conflicts, hence we assign all symbols belonging // to the same output word to a single thread // typedef typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::storage_type word_type; const uint32 SYMBOLS_PER_WORD = (8u*sizeof(word_type))/SYMBOL_SIZE; const uint32 word_offset = uint32( (offset + output.index()) & (SYMBOLS_PER_WORD-1) ); const uint32 elem_begin = thread_id ? (thread_id+0) * SYMBOLS_PER_WORD - word_offset : 0u; const uint32 elem_end = nvbio::min( (thread_id+1) * SYMBOLS_PER_WORD - word_offset, n ); if (elem_begin < n) { for (uint32 i = elem_begin; i < elem_end; ++i) output[offset+i] = input[i]; } } /// a dispatcher for device_copy /// template <typename input_iterator, typename output_iterator, typename index_type> struct device_copy_dispatch { /// copy n elements from the input stream to the output /// static void copy( const uint32 n, const input_iterator input, const output_iterator output, const index_type offset) { const uint32 batch_size = cuda::max_grid_size(); for (uint32 batch_begin = 0; batch_begin < n; batch_begin += batch_size) { const uint32 batch_end = nvbio::min( batch_begin + batch_size, n ); const uint32 blockdim = 128; const uint32 n_blocks = util::divide_ri( batch_end - batch_begin, blockdim ); simple_device_copy_kernel<<<n_blocks,blockdim>>>( n, input, output, offset ); } } }; /// a dispatcher for device_copy /// template <typename input_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type> struct device_copy_dispatch< input_iterator, PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>, index_type> { typedef PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output_iterator; /// copy n elements from the input stream to the output /// static void copy( const uint32 n, const input_iterator input, const output_iterator output, const index_type offset) { typedef typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::storage_type word_type; const uint32 SYMBOLS_PER_WORD = (8u*sizeof(word_type))/SYMBOL_SIZE; const uint32 batch_size = cuda::max_grid_size(); for (uint32 batch_begin = 0; batch_begin < n; batch_begin += batch_size) { const uint32 batch_end = nvbio::min( batch_begin + batch_size, n ); const uint32 blockdim = 128; const uint32 n_words = util::divide_ri( batch_end - batch_begin, SYMBOLS_PER_WORD ) + 1u; const uint32 n_blocks = util::divide_ri( n_words, blockdim ); packed_device_copy_kernel<<<n_blocks,blockdim>>>( batch_end - batch_begin, input, output, offset + batch_begin ); } } }; /// copy a set of n symbols from a given input stream to a given output stream /// template <typename input_iterator, typename output_iterator, typename index_type> void device_copy( const uint32 n, const input_iterator input, const output_iterator output, const index_type offset) { device_copy_dispatch<input_iterator,output_iterator,index_type>::copy( n, input, output, offset ); } /// an auxiliary kernel to scatter a set of symbols into a sparse set of slots of a given output stream; /// this kernel copies a full range of symbols per thread, where individual ranges are guaranteed to /// touch distinct words of the underlying storage where the output is packed. /// template <typename input_iterator, typename slot_iterator, typename range_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type> __global__ void device_scatter_kernel( const uint32 begin, const uint32 end, const range_iterator ranges, const input_iterator input, const slot_iterator slots, PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output) { const uint32 thread_id = threadIdx.x + blockIdx.x*blockDim.x; const uint32 idx = thread_id + begin; if (idx >= end) return; // // care must be used to avoid write-conflicts, hence we assign all symbols belonging // to the same output word to a single thread // const uint32 elem_begin = idx ? ranges[ idx-1 ] : 0u; const uint32 elem_end = ranges[ idx ]; for (uint32 i = elem_begin; i < elem_end; ++i) { const uint32 slot = slots[i]; output[ slot ] = input[i]; } } /// scatter a set of symbols into a sparse set of slots of a given output stream /// template <typename input_iterator, typename slot_iterator, typename output_iterator> struct device_scatter_dispatch { static void enact( const uint32 n, const input_iterator input, const slot_iterator slots, output_iterator output) { thrust::scatter( input, input + n, slots, output ); } }; /// scatter a set of symbols into a sparse set of slots of a given output stream /// template <typename input_iterator, typename slot_iterator, typename storage_type, uint32 SYMBOL_SIZE, bool BIG_ENDIAN, typename index_type> struct device_scatter_dispatch< input_iterator, slot_iterator, PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> > { typedef PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type> output_iterator; static void enact( const uint32 n, const input_iterator input, const slot_iterator slots, output_iterator output) { // find out a set of ranges of input symbols covering distinct words in the output: this is done // looking at the words covered by each of the symbols, and reducing together all symbols falling // in the same word. thrust::device_vector<uint32> d_ranges( n ); thrust::device_vector<uint32> d_keys( n ); typedef typename PackedStream<storage_type,uint8,SYMBOL_SIZE,BIG_ENDIAN,index_type>::storage_type word_type; const uint32 SYMBOLS_PER_WORD = (8u*sizeof(word_type))/SYMBOL_SIZE; const uint32 n_ranges = uint32( thrust::reduce_by_key( thrust::make_transform_iterator( slots, add_divide_functor( output.index(), SYMBOLS_PER_WORD ) ), thrust::make_transform_iterator( slots + n, add_divide_functor( output.index(), SYMBOLS_PER_WORD ) ), thrust::make_counting_iterator<uint32>(1u), d_keys.begin(), d_ranges.begin(), thrust::equal_to<uint32>(), thrust::maximum<uint32>() ).first - d_keys.begin() ); const uint32 batch_size = cuda::max_grid_size(); for (uint32 batch_begin = 0; batch_begin < n_ranges; batch_begin += batch_size) { const uint32 batch_end = nvbio::min( batch_begin + batch_size, n_ranges ); // at this point we can scatter the identified ranges const uint32 blockdim = 128; const uint32 n_blocks = util::divide_ri( batch_end - batch_begin, blockdim ); device_scatter_kernel<<<n_blocks,blockdim>>>( batch_begin, batch_end, d_ranges.begin(), input, slots, output ); } } }; /// scatter a set of symbols into a sparse set of slots of a given output stream /// template <typename input_iterator, typename slot_iterator, typename output_iterator> void device_scatter( const uint32 n, const input_iterator input, const slot_iterator slots, output_iterator output) { device_scatter_dispatch<input_iterator,slot_iterator,output_iterator>::enact( n, input, slots, output ); } // ------------------------------------------------------------------------------------------------------------- // /// pack a set of head flags into a bit-packed array /// void pack_flags( const uint32 n, const uint8* flags, uint32* comp_flags); /// build a set of head flags looking at adjacent keys /// void build_head_flags( const uint32 n, const uint32* keys, uint8* flags); /// build a set of head flags looking at adjacent keys /// void build_head_flags( const uint32 n, const uint64* keys, uint8* flags); } // namespace priv } // namespace nvbio
{ "content_hash": "bba3fb2158221f039fa2af87800b9d8f", "timestamp": "", "source": "github", "line_count": 2264, "max_line_length": 184, "avg_line_length": 36.68330388692579, "alnum_prop": 0.579354854246186, "repo_name": "kimrutherford/nvbio", "id": "3d5a076cedbfb9715e23ca2fdccd151d24d4e6ac", "size": "84642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nvbio/sufsort/sufsort_priv.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1954907" }, { "name": "C++", "bytes": "4691483" }, { "name": "CMake", "bytes": "28412" }, { "name": "CSS", "bytes": "8196" }, { "name": "Cuda", "bytes": "3330740" }, { "name": "DIGITAL Command Language", "bytes": "26402" }, { "name": "Groff", "bytes": "15599" }, { "name": "HTML", "bytes": "2497" }, { "name": "Makefile", "bytes": "38913" }, { "name": "Perl", "bytes": "3895" } ], "symlink_target": "" }
using System.Collections.Generic; using Azure.Core; namespace Azure.ResourceManager.Chaos.Models { /// <summary> The information of the experiment run. </summary> internal partial class ExperimentExecutionDetailsPropertiesRunInformation { /// <summary> Initializes a new instance of ExperimentExecutionDetailsPropertiesRunInformation. </summary> internal ExperimentExecutionDetailsPropertiesRunInformation() { Steps = new ChangeTrackingList<StepStatus>(); } /// <summary> Initializes a new instance of ExperimentExecutionDetailsPropertiesRunInformation. </summary> /// <param name="steps"> The steps of the experiment run. </param> internal ExperimentExecutionDetailsPropertiesRunInformation(IReadOnlyList<StepStatus> steps) { Steps = steps; } /// <summary> The steps of the experiment run. </summary> public IReadOnlyList<StepStatus> Steps { get; } } }
{ "content_hash": "b720c9f62a95ad258e7ddb6a89e14c8f", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 114, "avg_line_length": 39.4, "alnum_prop": 0.6994923857868021, "repo_name": "Azure/azure-sdk-for-net", "id": "7523e41058d9cec6a34216e43b58f91904a60355", "size": "1123", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/chaos/Azure.ResourceManager.Chaos/src/Generated/Models/ExperimentExecutionDetailsPropertiesRunInformation.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.gemstone.gemfire.internal.tools.gfsh.app.command.task; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import com.gemstone.gemfire.cache.Cache; import com.gemstone.gemfire.cache.CacheFactory; import com.gemstone.gemfire.cache.Region; import com.gemstone.gemfire.internal.tools.gfsh.command.CommandResults; import com.gemstone.gemfire.internal.tools.gfsh.command.CommandTask; import com.gemstone.gemfire.internal.tools.gfsh.util.RegionUtil; /** * RegionPathTask retrieves an entire list of region paths in the connected * server or in the entire distributed system in which the connected server * belongs. */ public class RegionPathTask implements CommandTask { private static final long serialVersionUID = 1L; private boolean regionsInDistributedSystem = false; private boolean recursive = true; private String parentRegionPath = null; /** * Returns all region paths in the entire distributed system. This * constructor call is equivalent to new RegonPathTask(true, true, null); */ public RegionPathTask() { } /** * Returns all region paths starting from the top level. * * @param regionsInDistributedSystem * if false, returns all region paths found in the cache. If * true, returns all region paths found in the entire distributed * system. * @param recursive * if true, returns all nested region paths, otherwise, returns * the top-level region paths */ public RegionPathTask(boolean regionsInDistributedSystem, boolean recursive) { this(regionsInDistributedSystem, recursive, null); } /** * @param regionsInDistributedSystem * if false, returns all region paths found in the cache. If * true, returns all region paths found in the entire distributed * system. * @param recursive * if true, returns all nested region paths, otherwise, returns * the top-level region paths * @param parentRegionPath * the parent region path */ public RegionPathTask(boolean regionsInDistributedSystem, boolean recursive, String parentRegionPath) { this.regionsInDistributedSystem = regionsInDistributedSystem; this.recursive = recursive; this.parentRegionPath = parentRegionPath; } public CommandResults runTask(Object userData) { String[] regionPaths = null; Cache cache = CacheFactory.getAnyInstance(); if (regionsInDistributedSystem) { // get region paths defined in this cache only if (parentRegionPath == null) { regionPaths = RegionUtil.getAllRegionPaths(CacheFactory.getAnyInstance(), recursive); } else { Region region = cache.getRegion(parentRegionPath); if (region != null) { regionPaths = RegionUtil.getAllRegionPaths(region, recursive); } } } else { // get region paths defined in all of the caches in the distributed // system if (parentRegionPath == null) { regionPaths = RegionUtil.getAllRegionPathsInDistributedSystem(cache.getDistributedSystem(), recursive); } else { Region region = cache.getRegion(parentRegionPath); if (region != null) { regionPaths = RegionUtil.getAllRegionPaths(region, recursive); } } } CommandResults results = new CommandResults(regionPaths); return results; } public boolean isRegionsInDistributedSystem() { return regionsInDistributedSystem; } public void setRegionsInDistributedSystem(boolean regionsInDistributedSystem) { this.regionsInDistributedSystem = regionsInDistributedSystem; } public boolean isRecursive() { return recursive; } public void setRecursive(boolean recursive) { this.recursive = recursive; } public String getParentRegionPath() { return parentRegionPath; } public void setParentRegionPath(String parentRegionPath) { this.parentRegionPath = parentRegionPath; } public void fromData(DataInput input) throws IOException, ClassNotFoundException { regionsInDistributedSystem = input.readBoolean(); recursive = input.readBoolean(); parentRegionPath = input.readUTF(); if (parentRegionPath.equals("\0")) { parentRegionPath = null; } } public void toData(DataOutput output) throws IOException { output.writeBoolean(regionsInDistributedSystem); output.writeBoolean(recursive); if (parentRegionPath == null) { output.writeUTF("\0"); } else { output.writeUTF(parentRegionPath); } } }
{ "content_hash": "d2be5889fc30a4c70a57e5a62447e7ac", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 107, "avg_line_length": 28.286624203821656, "alnum_prop": 0.7333933798693988, "repo_name": "SnappyDataInc/snappy-store", "id": "ba3ffd6d760fabed1297f8941005592975ca5f65", "size": "5106", "binary": false, "copies": "3", "ref": "refs/heads/snappy/master", "path": "gemfire-core/src/main/java/com/gemstone/gemfire/internal/tools/gfsh/app/command/task/RegionPathTask.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AGS Script", "bytes": "90653" }, { "name": "Assembly", "bytes": "738033" }, { "name": "Batchfile", "bytes": "23509" }, { "name": "C", "bytes": "298655" }, { "name": "C#", "bytes": "1338285" }, { "name": "C++", "bytes": "784695" }, { "name": "CSS", "bytes": "54987" }, { "name": "Gnuplot", "bytes": "3125" }, { "name": "HTML", "bytes": "8595527" }, { "name": "Java", "bytes": "117988027" }, { "name": "JavaScript", "bytes": "33027" }, { "name": "Makefile", "bytes": "9359" }, { "name": "Mathematica", "bytes": "92588" }, { "name": "PHP", "bytes": "869892" }, { "name": "PLSQL", "bytes": "80858" }, { "name": "PLpgSQL", "bytes": "205179" }, { "name": "Pascal", "bytes": "3707" }, { "name": "Pawn", "bytes": "93609" }, { "name": "Perl", "bytes": "196843" }, { "name": "Python", "bytes": "131049" }, { "name": "Ruby", "bytes": "26443" }, { "name": "SQLPL", "bytes": "47702" }, { "name": "Shell", "bytes": "550962" }, { "name": "SourcePawn", "bytes": "15059" }, { "name": "TSQL", "bytes": "5461819" }, { "name": "Thrift", "bytes": "55057" }, { "name": "XSLT", "bytes": "67112" }, { "name": "sed", "bytes": "6411" } ], "symlink_target": "" }
using System.Collections.Generic; using CefSharp; using TweetImpl.CefSharp.Adapters; using TweetImpl.CefSharp.Dialogs; using TweetLib.Browser.CEF.Dialogs; using TweetLib.Browser.CEF.Logic; using static TweetLib.Browser.CEF.Dialogs.FileDialogType; namespace TweetImpl.CefSharp.Handlers { sealed class CefFileDialogHandler : IDialogHandler { private readonly DialogHandlerLogic<IFileDialogCallback> logic; public CefFileDialogHandler() { this.logic = new DialogHandlerLogic<IFileDialogCallback>(FileDialogOpener.Instance, CefFileDialogCallbackAdapter.Instance); } public bool OnFileDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, CefFileDialogMode mode, string title, string defaultFilePath, List<string> acceptFilters, IFileDialogCallback callback) { return logic.OnFileDialog(ConvertDialogType(mode), acceptFilters, callback); } private static FileDialogType ConvertDialogType(CefFileDialogMode mode) { return mode switch { CefFileDialogMode.Open => Open, CefFileDialogMode.OpenMultiple => OpenMultiple, _ => Other }; } } }
{ "content_hash": "d55f88fa7ba5dfe3f849d18d94424c59", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 198, "avg_line_length": 38.41379310344828, "alnum_prop": 0.77737881508079, "repo_name": "chylex/TweetDuck", "id": "f496892c86119896eb224be53bf60bf2cd36112f", "size": "1114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "windows/TweetImpl.CefSharp/Handlers/CefFileDialogHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "122" }, { "name": "C#", "bytes": "568526" }, { "name": "CSS", "bytes": "101678" }, { "name": "F#", "bytes": "43385" }, { "name": "HTML", "bytes": "46603" }, { "name": "Inno Setup", "bytes": "17552" }, { "name": "JavaScript", "bytes": "198552" }, { "name": "PowerShell", "bytes": "1856" }, { "name": "Shell", "bytes": "795" } ], "symlink_target": "" }
<div class="row-fluid"> <div class="col-md-offset-3 col-md-6"> <h3>Registro de Usuário</h3> <form (submit)="save()" *ngIf="user"> <div class="form-group"> <label class="label-control" for="firstname">Nome</label> <input class="form-control" type="text" id="firstname" name="firstname" [(ngModel)]="user.firstname" required #ctrl="ngModel"> </div> <div class="form-group"> <label class="label-control" for="lastname">Ultimo nome</label> <input class="form-control" type="text" id="lastname" name="lastname" [(ngModel)]="user.lastname" #ctrl="ngModel"> </div> <div class="form-group"> <label class="label-control" for="email">Email</label> <input class="form-control" type="email" id="email" name="email" [(ngModel)]="user.email" required #ctrl="ngModel"> </div> <div class="form-group"> <label class="label-control" for="password">Senha</label> <input class="form-control" type="password" id="password" name="password" [(ngModel)]="user.password" required #ctrl="ngModel"> </div> <div class="form-group"> <label class="label-control" for="confirmPassword">Confirmar senha</label> <input class="form-control" type="password" id="confirmPassword" name="firstname" [(ngModel)]="user.confirmPassword" required #ctrl="ngModel"> </div> <div class="text-right"> <button type="button" class="btn btn-fab btn-warning" (click)="goBack()"> <i class="material-icons">undo</i> </button> <button type="submit" class="btn btn-fab btn-primary"> <i class="material-icons">send</i> </button> </div> </form> </div> </div>
{ "content_hash": "fbd9967696ad8c873fee342cf534633a", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 82, "avg_line_length": 33.854838709677416, "alnum_prop": 0.5021438780371605, "repo_name": "rodrigopmatias/kanban-task", "id": "3766a378502d90ccb4ccb0e4130f10253b7ca7ec", "size": "2101", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/user.component/register-form.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "180" }, { "name": "HTML", "bytes": "11377" }, { "name": "JavaScript", "bytes": "24692" }, { "name": "TypeScript", "bytes": "11071" } ], "symlink_target": "" }
from MAT.PluginMgr import PluginTaskDescriptor, \ PluginError, FindPluginClass, PluginStep, TagStep, WholeZoneStep from MAT.PluginDocInstaller import PluginDocInstaller from ReplacementEngine import PIIReplacementEngine, DOC_CACHE_SCOPE, \ BATCH_CACHE_SCOPE, NO_CACHE_SCOPE from ClearReplacementStrategy import ClearRenderingStrategy from MAT import Error from MAT.Workspace import WorkspaceOperation, WorkspaceError, WorkspaceFolder, \ CMDLINE_DEBUG_AVAILABLE, UI_AVAILABLE, NOT_AVAILABLE, CMDLINE_AVAILABLE, \ CoreWorkspaceFolder, Workspace, \ MATEngineExecutionWorkspaceOperationMixin from MAT.WorkspaceDB import WorkspaceDB from MAT.Operation import OpArgument from MAT.Score import AggregatorScoreColumn, FileAggregateScoreRow, BaseScoreRow, Formula import os # Used way below, in augmentTagSummaryScoreTable etc. class DocConfidence(Formula): def __init__(self, header): self.header = header def render(self, scoreTable, separator = None): return self.compute() def compute(self): # So I've passed in None below, just to trigger # the capture of the file row. fileRow, ignore = self.header doc = fileRow.hypDoc # Let's see if there's any confidence info here. # This will work with Carafe, probably nothing else. seqConfidences = doc.getAnnotations(["seq_confidence"]) if not seqConfidences: return None return reduce(lambda x, y: x * y, [float(a["posterior"]) for a in seqConfidences]) # I limit this to just completed documents, unless specified. class RedactionOperation(WorkspaceOperation): name = "redact" argList = [OpArgument("replacer", help = "specify the replacer to use for this redaction (optional; obligatory if no replacer is specified in the task.xml file)", hasArg = True), OpArgument("retain_existing", help = "don't clear the redacted folders first"), OpArgument("dont_limit_to_gold", help = "under normal circumstances, the redaction will apply only to gold and reconciled documents. If this flag is present, it applies to all documents.")] def getAffectedFolders(self): return ["redacted, rich", "redacted, raw"] def getTargetFolderAndDocuments(self): return "redacted, rich", self._getTargetDocuments("redacted, rich") def do(self, replacer = None, retain_existing = False, dont_limit_to_gold = False): # Clear the redacted folders. Run the engine. operationSettings = self.getOperationSettings() if operationSettings is None: raise WorkspaceError, ("no operation settings in task '%s' for operation '%s'" % (self.folder.workspace.task.name, self.name)) operationSettings = operationSettings.copy() # Now, we've got our settings. At least workflow and steps are defined. try: workflow = operationSettings["workflow"] except KeyError: raise WorkspaceError, ("workflow undefined in tag prep operation settings") if replacer is not None: operationSettings["replacer"] = replacer elif not operationSettings.has_key("replacer"): raise WorkspaceError, "no replacer specified in operation settings or command" del operationSettings["workflow"] rawFolder = self.folder.workspace.folders['redacted, raw'] richFolder = self.folder.workspace.folders['redacted, rich'] if not retain_existing: rawFolder.clear() richFolder.clear() if not dont_limit_to_gold: # Find the documents which are completed, and only use those. self.affectedBasenames = [r[1] for r in self.folder.workspace.getDB().basenameInfo(self.affectedBasenames) if r[2] in ("reconciled", "gold")] allPaths = self.folder.getFiles(self.affectedBasenames) try: import MAT.ToolChain e = MAT.ToolChain.MATEngine(workflow = workflow, task = self.folder.workspace.task.name) # I'd forced this to be debug = True, back when I was passing debug all over the place. # At this point, we're going to have to go with the less informative message. dataPairs = e.Run(inputFileList = allPaths, input_file_type = "mat-json", **operationSettings) except Exception, e: raise WorkspaceError, str(e) # If this succeeds, I should write all the files to # the appropriate folder. for file, output in dataPairs: richFolder.saveFile(output, os.path.basename(file)) rawFolder.saveFile(output, os.path.basename(file)) def webResult(self): d = WorkspaceOperation.webResult(self) # We want the document status to be something consistent. # It doesn't really matter what the actual status is. # The folder listing will reveal no # basename info for the target folder, so I don't need to hack that too. if d.has_key("status"): del d["status"] return d # The only reason I need this is because I need to be able to review # nominations in workspaces. Grrr. # Because this requires a lock ID, etc., I'm replacing it with something very similar # to autotag. class NominationOperation(WorkspaceOperation, MATEngineExecutionWorkspaceOperationMixin): name = "nominate" argList = [OpArgument("replacer", help = "specify the replacer to use for this nomination (optional; obligatory if no replacer is specified in the task.xml file)", hasArg = True), OpArgument("dont_limit_to_gold", help = "under normal circumstances, the nomination will apply only to gold and reconciled documents. If this flag is present, it applies to all documents."), OpArgument("lock_id", hasArg = True, help="lock ID (if document is locked)")] def getAffectedFolders(self): return ["nominated"] def getTargetFolderAndDocuments(self): # Cache the target documents, so I don't open them # again when I lock in webResult(). self.targetDocuments = self._getTargetDocuments("nominated") return "nominated", self.targetDocuments def getAffectedFileBasenames(self): if hasattr(self, "affectedFileBasename"): return {self.affectedFileBasename: self.affectedBasenames[0]} else: return WorkspaceOperation.getAffectedFileBasenames(self) def allPaths(self): if not self.dont_limit_to_gold: # Find the documents which are completed, and only use those. if hasattr(self, "affectedFileBasename"): paths = [os.path.join(self.folder.dir, p[0]) for p in self.folder.workspace.getDB().basenameInfo(self.affectedBasenames) if p[0] == self.affectedFileBasename and p[2] in ("reconciled", "gold")] else: paths = [os.path.join(self.folder.dir, r[0]) for r in self.folder.workspace.getDB().basenameInfo(self.affectedBasenames) if r[2] in ("reconciled", "gold")] elif hasattr(self, "affectedFileBasename"): paths = [os.path.join(self.folder.dir, self.affectedFileBasename)] else: paths = self.folder.getFiles(self.affectedBasenames) return paths # lock_id is only # used from the UI. If the requested basenames have a lock that doesn't # match the lock ID, you can't do anything. # This lock_id is for the CORE. So if the lock is there, it's just used to # determine the source file, and whether to lock the output. But # we need to check the target locks the same way we do for autotag. def do(self, checkPathsAffected = True, lock_id = None, replacer = None, dont_limit_to_gold = False): self.replacer = replacer self.dont_limit_to_gold = dont_limit_to_gold db = self.folder.workspace.getDB() # If there's a lock_id, there better be only one affected basename. if lock_id and len(self.affectedBasenames) != 1: raise WorkspaceError, "lock_id requires exactly one affected basename" nominationLockInfo = db.nominationLockInfo() if nominationLockInfo and (lock_id is None): # In this situation, we can't proceed. raise WorkspaceError, "can't nominate while documents are locked" if lock_id: # First, see if that file in the nomination folder is already locked. idInfo = db.coreGetLockIDInfo(lock_id) if [p for p in nominationLockInfo if p[0] == idInfo[0]]: raise WorkspaceError, "can't nominate while documents are locked" # Otherwise, make sure that the affected file basenames are just # the one for the lock info. self.affectedFileBasename = idInfo[0] self.lockingUser = idInfo[2] t = self.folder.workspace.beginTransaction(self) self.transaction = t try: self._do(checkPathsAffected = checkPathsAffected) t.commit() except: t.rollback() raise def _do(self, checkPathsAffected = True): try: MATEngineExecutionWorkspaceOperationMixin.do(self, checkPathsAffected = checkPathsAffected) except: raise def getRunParameters(self, operationSettings): replacer = self.replacer or operationSettings.get("replacer") if replacer is None: raise WorkspaceError, "no replacer specified in operation settings or command" # In order to process the command lines really correctly, we # pass the operationSettings to an XMLOpArgumentAggregator. for key in ["input_file", "input_file_type", "output_file", "output_dir", "input_file_re", "input_encoding", "input_dir", "output_file_type", "output_encoding", "output_fsuff"]: if operationSettings.has_key(key): raise WorkspaceError, ("workspace operation settings don't permit %s option to MATEngine", key) return {"input_file_type": self.folder.fileType, "input_encoding": "utf-8", "replacer": replacer} def wrapup(self, dataPairs): nominationFolder = self.folder.workspace.folders['nominated'] db = self.folder.workspace.getDB() # Next, we'd better check to make sure that we can write each file. # If we can't, we want to raise an error. We should check each # individual file, because we don't want ANYthing to happen # if the writes can fail. if not os.access(nominationFolder.dir, os.W_OK | os.X_OK): raise WorkspaceError, "folder nominated not available for writing" self.transaction.addFilesToAdd([os.path.join(nominationFolder.dir, os.path.basename(p)) for (p, iData) in dataPairs]) for p, iData in dataPairs: fileBasename = os.path.basename(p) if not os.access(os.path.join(nominationFolder.dir, p), os.W_OK): raise WorkspaceError, ("file %s in folder nominated not available for writing" % fileBasename) nominationFolder.saveFile(iData, fileBasename) def webResult(self): d = WorkspaceOperation.webResult(self) if d.get("basename"): nominationFolder = self.folder.workspace.folders['nominated'] basename, fileBasename, doc = self.targetDocuments[0] ignore, fileBasename, lockId = self.folder.workspace._openFileBasename(nominationFolder, fileBasename, self.lockingUser, False, doc = doc) d["lock_id"] = lockId # We want the document status to be something consistent. # It doesn't really matter what the actual status is. # The folder listing will reveal no # basename info for the target folder, so I don't need to hack that too. if d.has_key("status"): del d["status"] return d class NominationReleaseLockOperation(WorkspaceOperation): name = "release_lock" availability = NOT_AVAILABLE argList = [OpArgument("lock_id", hasArg = True, help="lock ID")] def do(self, lock_id = None): _in_transaction = self.transaction if lock_id is None: raise WorkspaceError, "Can't release a lock without an ID" db = self.folder.workspace.getDB() # I'm wrapping this because I don't know whether this # operation is going to remain atomic. if _in_transaction: self._do(db, lock_id) else: t = self.folder.workspace.beginTransaction(self) try: self._do(db, lock_id) t.commit() except: t.rollback() raise def _do(self, db, lock_id): db.unlockNominationLock(lock_id) class NominationForceUnlockOperation(WorkspaceOperation): name = "force_unlock" availability = CMDLINE_AVAILABLE argList = [OpArgument("user", hasArg = True, help = "the user who's locked the basename")] def do(self, user = None): if user is None: raise WorkspaceError, "can't force unlock a basename without a user" t = self.folder.workspace.beginTransaction(self) try: self._do(user) t.commit() except: t.rollback() raise def _do(self, user): db = self.folder.workspace.getDB() unlocked = db.forceUnlockNominationBasenames(user, self.affectedBasenames) if self.fromCmdline: if unlocked: print "Unlocked core documents:", " ".join(unlocked) else: print "Unlocked no documents." class NominationSaveOperation(WorkspaceOperation): name = "nominate_save" availability = CMDLINE_DEBUG_AVAILABLE | UI_AVAILABLE argList = [OpArgument("retain_existing", help = "don't clear the redacted folders first, if transform is set"), OpArgument("doc", help = "a document to save, as a JSON string", hasArg = True), OpArgument("transform", help = "transform after saving"), OpArgument("lock_id", hasArg = True, help="lock ID (if document is locked)"), OpArgument("release_lock", help="release the lock after save")] def getAffectedFolders(self): if hasattr(self, "doTransform") and self.doTransform: return ["nominated", "redacted, rich", "redacted, raw"] else: return ["nominated"] def getTargetFolderAndDocuments(self): if hasattr(self, "doTransform") and self.doTransform: return "redacted, rich", self._getTargetDocuments("redacted, rich") else: return "nominated", self._getTargetDocuments("nominated") def getAffectedFileBasenames(self): return {self.affectedFileBasename: self.affectedBasenames[0]} def do(self, retain_existing = False, doc = None, transform = False, lock_id = None, release_lock = False): self.doTransform = transform if lock_id is None: raise WorkspaceError, "can't save without lock ID" # Now we get the basename. Must check to ensure that # the lock ID matches. Need to get the file basename # from the transaction. db = self.folder.workspace.getDB() fileBasename, basename, user = db.nominationGetLockIDInfo(lock_id) if basename != self.affectedBasenames[0]: raise WorkspaceError, ("wrong lock ID %s for basename %s" % (lock_id, self.affectedBasenames[0])) self.affectedFileBasename = fileBasename t = self.folder.workspace.beginTransaction(self, filesToPreserve = [os.path.join(self.folder.dir, fileBasename)]) try: if doc is not None: # It can be none, if it's not dirty. # First, make it into a document. The document # string is almost certainly not Unicode yet. docObj = self.folder.docIO.readFromByteSequence(doc, 'utf-8') # There better only be one basename. self.folder.saveFile(docObj, fileBasename) if release_lock: if self.fromCmdline: print "Releasing lock ID %s" % lock_id o = self.folder.getOperation("release_lock", basenames = [basename], transaction = t) o.do(lock_id = lock_id) t.commit() except: t.rollback() raise if transform: # Clear the redacted folders. Run the engine. operationSettings = self.getOperationSettings() if operationSettings is None: raise WorkspaceError, ("no operation settings in task '%s' for operation '%s'" % \ (self.folder.workspace.task.name, self.name)) operationSettings = operationSettings.copy() # Now, we've got our settings. At least workflow and steps are defined. try: workflow = operationSettings["workflow"] except KeyError: raise WorkspaceError, ("workflow undefined in tag prep operation settings") del operationSettings["workflow"] rawFolder = self.folder.workspace.folders['redacted, raw'] richFolder = self.folder.workspace.folders['redacted, rich'] if not retain_existing: rawFolder.clear() richFolder.clear() allPaths = [os.path.join(self.folder.dir, fileBasename)] try: import MAT.ToolChain e = MAT.ToolChain.MATEngine(workflow = workflow, task = self.folder.workspace.task.name) dataPairs = e.Run(inputFileList = allPaths, input_file_type = "mat-json", **operationSettings) except Error.MATError, e: raise WorkspaceError, e.prefix + ": " + e.errstr # If this succeeds, I should write all the files to # the appropriate folder. for file, output in dataPairs: richFolder.saveFile(output, os.path.basename(file)) rawFolder.saveFile(output, os.path.basename(file)) # And remove them from the nominated folder, I think. self.folder.removeFile(fileBasename) def webResult(self): d = WorkspaceOperation.webResult(self) # We want the document status to be something consistent. # It doesn't really matter what the actual status is. # The folder listing will reveal no # basename info for the target folder, so I don't need to hack that too. if d.has_key("status"): del d["status"] return d class NominationFolder(CoreWorkspaceFolder): def fileBasenameLocked(self, fileBasename): return self.workspace.getDB().nominationDocumentLocked(fileBasename) def updateOpenFileWebResultSeed(self, doc, basename, seed): return def prepareForEditing(self, doc, fileBasename, user, lockId): db = self.workspace.getDB() db.lockNominationDocument(lockId, fileBasename, user) def listContents(self, basenames): db = self.workspace.getDB() bPairs = [] # For these basenames, see which files are actually present. lockInfo = dict([(docName, lockedBy) for (docName, lockedBy, lockID) in db.nominationLockInfo()]) for docName, basename, status, assignedUser, lockedBy in db.basenameInfo(basenames): # Ignore locking and status - this is just to get assignment info. if os.path.exists(os.path.join(self.dir, docName)): info = {"basename": basename} if docName != basename: info["doc name"] = docName if assignedUser: info["assigned to"] = assignedUser lockedBy = lockInfo.get(docName) if lockedBy: info["locked by"] = lockedBy bPairs.append(info) return bPairs def removeFile(self, fileBasename): CoreWorkspaceFolder.removeFile(self, fileBasename) self.workspace.getDB().unlockNominationDocument(fileBasename) class RedactionFolder(CoreWorkspaceFolder): def fileBasenameLocked(self, fileBasename): return None def updateOpenFileWebResultSeed(self, doc, basename, seed): return def prepareForEditing(self, doc, fileBasename, user, lockId): raise WorkspaceError, "folder is not editable" def listContents(self, basenames): db = self.workspace.getDB() bPairs = [] # For these basenames, see which files are actually present. for docName, basename, status, assignedUser, lockedBy in db.basenameInfo(basenames): # Ignore locking and status - this is just to get assignment info. if os.path.exists(os.path.join(self.dir, docName)): info = {"basename": basename} if docName != basename: info["doc name"] = docName if assignedUser: info["assigned to"] = assignedUser bPairs.append(info) return bPairs class DeidentificationDB(WorkspaceDB): def nominationDocumentLocked(self, docName): lockedByResult = self._execute("SELECT locked_by FROM nomination_lock WHERE doc_name = ?", params = [docName]) if not lockedByResult: return None else: return lockedByResult[0][0] def lockNominationDocument(self, lockId, docName, lockedBy): # If there's already one, we overwrite the original lock. if self._execute("SELECT locked_by FROM nomination_lock WHERE doc_name = ?", params = [docName]): self._execute("UPDATE nomination_lock SET lock_id = ?, locked_by = ? WHERE doc_name = ?", params = [lockId, lockedBy, docName], retrieval = False) else: self._execute("INSERT INTO nomination_lock VALUES (?, ?, ?)", params = [docName, lockedBy, lockId], retrieval = False) def unlockNominationLock(self, lockId): self._execute("DELETE FROM nomination_lock WHERE lock_id = ?", params = [lockId], retrieval = False) def unlockNominationDocument(self, docName): self._execute("DELETE FROM nomination_lock WHERE doc_name = ?", params = [docName], retrieval = False) def nominationLockInfo(self): return self._execute("SELECT doc_name, locked_by, lock_id FROM nomination_lock") def nominationGetLockIDInfo(self, lockId): v = self._execute("SELECT A.doc_name, B.basename, A.locked_by FROM nomination_lock A, document_info B WHERE A.lock_id = ? AND A.doc_name = B.doc_name", params = [lockId]) if len(v) == 0: return None, None, None else: return v[0] # Another situation where we can't use substitution because I need "IN". def forceUnlockNominationBasenames(self, user, basenames): docLocksToDelete = [r[0] for r in self._executeWithParamDict("SELECT B.doc_name FROM document_info A, nomination_lock B WHERE A.doc_name = B.doc_name AND B.locked_by = $(user) AND A.basename IN ($(basenames))", {"user": user, "basenames": basenames})] if docLocksToDelete: self._executeWithParamDict("DELETE FROM nomination_lock WHERE doc_name IN ($(docLocksToDelete))", {"docLocksToDelete": docLocksToDelete}, retrieval = False) return docLocksToDelete class DeidTaskDescriptor(PluginTaskDescriptor): categories = {} REDACTION_ATTR = "redacted" SEED_UNPARSEABLE_ATTR = "seed_unparseable" def __init__(self, *args, **kw): PluginTaskDescriptor.__init__(self, *args, **kw) self.localReplacers = {} self._rdirCache = None self._replacerCache = None self._instantiatedReplacerCache = {} def fromXML(self, *args): PluginTaskDescriptor.fromXML(self, *args) # At this point, we want to pull out the redaction settings. # Now, we look for all the settings which end in # _replacers, which have a corresponding setting # which ends in _replacers_workflows. import re replPat = re.compile("^(.*)_replacers$") replWFPat = re.compile("^(.*)_replacers_workflows$") replKeyPairs = {} for key in self.settings.keys(): m = replPat.match(key) if m is not None: try: replKeyPairs[m.group(1)][0] = key except KeyError: replKeyPairs[m.group(1)] = [key, None] else: m = replWFPat.match(key) if m is not None: try: replKeyPairs[m.group(1)][1] = key except KeyError: replKeyPairs[m.group(1)] = [None, key] # Now, we've gone through all the keys. # I need two types of mappings. First, I need to be able # to find a replacer of a particular name. Second, I need # to be able to see if a replacer supports a workflow. # Third, I need to report, for various workflows, what # replacers are available. The last is least important. # This all needs to happen by the rname in the replacer. self.localReplacers = {} for family, [repls, replWFs] in replKeyPairs.items(): if (repls is not None) and (replWFs is not None): replWFs = self.settings[replWFs].split(",") repls = self.settings[repls].split(",") # Now, we have all the workflow names and the replacer names. for rName in repls: try: r = FindPluginClass(rName, self.name) if not issubclass(r, PIIReplacementEngine): raise PluginError, ("replacer class %s is not a subclass of PIIReplacementEngine" % rName) if self.localReplacers.has_key(r.__rname__): entry = self.localReplacers[r.__rname__][1] for wf in replWFs: if wf not in entry: entry.append(wf) else: self.localReplacers[r.__rname__] = [r, replWFs[:]] except NameError: raise PluginError, ("unknown replacer %s" % rName) # Now, anyone who gets the replacers, gets a mapping from workflows # to replacer names. def findReplacer(self, rName): try: return self.localReplacers[rName] except KeyError: return None def allReplacers(self): return self.localReplacers.keys() def getReplacerRDirs(self): if self._rdirCache is not None: return self._rdirCache else: # Return all resource directories up to the root. if self.parentObj and hasattr(self.parentObj, "getReplacerRDirs"): seed = self.parentObj.getReplacerRDirs()[:] else: seed = [] if self.resourceDir not in seed: seed[0:0] = [self.resourceDir] self._rdirCache = seed return seed # Fetch the CGI task metadata. Only called on leaves. def getCGIWorkflowMetadata(self, wfObj): params = PluginTaskDescriptor.getCGIWorkflowMetadata(self, wfObj) workFlow = wfObj.name # Return the replacers. params["uiSettings"]["replacers"] = [key for (key, rPair) in self.localReplacers.items() if workFlow in rPair[1]] return params def enhanceCGIMetadata(self, metadata): PluginTaskDescriptor.enhanceCGIMetadata(self, metadata) # What I need to do here is get the replacers for the # workspace. try: redactionWorkflow = self.getWorkspaceOperations()["redact"]["workflow"] metadata["workspaceReplacers"] = [key for (key, rPair) in self.localReplacers.items() if redactionWorkflow in rPair[1]] except KeyError: metadata["workspaceReplacers"] = [] def getCmdlineTaskMetadata(self): # How should we format this? We need to find all the possible sets. wfSets = {} for key, rPair in self.localReplacers.items(): wfSet = rPair[1][:] wfSet.sort() wfTuple = tuple(wfSet) try: wfSets[wfTuple].append(key) except KeyError: wfSets[wfTuple] = [key] return [" replacers : " + ", ".join([", ".join(vals) + " (" + ", ".join(key) + ")" for key, vals in wfSets.items()])] # Workspace customization. Add the redact action to the # completed folder. Add the redacted, rich and redacted, raw folders. # Redaction has default settings in the def workspaceCustomize(self, workspace, create = False): workspace.addFolder('redacted, rich', "redacted_rich", create = create, folderClass = RedactionFolder, description = "rich versions of redacted documents", importTarget = False) workspace.addFolder('redacted, raw', "redacted_raw", create = create, folderClass = RedactionFolder, description = "raw versions of redacted documents", importTarget = False) from MAT.DocumentIO import getDocumentIO workspace.folders["redacted, raw"].docIO = getDocumentIO("raw", encoding = "utf-8") workspace.folders['core'].addOperation("redact", RedactionOperation) # I have to make sure that this folder gets created if it's not already # there, because some of the folks who are using this code have already # made workspaces. f = NominationFolder(workspace, 'nominated', description = "completed documents with nominated replacements", importTarget = False) workspace.folders['nominated'] = f if not os.path.isdir(f.dir): f.create() workspace.folders['core'].addOperation("nominate", NominationOperation) workspace.folders['nominated'].addOperation("nominate_save", NominationSaveOperation) workspace.folders["nominated"].addOperation("release_lock", NominationReleaseLockOperation) workspace.folders["nominated"].addOperation("force_unlock", NominationForceUnlockOperation) workspace.getDB = lambda: self._getEnhancedWorkspaceDB(workspace) def _getEnhancedWorkspaceDB(self, ws): db = Workspace.getDB(ws) db.run_script(os.path.join(os.path.dirname(os.path.abspath(__file__)), "deid_ws.sql")) db.__class__ = DeidentificationDB return db def workspaceUpdate1To2(self, workspace, oldWorkspaceDir, basenames, initialUser): import shutil # Just copy them over. The folders will already have been created. redactedRichBasenames = list(set(os.listdir(os.path.join(oldWorkspaceDir, "folders", "redacted_rich"))) & basenames) print "Copying basenames from 'redacted, rich':", " ".join(redactedRichBasenames) for b in redactedRichBasenames: shutil.copy(os.path.join(oldWorkspaceDir, "folders", "redacted_rich", b), os.path.join(workspace.folders["redacted, rich"].dir, b)) redactedRawBasenames = list(set(os.listdir(os.path.join(oldWorkspaceDir, "folders", "redacted_raw"))) & basenames) print "Copying basenames from 'redacted, raw':", " ".join(redactedRawBasenames) for b in redactedRawBasenames: shutil.copy(os.path.join(oldWorkspaceDir, "folders", "redacted_raw", b), os.path.join(workspace.folders["redacted, raw"].dir, b)) nominatedBasenames = list(set(os.listdir(os.path.join(oldWorkspaceDir, "folders", "nominated"))) & basenames) print "Copying basenames from 'nominated': ", " ".join(nominatedBasenames) for b in nominatedBasenames: shutil.copy(os.path.join(oldWorkspaceDir, "folders", "nominated", b), os.path.join(workspace.folders["nominated"].dir, b)) # Local operations. def replaceableAnnotations(self): return self.getAnnotationTypesByCategory("content") def instantiateReplacer(self, rName, **kw): if self._instantiatedReplacerCache.has_key(rName): return self._instantiatedReplacerCache[rName] else: rPair = self.findReplacer(rName) if rPair is not None: r = rPair[0] c = r(self.getReplacerRDirs(), self.categories, **kw) self._instantiatedReplacerCache[rName] = c return c return None # Here, I'm going to try to add a column which reflects the # document-level probabilities. def augmentTagSummaryScoreTable(self, tbl): c = AggregatorScoreColumn("doc_confidence", rowDispatch = [(FileAggregateScoreRow, DocConfidence, None), (BaseScoreRow, None)]) tbl.addColumn(c, after = "accum") tbl.aggregates.append(c) return tbl def augmentTokenSummaryScoreTable(self, tbl): c = AggregatorScoreColumn("doc_confidence", rowDispatch = [(FileAggregateScoreRow, DocConfidence, None), (BaseScoreRow, None)]) tbl.addColumn(c, after = "accum") tbl.aggregates.append(c) return tbl def augmentDetailScoreTable(self, tbl): return tbl # # Here are the deidentification steps # class NominateStep(PluginStep): argList = [OpArgument("replacer", help = "specify the replacer to use. Obligatory if more than one replacer is available. See above for available replacers.", hasArg = True), OpArgument("cache_scope", help = "specify the cache scope for particular tags. Argument is a semicolon-delimited sequence of <tag>,doc|batch|none, e.g. 'PERSON,batch;LOCATION;doc'. Default scope is document scope.", hasArg = True), OpArgument("cache_case_sensitivity", help = "specify which tags have case-sensitive caches. Argument is a semicolon-delimited sequence of tags, e.g., 'PERSON;LOCATION'.", hasArg = True), OpArgument("resource_file_repl", help="specify a replacement for one of the resource files used by the replacement engine. Argument is a semicolon-delimited sequence of <file>=<repl>. See the ReplacementEngine.py for details.", hasArg = True), OpArgument("replacement_map_file", help="Specify a replacement map file to provide some detailed control over clear -> clear replacements. See documentation for details.", hasArg = True), OpArgument("replacement_map", help="Specify a replacement map to provide some detailed control over clear -> clear replacements. See documentation for details.", hasArg = True), OpArgument("dont_nominate", help = "A comma-separated list of labels for which nominations should not be proposed", hasArg = True), OpArgument("flag_unparseable_seeds", hasArg = True, help = "A comma-separated list of labels whose annotations should be flagged in clear -> clear replacement when the phrase in the original document could not be parsed appropriately (and thus whose replacements might not have the appropriate fidelity). Currently, only dates, URLs, phone numbers, and can be flagged in this way.")] def paramsSatisfactory(self, wfName, failureReasons, replacer = None, **params): if replacer is None: allReplacers = self.descriptor.allReplacers() if len(allReplacers) == 1: replacer = allReplacers[0] if replacer is None: raise PluginError, "no replacer specified" # Filter the task implementation based on the replacer. # If the named replacer isn't one of the replacers # in the task, we bail. rPair = self.descriptor.findReplacer(replacer) if rPair is None: failureReasons.append("task '%s' does not know about the replacer '%s'" % (self.descriptor.name, replacer)) return False elif wfName not in rPair[1]: failureReasons.append("workflow '%s' in task '%s' does not support the replacer '%s'" % (wfName, self.descriptor.name, replacer)) return False else: return True # This drives the replacers. def doBatch(self, iDataPairs, replacer = None, dont_nominate = None, flag_unparseable_seeds = None, **kw): # This needs to be a batch step, so that we can get corpus-level # weights to work. # Don't bother catching the errors; we'll deal with them # in the engine. if replacer is None: # Checked in paramsSatisfactory(). replacer = self.descriptor.allReplacers()[0] r = self.descriptor.instantiateReplacer(replacer, **kw) if not r: raise Error.MATError("nominate", "couldn't find the replacer named " + replacer) if dont_nominate is not None: dontNominate = set([x.strip() for x in dont_nominate.split(",")]) else: dontNominate = set() if flag_unparseable_seeds is not None: flagUnparseableSeeds = set([x.strip() for x in flag_unparseable_seeds.split(",")]) else: flagUnparseableSeeds = set() # print "FLAGGING", flagUnparseableSeeds # This should only happen with spanned annotations, but we # have to make absolutely sure. See below. replaceableAnnots = set(self.descriptor.replaceableAnnotations()) - dontNominate # Two phases: first we digest, then we replace. # Note that what we need for the replacement is the # effective label, as defined by the task. nomMapping = {} # Apparently, you may have the same file more than once. This # is a bug in the bug queue, and the only instance of doBatch in the # system where that problem might arise is this one. So let's fix it. for f, annotSet in iDataPairs: annotSet.metadata["replacer_used"] = replacer # First, generate all the nominations. digestionDict = {} annList = [] for eName in replaceableAnnots: try: eType = annotSet.anameDict[eName] except KeyError: # There may not be any. continue # If it's spanless, skip it. if not eType.hasSpan: continue annList = annList + annotSet.atypeDict[eType] # Sort them in order. annList.sort(key = lambda ann: ann.start) # Digest. for annot in annList: lab = self.descriptor.getEffectiveAnnotationLabel(annot) digestionDict[annot] = (lab, r.Digest(lab, annotSet.signal[annot.start:annot.end])) r.EndDocumentForDigestion() if hasattr(r, "dateDelta"): # This is an integer. annotSet.metadata["dateDelta"] = r.dateDelta nomMapping[(f, annotSet)] = (annList, digestionDict) # Replace. for f, annotSet in iDataPairs: annList, digestionDict = nomMapping[(f, annotSet)] for annot in annList: lab, digestions = digestionDict[annot] repl = r.Replace(lab, digestions, filename = f) annot[self.descriptor.REDACTION_ATTR] = repl # ONLY if we're in clear -> clear. Otherwise, it doesn't matter # that the seed is unparseable. Either it's not expected to be, # or the target doesn't care. if (replacer == "clear -> clear") and (lab in flagUnparseableSeeds) and \ hasattr(digestions, "seed_unparseable") and digestions.seed_unparseable: import sys print >> sys.stderr, "WARNING: the '%s' phrase '%s' from %d to %d could not be parsed for nomination, and its nomination must be reviewed before the transform step can apply" % (annot.atype.lab, annotSet.signal[annot.start:annot.end], annot.start, annot.end) annot[self.descriptor.SEED_UNPARSEABLE_ATTR] = digestions.__ctype__ r.EndDocumentForReplacement() return iDataPairs def undo(self, annotSet, **kw): try: del annotSet.metadata["replacer_used"] except KeyError: pass for tag in self.descriptor.getAnnotationTypesByCategory("content"): try: atype = annotSet.anameDict[tag] if not atype.attr_table.has_key(self.descriptor.REDACTION_ATTR): continue # We can't remove the attribute from the # annotation TYPE, because those are global. # Once the attribute is defined, it's always # defined. However, we can remove it most efficiently # from the ANNOTATION by seeing how many attributes # the annotation has (remember, a shorter list # is equal to nulls everywhere). If the annotation # list is no longer than the index of the # redacted attribute, then we can just truncate # the list of attrs. This should probably # be a delitem on the annotation. Well, no; # you can set an attribute to null, but you # can't actually delete it once it's set. i = atype.attr_table[self.descriptor.REDACTION_ATTR] for annot in annotSet.atypeDict[atype]: if len(annot.attrs) > i: # There's something at that index. annot.attrs[i] = None i = atype.attr_table.get(self.descriptor.SEED_UNPARSEABLE_ATTR) if i is not None: for annot in annotSet.atypeDict[atype]: if len(annot.attrs) > i: annot.attrs[i] = None except KeyError: pass def isDone(self, annotSet): for annot in annotSet.getAnnotations(self.descriptor.getAnnotationTypesByCategory("content")): try: if annot[self.descriptor.REDACTION_ATTR] is not None: return True except KeyError: pass return False from MAT.Document import OverlapError, AnnotatedDoc import sys class TransformStep(PluginStep): argList = [OpArgument("prologue", help = "Specify the text of a prologue to insert into the transformed document. You may wish to do this, e.g., to assert that all names in the document are fake. This option takes preference over --prologue_file.", hasArg = True), OpArgument("prologue_file", help = "Specify a file which contains the text of a prologue to insert into the transformed document. You may wish to do this, e.g., to assert that all names in the document are fake. The file is assumed to be in UTF-8 encoding. --prologue takes preference over this option.", hasArg = True), OpArgument("dont_transform", help = "A comma-separated list of labels that should not be transformed", hasArg = True)] def __init__(self, *args, **kw): PluginStep.__init__(self, *args, **kw) # We need to know which # step to use to prep the final document after the tags # have been located. The prepping differs # depending on whether the redaction is to clear or not. # If it's to clear, find the "zone" task in the demo workflow; # otherwise, find the zone task in the resynth workflow. # We don't want to have to find the replacer in the # invocation of do(). In particular, we should expect that the # replacer be in the document itself. But that means that we'd # need to figure out, on a document-by-document basis, # which prep function to use. So let's cache them in advance. # Well, we can't, actually, because looking for a step # in the context of when the steps are created gives you # infinite recursion. So we need to create them later. self._postTransformStepsFound = False self.clearZoneStep = None self.resynthZoneStep = None def _ensurePostTransformSteps(self): if not self._postTransformStepsFound: self._postTransformStepsFound = True self.clearZoneStep = self.descriptor.getStep("Demo", "zone") try: self.resynthZoneStep = self.descriptor.getStep("Resynthesize", "zone") except PluginError: pass # # Core deidentification engine. Transform step is general. # def augmentClearZones(self, iDataPairs): self.clearZoneStep.doBatch(iDataPairs) # And, once it's tokenized, I have to make sure that (believe it # or not) no tags mismatch the annotation boundaries. If they do, # I need to expand the annotation boundaries to match the nearest # token. This is a messy computation, but it turns out I need # it in the core, anyway. for fname, annotSet in iDataPairs: for seg in annotSet.getAnnotations(["SEGMENT"]): seg["annotator"] = "unknown human" seg["status"] = "human gold" annotSet.adjustTagsToTokens(self.descriptor) def augmentRedactedZones(self, iDataPairs): # There may not be a zone step. But in any case, what we # want to do is go back through the annotations and adjust # the boundaries until there's no leading or trailing whitespace. if self.resynthZoneStep: resynthZoneStep.doBatch(iDataPairs) for fname, annotSet in iDataPairs: annotSet.avoidWhitespaceInTags(self.descriptor) # The problem with doing this file by file is that you have to call the # tokenizer every damn time when you align. What I really want to do is # do it in batch, and within the batch process, do the individual file # replacements. def doBatch(self, iDataPairs, replacer = None, prologue = None, prologue_file = None, dont_transform = None, **kw): if (prologue is None) and (prologue_file is not None): if not os.path.isabs(prologue_file): prologue_file = os.path.join(self.descriptor.taskRoot, prologue_file) import codecs fp = codecs.open(prologue_file, "r", "utf-8") prologue = fp.read() fp.close() elif type(prologue) is str: prologue = prologue.decode('ascii') if dont_transform is not None: dontTransform = set([x.strip() for x in dont_transform.split(",")]) else: dontTransform = set() # Someone might decide to call do() on this object. Let's see if we can # figure out what replacer was used. replacersUsed = set([annotSet.metadata.get("replacer_used") for fname, annotSet in iDataPairs]) replacersUsed.discard(None) if len(replacersUsed) > 1: raise Error.MATError("transform", "multiple replacers specified in transform set") if replacer is None: if len(replacersUsed) == 0: raise Error.MATError("transform", "no replacer specified") else: replacer = list(replacersUsed)[0] r = self.descriptor.instantiateReplacer(replacer, **kw) if not r: raise Error.MATError("transform", "couldn't find the replacer named " + replacer) if isinstance(r.renderingStrategy, ClearRenderingStrategy): clearTarget = True else: clearTarget = False self._ensurePostTransformSteps() # From these, we remove the ones which don't have any redaction attributes # specified (they may have been filtered out by dont_nominate), and the ones which # shouldn't be transformed. # Actually, it's a bit more complicated than that. We don't want to LOSE # content annotations which aren't replaceable. So what we want to do # is build up a map of replacements for all content annotations, and # then, for the subset of annotations which are transformable and # have a replacement, use that replacement. annotNames = self.descriptor.getAnnotationTypesByCategory("content") outPairs = [] for fname, annotSet in iDataPairs: try: newSet = self._transformAnnotSet(r, annotSet, annotNames, dontTransform, prologue) outPairs.append((fname, newSet)) except OverlapError: sys.stderr.write("Can't transform document %s because there's an overlap\n" % fname) return [] if clearTarget: self.augmentClearZones(outPairs) else: self.augmentRedactedZones(outPairs) # Finally, mark the document as zoned and tagged. for fname, d in outPairs: d.setStepsDone(["zone", "tag"]) return outPairs def _transformAnnotSet(self, engine, annotSet, annotNames, dontTransform, prologue): # Seed it with mapings into the original signal. replacerMap = {} replaceableAnnotNames = set([a for a in self.descriptor.replaceableAnnotations() if (a not in dontTransform) and \ (annotSet.findAnnotationType(a).attr_table.has_key(self.descriptor.REDACTION_ATTR))]) # We have to change the regions in the signal so that # they're substituted. We order them because we need to # go through them in order to handle the substitutions cleanly. # Note that orderAnnotations will filter out the spanless types. # This might generate an overlap error; see caller. try: annots = annotSet.orderAnnotations(annotNames) except OverlapError: sys.stderr.write("Can't transform document because there's an overlap\n") return None atypeIndexDict = {} for aname in replaceableAnnotNames: try: t = annotSet.anameDict[aname] except KeyError: # There may not be any. continue atypeIndexDict[t] = t.ensureAttribute(self.descriptor.REDACTION_ATTR) # Update the replacer map. replacerMap[t] = lambda x: x[atypeIndexDict[x.atype]] # Build a new doc. d = AnnotatedDoc(globalTypeRepository = annotSet.atypeRepository.globalTypeRepository) # Copy the metadata, because the interface will need it. d.metadata = annotSet.metadata.copy() d.metadata["phasesDone"] = [] signal = annotSet.signal unparseableAttr = self.descriptor.SEED_UNPARSEABLE_ATTR # Originally, I was going to have the # untransformed ones as no annotations at all, but # really, I should have an annotation, since I may # need to compare them later. replacementTuples = [] preservationTuples = [] for a in annots: if a.get(unparseableAttr) is not None: raise PluginError, ("The '%s' phrase '%s' from %d to %d could not be parsed for nomination, and its nomination must be reviewed before the transform step can apply" % (a.atype.lab, signal[a.start:a.end], a.start, a.end)) if a.atype.lab in replaceableAnnotNames: replacementTuples.append((a.atype.lab, a.start, a.end, replacerMap[a.atype](a))) else: preservationTuples.append((a.atype.lab, a.start, a.end)) output, finalTuples = engine.Transform(signal, prologue, replacementTuples, preservationTuples) for lab, start, end in finalTuples: # Poo. The type is going to have the "redacted" attribute, # which may hose me at some point. newT = d.findAnnotationType(lab) d.createAnnotation(start, end, newT) d.signal = output return d # This won't be recorded as a step done, but if it were, you can't # undo it anyway. def do(self, annotSet, **kw): iDataPairs = self.doBatch([("<file>", annotSet)], **kw) if iDataPairs: return iDataPairs[0][1] else: return None def undo(self, annotSet, **kw): pass class ResynthZoneStep(PluginStep): def do(self, annotSet, **kw): return annotSet def undo(self, annotSet, **kw): pass class MultiZoneStepForUndo(PluginStep): # This had better never be called. def do(self, annotSet, **kw): return annotSet def undo(self, annotSet, **kw): self.removeAnnotationsByCategory(annotSet, "token", "zone") def isDone(self, annotSet): return False class ResynthTagStep(TagStep): def __init__(self, *args, **kw): if (kw.has_key("by_hand") and kw["by_hand"]): raise PluginError, "by_hand attribute applies only to a real tagging step" TagStep.__init__(self, *args, **kw) # This isn't really a tag step. del self.initSettings["tag_step"] def paramsSatisfactory(self, wfName, failureReasons, replacer = None, **params): if replacer is None: allReplacers = self.descriptor.allReplacers() if len(allReplacers) == 1: replacer = allReplacers[0] if replacer is None: raise PluginError, "no replacer specified" # Filter the task implementation based on the replacer. # If the named replacer isn't one of the replacers # in the task, we bail. rPair = self.descriptor.findReplacer(replacer) if rPair is None: failureReasons.append("task '%s' does not know about the replacer '%s'" % (self.descriptor.name, replacer)) return False elif wfName not in rPair[1]: failureReasons.append("workflow '%s' in task '%s' does not support the replacer '%s'" % (wfName, self.descriptor.name, replacer)) return False else: return True def do(self, annotSet, replacer = None, **kw): # Ask the current replacer to find all the matches. if replacer is None: # Checked in paramsSatisfactory(). replacer = self.descriptor.allReplacers()[0] try: r = self.descriptor.instantiateReplacer(replacer, **kw) if not r: raise Error.MATError("tag", "couldn't find the replacer named " + replacer) # Two phases: first we digest, then we replace. tuples = r.FindReplacedElements(annotSet.signal) for start, end, tname in tuples: atype = annotSet.findAnnotationType(tname) annotSet.createAnnotation(start, end, tname) return annotSet except Exception, e: raise Error.MATError("tag", str(e), show_tb = True) # Undocumented utility for expanding the documentation in-line. class DocEnhancer(PluginDocInstaller): def process(self): # # BEGIN APP-SPECIFIC MODIFICATIONS # # In this section, you should modify the value of INDEX_CONTENTS, # and populate the HTML target directory appropriately. # The deidentification bundle consists of three things: the deidentification # summary and the general extensions, which are only provided by the core, and # the site modifications, which are only provided by the sites. Ideally, # these should be loadable in any order. So let's say that we expect to insert, # under the section marker # <div class="invisible" id="appcustomizations"></div> # something that looks like # <div id="deidcustomizations"> # <ul class="secthead"><li>Deidentification customizations</li><ul> # <ul><li>General # <li><...site link...> # </ul> # </div> self.ensureDEID() # Now, since this is the core, we insert the general link # at the beginning of the deidcustomization list, and we # insert the introduction at the appropriate place. self.addListElement(self.getElementById("deidcustomizationlist"), "General", href = "doc/general.html", first = True) self.addAppOverviewEntry("doc/intro.html", "MIST: The MITRE Identification Scrubber Toolkit") def ensureDEID(self): # So if there isn't any div yet, insert the infrastructure. Then, add the local # link at the end, if this is the local one, and if it's the core, add the # core link. DEID_INSERT = """ <div id="deidcustomizations"> <ul class="secthead"><li>Deidentification customizations</li></ul> <ul id="deidcustomizationlist"></ul> </div> """ # Everybody makes sure that the deidcustomization node is present. custNode = self.getElementById("deidcustomizations") if custNode is None: self.addAppCustomizationList(DEID_INSERT) def addSubtaskDetail(self, url, listEntry): self.ensureDEID() # Now, since this is one of the sites, we insert the site link # at the end of the deidcustomization list. self.addListElement(self.getElementById("deidcustomizationlist"), listEntry, href = url)
{ "content_hash": "5fc5e33186e96da331192f7411b7afcb", "timestamp": "", "source": "github", "line_count": 1347, "max_line_length": 357, "avg_line_length": 44.18634001484781, "alnum_prop": 0.6065626102589089, "repo_name": "VHAINNOVATIONS/DmD", "id": "c1b4afe06b10a1f4f73064ab188d6ae80a75b6fe", "size": "59622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scrubber/MIST_2_0_4/src/tasks/core/python/Deidentification.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "258262" }, { "name": "HTML", "bytes": "3057541" }, { "name": "Java", "bytes": "363296" }, { "name": "JavaScript", "bytes": "8682388" }, { "name": "Perl", "bytes": "294110" }, { "name": "Perl6", "bytes": "14166" }, { "name": "Prolog", "bytes": "782419" }, { "name": "Python", "bytes": "3569206" }, { "name": "Shell", "bytes": "6422" }, { "name": "XS", "bytes": "120883" } ], "symlink_target": "" }
import logging import requests import unittest from unittest.mock import MagicMock, patch, PropertyMock from pyhik.hikvision import HikCamera from pyhik.constants import (CONNECT_TIMEOUT) XML = """<MotionDetection xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0"> <enabled>{}</enabled> <enableHighlight>true</enableHighlight> <samplingInterval>2</samplingInterval> <startTriggerTime>500</startTriggerTime> <endTriggerTime>500</endTriggerTime> <regionType>grid</regionType> <Grid> <rowGranularity>18</rowGranularity> <columnGranularity>22</columnGranularity> </Grid> <MotionDetectionLayout version="2.0"> <sensitivityLevel>20</sensitivityLevel> <layout> <gridMap>000000000000000000000000000000000c007e0c007ffffc</gridMap> </layout> </MotionDetectionLayout> </MotionDetection>""" @patch("pyhik.hikvision.requests.Session") class HikvisionTestCase(unittest.TestCase): @staticmethod def set_motion_detection_state(get, value): get.reset_mock() mock = get.return_value mock.reset_mock() type(mock).ok = PropertyMock(return_value=True) type(mock).status_code = PropertyMock(return_value=requests.codes.ok) type(mock).text = PropertyMock( return_value=XML.format("true" if value else "false") ) return get @patch("pyhik.hikvision.HikCamera.get_device_info") @patch("pyhik.hikvision.HikCamera.get_event_triggers") def test_motion_detection(self, *args): session = args[-1].return_value get = session.get url = "localhost:80/ISAPI/System/Video/inputs/channels/1/motionDetection" # Motion detection disabled self.set_motion_detection_state(get, False) device = HikCamera(host="localhost") get.assert_called_once_with(url, timeout=CONNECT_TIMEOUT) self.assertIsNotNone(device) self.assertFalse(device.current_motion_detection_state) # Motion detection enabled self.set_motion_detection_state(get, True) device = HikCamera(host="localhost") self.assertIsNotNone(device) self.assertTrue(device.current_motion_detection_state) # Enable calls put with the expected data self.set_motion_detection_state(get, True) session.put.return_value = MagicMock(status_code=requests.codes.ok, ok=True) device.enable_motion_detection() session.put.assert_called_once_with(url, data=XML.format("true").encode(), timeout=CONNECT_TIMEOUT) # Disable def change_get_response(url, data,timeout): self.set_motion_detection_state(get, False) return MagicMock(ok=True, status_code=requests.codes.ok) self.set_motion_detection_state(get, True) session.put = MagicMock(side_effect=change_get_response) device = HikCamera(host="localhost") self.assertTrue(device.current_motion_detection_state) device.disable_motion_detection() self.assertFalse(device.current_motion_detection_state) if __name__ == "__main__": unittest.main()
{ "content_hash": "358d4af3878a64a064c54e2161a5516d", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 107, "avg_line_length": 37.464285714285715, "alnum_prop": 0.6835081029551954, "repo_name": "mezz64/pyHik", "id": "21d4687b07961a50ceb170d54a3a559f78f7a9fb", "size": "3171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/test_hikvision.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "33500" } ], "symlink_target": "" }
<?php /** * ActionDesc element class * * Heirarchy: * (%pcd-model; | %phrase-level; | committee-name | cosponsor | sponsor | nonsponsor)* * * @todo A list of assumptions ( which are don't account for the true spec detailed above ): * * We will have only one sponsor * * NOTE: Right now we only account for one committee */ namespace USLM\Legislation\Element\Action; use USLM\Legislation\Element\LegislationElement; class ActionDesc extends LegislationElement{ public function toArray(){ $this->checkRequirements(array('xml')); $array = array(); //Cannot simple cast to a string. This won't include child element text. $array['text'] = strip_tags($this->xml->asXML()); if($sponsor = $this->getSponsor()){ $array['sponsor'] = $sponsor; } if($committeeName = $this->getCommittee()){ $array['committee-name'] = (string)$committeeName; } if($cosponsors = $this->getCosponsors()){ $array['cosponsors'] = $cosponsors; } return $array; } public function getSponsor(){ if(!isset($this->xml->sponsor)){ return false; } $sponsor = new Sponsor(); $sponsor->simplexml($this->xml->sponsor); return $sponsor->toArray(); } public function getCommittee(){ if(!isset($this->xml->{'committee-name'})){ return false; } $committeeName = new CommitteeName(); $committeeName->simplexml($this->xml->{'committee-name'}); return $committeeName; } public function getCosponsors(){ if(!isset($this->xml->cosponsor)){ return false; } $nodes = $this->xml->cosponsor; $array = array(); foreach($nodes as $node){ $cosponsor = new Cosponsor(); $cosponsor->simplexml($node); array_push($array, $cosponsor->toArray()); } return $array; } }
{ "content_hash": "cc89d01e42c7f72512285f4b14e5549f", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 91, "avg_line_length": 22.6375, "alnum_prop": 0.6272777471010491, "repo_name": "opengovfoundation/USLM", "id": "e8b56beb9e5c587bf8d310c256a5b93847b664e6", "size": "1811", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/USLM/Legislation/Element/Action/ActionDesc.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "132460" } ], "symlink_target": "" }
const stats = { compilation: { warnings: [] }, hasErrors: () => false } const webpack = jest.fn((_, fn) => { fn(null, stats) }) export default webpack
{ "content_hash": "00b97fdeb990395628fd5a3e4dc276f1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 36, "avg_line_length": 16.3, "alnum_prop": 0.5766871165644172, "repo_name": "railsware/bozon", "id": "7ee8053ddf5c000973d22f5011c8255056ff8699", "size": "163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "__mocks__/webpack.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "467" }, { "name": "HTML", "bytes": "367" }, { "name": "JavaScript", "bytes": "75779" } ], "symlink_target": "" }
<?php namespace League\OAuth2\Client\Provider; use League\OAuth2\Client\Provider\Exception\IdentityProviderException; use League\OAuth2\Client\Token\AccessToken; use Psr\Http\Message\ResponseInterface; class Moves extends AbstractProvider { /** * @var string */ const BASE_MOVES_URL = 'https://moves-app.com'; /** * @var string */ const BASE_MOVES_API_URL = 'https://api.moves-app.com'; /** * @var string */ protected $apiAuthVersion = 'v1'; /** * @var string */ protected $apiVersion = '1.1'; /** * Constructs an OAuth 2.0 service provider. * * @param array $options An array of options to set on this provider. * Options include `clientId`, `clientSecret`, `redirectUri`, `state`, `apiVersion`. * Individual providers may introduce more options, as needed. * @param array $collaborators An array of collaborators that may be used to * override this provider's default behavior. Collaborators include * `grantFactory`, `requestFactory`, `httpClient`, and `randomFactory`. * Individual providers may introduce more collaborators, as needed. */ public function __construct(array $options = [], array $collaborators = []) { parent::__construct($options, $collaborators); foreach ($options as $option => $value) { if (property_exists($this, $option)) { $this->{$option} = $value; } } } /** * Get authorization url to begin OAuth flow * * @return string */ public function getBaseAuthorizationUrl() { return self::BASE_MOVES_API_URL . '/oauth/' . $this->apiAuthVersion . '/authorize'; } /** * Get access token url to retrieve token * * @param array $params * * @return string */ public function getBaseAccessTokenUrl(array $params) { return self::BASE_MOVES_API_URL . '/oauth/' . $this->apiAuthVersion . '/access_token'; } /** * Get provider url to fetch user details * * @param AccessToken $token * * @return string */ public function getResourceOwnerDetailsUrl(AccessToken $token) { return self::BASE_MOVES_API_URL . '/api/' . $this->apiVersion . '/user/profile?access_token=' . $token; } /** * @link https://dev.moves-app.com/docs/authentication#scopes * Get the default scopes used by this provider. * * This should not be a complete list of all scopes, but the minimum * required for the provider user interface! * * @return array */ protected function getDefaultScopes() { return ['default']; } /** * Check a provider response for errors. * * @throws IdentityProviderException * @param ResponseInterface $response * @param string $data Parsed response data * @return void */ protected function checkResponse(ResponseInterface $response, $data) { if (isset($data['error'])) { throw new IdentityProviderException( $data['error'] ?: $response->getReasonPhrase(), $response->getStatusCode(), $response ); } } /** * Generate a user object from a successful user details request. * * @param array $response * @param AccessToken $token * @return \League\OAuth2\Client\Provider\ResourceOwnerInterface */ protected function createResourceOwner(array $response, AccessToken $token) { return new MovesResourceOwner($response); } }
{ "content_hash": "55ea38852ba78d6cb4ef3a2ea95ac50c", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 111, "avg_line_length": 28.022900763358777, "alnum_prop": 0.6014709888313811, "repo_name": "Edwin-Luijten/oauth2-moves", "id": "d3c4ebfa31085723b760585d38caf7f8e8a68990", "size": "3671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Provider/Moves.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "11820" } ], "symlink_target": "" }
<?php namespace Vidal\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Validator\Constraints\NotBlank; use Vidal\MainBundle\Entity\AstrazenecaFaq; use Lsw\SecureControllerBundle\Annotation\Secure; class NeirodozController extends Controller { /** * @Route("/neiro_doz", name="neirodoz") * @Secure(roles="IS_AUTHENTICATED_REMEMBERED") * @Template("VidalMainBundle:NeiroDoz:home.html.twig") */ public function numb11erAction(Request $request) { if ($request->query->get('test') != 'test') { throw $this->createNotFoundException(); } $params = array( 'noHofitol' => 'true', ); return $params; } }
{ "content_hash": "b77e2d97a9e6d14c31c1b2ccf8a583d3", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 62, "avg_line_length": 29.757575757575758, "alnum_prop": 0.7443991853360489, "repo_name": "Vidal-ru/Vidal", "id": "8c4aa69d7d8d53f8031ef0b2d1fead9316cf48f2", "size": "982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Vidal/MainBundle/Controller/NeirodozController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "81" }, { "name": "CSS", "bytes": "313732" }, { "name": "HTML", "bytes": "3287813" }, { "name": "Java", "bytes": "80" }, { "name": "JavaScript", "bytes": "4032226" }, { "name": "PHP", "bytes": "12455276" }, { "name": "Shell", "bytes": "21036" } ], "symlink_target": "" }
casper.notebook_test(function () { var messages = []; this.on('remote.alert', function (msg) { messages.push(msg); }); this.evaluate(function () { var cell = IPython.notebook.get_cell(0); var json = cell.toJSON(); json.prompt_number = "<script> alert('hello from input prompts !')</script>"; cell.fromJSON(json); }); this.then(function () { this.test.assert(messages.length == 0, "Captured log message from script tag injection !"); }); });
{ "content_hash": "89b92a733458ae1390b6ca548775d0aa", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 99, "avg_line_length": 30.764705882352942, "alnum_prop": 0.5774378585086042, "repo_name": "Lightmatter/django-inlineformfield", "id": "4f72a36598690772d344c241077482a3d42e891a", "size": "648", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": ".tox/py27/lib/python2.7/site-packages/IPython/html/tests/notebook/inject_js.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "43622" }, { "name": "Groff", "bytes": "3667" }, { "name": "HTML", "bytes": "108126" }, { "name": "JavaScript", "bytes": "853457" }, { "name": "Python", "bytes": "10506732" }, { "name": "Shell", "bytes": "3801" }, { "name": "Smarty", "bytes": "21023" } ], "symlink_target": "" }
require 'spec_helper' describe SelectedPhoto do it "should respond to #title" do SelectedPhoto.new.should respond_to(:title) end it "should respond to #title=" do SelectedPhoto.new.should respond_to(:title=) end describe "#photo=" do it "should assign the photo" do s = SelectedPhoto.new photo = Photo.create!(:title => 'My Photo') s.photo = photo s.photo.should eq(photo) end end describe "#photo" do it "should return the selected photo" do s = SelectedPhoto.new photo = Photo.create!(:title => 'My Photo') s.photo = photo s.photo.should eq(photo) end end describe "#as_json" do it "should include the id, title, and image urls" do photo = Photo.create!(:image => File.new(Rails.root + 'photos/1_1.jpg'), :title => 'My Photo') s = SelectedPhoto.new(:title => 'My Selected Title', :photo => photo) s.as_json['image_gallery_url'].should == photo.image.url(:gallery) s.as_json['image_large_url'].should == photo.image.url(:large) s.as_json['image_original_url'].should == photo.image.url(:original) end end end
{ "content_hash": "cb48562e1db5113742a2e7a09c765bbe", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 100, "avg_line_length": 27.975609756097562, "alnum_prop": 0.6338273757628596, "repo_name": "ganeshganga/angularjs_rails_demo", "id": "4a9a93e3c0ef0d9f6ea139f5980181ba7430c92c", "size": "1147", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/models/selected_photo_spec.rb", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2213" }, { "name": "CoffeeScript", "bytes": "18" }, { "name": "JavaScript", "bytes": "1640" }, { "name": "Perl", "bytes": "211" }, { "name": "Ruby", "bytes": "30532" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1"> <context> <name>MainPage</name> <message> <location filename="../qml/pages/MainPage.qml" line="41"/> <source>Copy to clipboard</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="49"/> <source>Clear</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="56"/> <source>Base64 to Text</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="69"/> <source>Text to Base64</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="75"/> <source>Any text…</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="83"/> <location filename="../qml/pages/MainPage.qml" line="125"/> <source>Encode</source> <translation type="unfinished"></translation> </message> <message> <location filename="../qml/pages/MainPage.qml" line="127"/> <source>Decode</source> <translation type="unfinished"></translation> </message> </context> </TS>
{ "content_hash": "878b74ea1169648f8962e95b601f2dc9", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 67, "avg_line_length": 34.81395348837209, "alnum_prop": 0.6032064128256514, "repo_name": "ilpianista/harbour-Base64", "id": "0241e55157f532da6235924cace9f9355c782724", "size": "1499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "translations/harbour-base64.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1639" }, { "name": "QML", "bytes": "6246" }, { "name": "QMake", "bytes": "1069" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Patellina italichroma var. italichroma Speg. ### Remarks null
{ "content_hash": "611afedec4ed87322fc9576b7e4f30fa", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 44, "avg_line_length": 11.461538461538462, "alnum_prop": 0.7248322147651006, "repo_name": "mdoering/backbone", "id": "280ff808c1f37eca4ece04fe4c86d11e8ee528c5", "size": "217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Patellina/Patellina italichroma/Patellina italichroma italichroma/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class FormBase include ActiveModel::Model include Virtus.model def save if valid? persist! true else false end end end
{ "content_hash": "1e3122c48aa635b0ef3af7fb160dce20", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 28, "avg_line_length": 12.153846153846153, "alnum_prop": 0.6139240506329114, "repo_name": "NeilBetham/automaton", "id": "9c66ee9b0cde2db5bd8ea6f13e2b981cc273c97c", "size": "158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/forms/form_base.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7061" }, { "name": "CoffeeScript", "bytes": "7816" }, { "name": "HTML", "bytes": "34937" }, { "name": "Ruby", "bytes": "149079" } ], "symlink_target": "" }
<?php namespace PHPCfg\Op\Expr; use PHPCfg\Assertion as Assert; use PHPCfg\Op\Expr; use PHPCfg\Operand; class Assertion extends Expr { public $read; public $assertion; public function __construct(Operand $read, Operand $write, Assert $assertion, array $attributes = []) { parent::__construct($attributes); $this->expr = $this->addReadRef($read); $this->assertion = $this->addReadRef($assertion); $this->result = $this->addWriteRef($write); } public function getVariableNames() { return ["expr", "result"]; } }
{ "content_hash": "976aa985c6aad38c8f30cebcfa066506", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 107, "avg_line_length": 22.384615384615383, "alnum_prop": 0.6357388316151202, "repo_name": "RustJason/php-cfg", "id": "32ef59a060fad30507e33ce7726bc222bfc18521", "size": "793", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "lib/PHPCfg/Op/Expr/Assertion.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "157124" }, { "name": "Shell", "bytes": "61" } ], "symlink_target": "" }
module Cms::Addon module PageSearchInfo extend ActiveSupport::Concern extend SS::Translation def brief_search_condition info = [ :search_name_info, :search_filename_info, :search_category_ids_info, :search_group_ids_info, :search_node_ids_info, :search_routes_info, :search_released_info, :search_updated_info, :search_state_info, :search_first_released_info, :search_approver_state_info ].map do |m| method(m).call end info.select(&:present?).join(", ") end def search_sort_options [ [I18n.t('cms.options.sort.filename'), 'filename'], [I18n.t('cms.options.sort.name'), 'name'], [I18n.t('cms.options.sort.created'), 'created'], [I18n.t('cms.options.sort.updated_1'), 'updated -1'], [I18n.t('cms.options.sort.released_1'), 'released -1'], ] end def search_state_options %w(public closed ready closing).map do |w| [ I18n.t("views.options.state.#{w}"), w ] end end def search_first_released_options %w(draft published).map do |w| [ I18n.t("views.options.first_released.#{w}"), w ] end end def search_approver_state_options %w(request approve remand).map do |w| [ I18n.t("workflow.page.#{w}"), w ] end end def status_options [ [I18n.t('views.options.state.public'), 'public'], [I18n.t('views.options.state.closed'), 'closed'], [I18n.t('views.options.state.ready'), 'ready'], [I18n.t('views.options.state.request'), 'request'], [I18n.t('views.options.state.remand'), 'remand'], ] end private def search_name_info "#{Cms::Page.t(:name)}: #{search_name}" if search_name.present? end def search_filename_info "#{Cms::Page.t(:filename)}: #{search_filename}" if search_filename.present? end def search_category_ids_info "#{Cms::Page.t(:category_ids)}: #{search_categories.pluck(:name).join(",")}" if search_category_ids.present? end def search_group_ids_info "#{Cms::Page.t(:group_ids)}: #{search_groups.pluck(:name).join(",")}" if search_group_ids.present? end def search_node_ids_info "#{I18n.t 'cms.node'}: #{search_nodes.pluck(:name).join(",")}" if search_node_ids.present? end def search_routes_info normalize_search_routes if search_routes.present? "#{Cms::Page.t(:route)}: #{search_routes.map { |route| route_name(route) }.join(",")}" end end def route_name(route) "#{I18n.t("modules.#{route.sub(/\/.*/, '')}")}/#{I18n.t("mongoid.models.#{route}")}" end def search_released_info if search_released_start.present? || search_released_close.present? start = search_released_start.try(:strftime, "%Y/%m/%d %H:%M") close = search_released_close.try(:strftime, "%Y/%m/%d %H:%M") "#{Cms::Page.t(:released)}: #{start}-#{close}" end end def search_updated_info if search_updated_start.present? || search_updated_close.present? start = search_updated_start.try(:strftime, "%Y/%m/%d %H:%M") close = search_updated_close.try(:strftime, "%Y/%m/%d %H:%M") "#{Cms::Page.t(:updated)}: #{start}-#{close}" end end def search_state_info "#{Cms::Page.t(:state)}: #{I18n.t :"views.options.state.#{search_state}"}" if search_state.present? end def search_first_released_info if search_first_released.present? "#{Cms::PageSearch.t(:search_first_released)}: #{I18n.t :"views.options.state.#{search_first_released}"}" end end def search_approver_state_info if search_approver_state.present? "#{Cms::Page.t(:workflow_state)}: #{I18n.t :"workflow.page.#{search_approver_state}"}" end end end module PageSearch extend ActiveSupport::Concern extend SS::Addon include Cms::Addon::PageSearchInfo KEYWORD_FIELDS = [ :name, :html, :question, :upper_html, :lower_html, :contact_charge, :contact_tel, :contact_fax, :contact_email ].freeze included do field :search_name, type: String field :search_filename, type: String field :search_keyword, type: String field :search_state, type: String field :search_first_released, type: String field :search_approver_state, type: String field :search_released_start, type: DateTime field :search_released_close, type: DateTime field :search_updated_start, type: DateTime field :search_updated_close, type: DateTime field :search_sort, type: String embeds_ids :search_categories, class_name: "Category::Node::Base" embeds_ids :search_groups, class_name: "SS::Group" embeds_ids :search_nodes, class_name: "Cms::Node" embeds_ids :search_users, class_name: "Cms::User" field :search_routes, type: SS::Extensions::Words, default: [] permit_params :search_name, :search_filename, :search_keyword, :search_state, :search_approver_state permit_params :search_first_released, :search_sort permit_params :search_released_start, :search_released_close, :search_updated_start, :search_updated_close permit_params search_category_ids: [], search_group_ids: [], search_node_ids: [], search_user_ids: [], search_routes: [] before_validation :normalize_search_routes validates :search_state, inclusion: { in: %w(public closed ready closing), allow_blank: true } validates :search_approver_state, inclusion: { in: %w(request approve remand), allow_blank: true } validates :search_released_start, datetime: true validates :search_released_close, datetime: true validates :search_updated_start, datetime: true validates :search_updated_close, datetime: true end def search(opts = {}) @search ||= begin name = search_name.present? ? { name: /#{Regexp.escape(search_name)}/ } : {} filename = search_filename.present? ? { filename: /#{Regexp.escape(search_filename)}/ } : {} keyword = build_search_keyword_criteria categories = search_category_ids.present? ? { category_ids: search_category_ids } : {} groups = search_group_ids.present? ? { group_ids: search_group_ids } : {} users = search_user_ids.present? ? { user_id: search_user_ids } : {} state = build_search_state_criteria nodes = build_search_nodes_criteria routes = build_search_routes_criteria approver = build_search_approver_criteria first_released = build_search_first_released_criteria released = [] released << { :released.gte => search_released_start } if search_released_start.present? released << { :released.lte => search_released_close } if search_released_close.present? updated = [] updated << { :updated.gte => search_updated_start } if search_updated_start.present? updated << { :updated.lte => search_updated_close } if search_updated_close.present? criteria = Cms::Page.site(@cur_site). allow(:read, @cur_user). where(name). where(filename). where(nodes). and(keyword). in(categories). in(groups). in(routes). in(users). and(state). and(released). and(updated). and(approver). and(first_released). search(opts) @search_count = criteria.count criteria.order_by(search_sort_hash) end end def search_sort_hash return { filename: 1 } if search_sort.blank? h = {} search_sort.split(" ").each_slice(2) { |k, v| h[k] = (v =~ /-1$/ ? -1 : 1) } h end def search_count search if @search_count.nil? @search_count end def search_condition? normalize_search_routes self.class.fields.keys.any? do |k| k.start_with?("search_") && self[k].present? end end private def normalize_search_routes return if search_routes.blank? self.search_routes = search_routes.dup.select(&:present?) end def build_search_state_criteria return {} unless search_state.present? if search_state == "closing" { "$and" => [ { :state => "public" }, { :close_date.ne => nil } ] } else { state: search_state } end end def build_search_keyword_criteria if search_keyword.present? { "$or" => KEYWORD_FIELDS.map { |field| { field => /#{Regexp.escape(search_keyword)}/ } } } else {} end end def build_search_nodes_criteria if search_node_ids.present? { filename: /^#{search_nodes.map { |node| Regexp.escape("#{node.filename}/") }.join("|")}/ } else {} end end def build_search_routes_criteria normalize_search_routes search_routes.present? ? { route: search_routes } : {} end def build_search_approver_criteria case search_approver_state when 'request' { workflow_state: "request", workflow_user_id: @cur_user._id, } when 'approve' { workflow_state: "request", workflow_approvers: { "$elemMatch" => { "user_id" => @cur_user._id, "state" => "request" } } } when 'remand' { workflow_state: "remand", workflow_user_id: @cur_user._id, } else {} end end def build_search_first_released_criteria case search_first_released when "draft" { :first_released.exists => false } when "published" { :first_released.exists => true } else {} end end end end
{ "content_hash": "178a4682f7692a0cdb3c5d2ccb6bf6d8", "timestamp": "", "source": "github", "line_count": 296, "max_line_length": 126, "avg_line_length": 34.070945945945944, "alnum_prop": 0.5789786812097174, "repo_name": "bee01/shirasagi", "id": "da134204104e38cb250e48b7897d28a0c4e531a9", "size": "10085", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/models/concerns/cms/addon/page_search.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "409519" }, { "name": "CoffeeScript", "bytes": "22243" }, { "name": "HTML", "bytes": "1476372" }, { "name": "JavaScript", "bytes": "4808072" }, { "name": "Ruby", "bytes": "3928693" }, { "name": "Shell", "bytes": "15315" } ], "symlink_target": "" }
// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.impala.catalog; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import org.apache.log4j.Logger; import com.cloudera.impala.thrift.TTableName; import com.cloudera.impala.util.HdfsCachingUtil; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; /** * Class that manages scheduling the loading of table metadata from the Hive Metastore and * the Hadoop NameNode. Loads tables using a pool of table loading threads. New load * requests can be submitted using loadAsync(), which will schedule the load when the * next thread becomes available. Also manages prioritized background table loading by * reading from a deque of table names to determine which table to load next. Tables added * to the head of the deque will be loaded before tables added to the tail, so the loading * order can be prioritized (see prioritizeLoad()/backgroundLoad()). */ public class TableLoadingMgr { /** * Represents the result of an asynchronous Table loading request. Calling * get() will block until the Table has completed loading. When finished * processing the request, call close() to clean up. */ public class LoadRequest { private final Future<Table> tblTask_; private final TTableName tblName_; private LoadRequest(TTableName tblName, Future<Table> tblTask) { tblTask_ = tblTask; tblName_ = tblName; } /** * Blocks until the table has finished loading and returns the result. If any errors * were encountered while loading the table an IncompleteTable will be returned. */ public Table get() { Table tbl; try { tbl = tblTask_.get(); } catch (Exception e) { tbl = IncompleteTable.createFailedMetadataLoadTable( TableId.createInvalidId(), catalog_.getDb(tblName_.getDb_name()), tblName_.getTable_name(), new TableLoadingException(e.getMessage(), e)); } Preconditions.checkState(tbl.isLoaded()); return tbl; } /** * Cleans up the in-flight load request matching the given table name. Will not * cancel the load if it is still in progress, frees a slot should another * load for the same table come in. Can be called multiple times. */ public void close() { synchronized (loadingTables_) { if (loadingTables_.get(tblName_) == tblTask_) loadingTables_.remove(tblName_); } } } private static final Logger LOG = Logger.getLogger(TableLoadingMgr.class); // A thread safe blocking deque that is used to prioritize the loading of table // metadata. The CatalogServer has a background thread that will always add unloaded // tables to the tail of the deque. However, a call to prioritizeLoad() will add // tables to the head of the deque. The next table to load is always taken from the // head of the deque. May contain the same table multiple times, but a second // attempt to load the table metadata will be a no-op. private final LinkedBlockingDeque<TTableName> tableLoadingDeque_ = new LinkedBlockingDeque<TTableName>(); // A thread safe HashSet of table names that are in the tableLoadingDeque_. Used to // efficiently check for existence of items in the deque. // Updates may lead/lag updates to the tableLoadingDeque_ - they are added to this set // immediately before being added to the deque and removed immediately after removing // from the deque. The fact the updates are not synchronized shouldn't impact // functionality since this set is only used for efficient lookups. private final Set<TTableName> tableLoadingSet_ = Collections.synchronizedSet(new HashSet<TTableName>()); // Map of table name to a FutureTask associated with the table load. Used to // prevent duplicate loads of the same table. private final ConcurrentHashMap<TTableName, FutureTask<Table>> loadingTables_ = new ConcurrentHashMap<TTableName, FutureTask<Table>>(); // Map of table name to the cache directives that are being waited on for that table. // Once all directives have completed, the table's metadata will be refreshed and // the table will be removed from this map. // A caching operation may take a long time to complete, so to maximize query // throughput it is preferable to allow the user to continue to run queries against // the table while a cache request completes in the background. private final Map<TTableName, List<Long>> pendingTableCacheDirs_ = Maps.newHashMap(); // The number of parallel threads to use to load table metadata. Should be set to a // value that provides good throughput while not putting too much stress on the // metastore. private final int numLoadingThreads_; // Pool of numLoadingThreads_ threads that loads table metadata. If additional tasks // are submitted to the pool after it is full, they will be queued and executed when // the next thread becomes available. There is no hard upper limit on the number of // pending tasks (no work will be rejected, but memory consumption is unbounded). private final ExecutorService tblLoadingPool_; // Thread that incrementally refreshes tables in the background. Used to update a // table's metadata after a long running operation completes, such as marking a // table as cached. There is no hard upper limit on the number of pending tasks // (no work will be rejected, but memory consumption is unbounded). If this thread // dies it will be automatically restarted. // The tables to process are read from the resfreshThreadWork_ queue. ExecutorService asyncRefreshThread_ = Executors.newSingleThreadExecutor(); // Tables for the async refresh thread to process. Synchronization must be handled // externally. private final LinkedBlockingQueue<TTableName> refreshThreadWork_ = new LinkedBlockingQueue<TTableName>(); private final CatalogServiceCatalog catalog_; private final TableLoader tblLoader_; public TableLoadingMgr(CatalogServiceCatalog catalog, int numLoadingThreads) { catalog_ = catalog; tblLoader_ = new TableLoader(catalog_); numLoadingThreads_ = numLoadingThreads; tblLoadingPool_ = Executors.newFixedThreadPool(numLoadingThreads_); // Start the background table loading threads. startTableLoadingThreads(); // Start the asyncRefreshThread_. Currently used to wait for cache directives to // complete in the background. asyncRefreshThread_.submit(new Callable<Void>() { @Override public Void call() throws Exception { while(true) { execAsyncRefreshWork(refreshThreadWork_.take()); } }}); } /** * Prioritizes the loading of the given table. */ public void prioritizeLoad(TTableName tblName) { tableLoadingSet_.add(tblName); tableLoadingDeque_.offerFirst(tblName); } /** * Submits a single table for background (low priority) loading. */ public void backgroundLoad(TTableName tblName) { // Only queue for background loading if the table doesn't already exist // in the table loading set. if (tableLoadingSet_.add(tblName)) { tableLoadingDeque_.offerLast(tblName); } } /** * Adds a list of cache directive IDs to watch for the given table name. * The asyncRefreshThread_ will process the cache directives and once all directives * complete (data has been cached or no progress is being made), the * asyncRefreshThread_ will refresh the table metadata. After processing the * request the watch will be deleted. */ public void watchCacheDirs(List<Long> cacheDirIds, final TTableName tblName) { synchronized (pendingTableCacheDirs_) { // A single table may have multiple pending cache requests since one request // gets submitted per-partition. List<Long> existingCacheReqIds = pendingTableCacheDirs_.get(tblName); if (existingCacheReqIds == null) { existingCacheReqIds = cacheDirIds; pendingTableCacheDirs_.put(tblName, cacheDirIds); refreshThreadWork_.add(tblName); } else { cacheDirIds.addAll(cacheDirIds); } } } /** * Loads a table asynchronously, returning a LoadRequest that can be used to get * the result (a Table). If there is already a load in flight for this table name, * the same underlying loading task (Future) will be used, helping to prevent duplicate * loads of the same table. * Can also be used to perform an incremental refresh of an existing table, by passing * the previous Table value in previousTbl. This may speedup the loading process, but * may return a stale object. */ public LoadRequest loadAsync(final TTableName tblName, final Table previousTbl) throws DatabaseNotFoundException { final Db parentDb = catalog_.getDb(tblName.getDb_name()); if (parentDb == null) { throw new DatabaseNotFoundException( "Database '" + tblName.getDb_name() + "' was not found."); } FutureTask<Table> tableLoadTask = new FutureTask<Table>(new Callable<Table>() { @Override public Table call() throws Exception { return tblLoader_.load(parentDb, tblName.table_name, previousTbl); }}); FutureTask<Table> existingValue = loadingTables_.putIfAbsent(tblName, tableLoadTask); if (existingValue == null) { // There was no existing value, submit a new load request. tblLoadingPool_.execute(tableLoadTask); } else { tableLoadTask = existingValue; } return new LoadRequest(tblName, tableLoadTask); } /** * Starts table loading threads in a fixed sized thread pool with a size * defined by NUM_TBL_LOADING_THREADS. Each thread polls the tableLoadingDeque_ * for new tables to load. */ private void startTableLoadingThreads() { ExecutorService loadingPool = Executors.newFixedThreadPool(numLoadingThreads_); try { for (int i = 0; i < numLoadingThreads_; ++i) { loadingPool.execute(new Runnable() { @Override public void run() { while (true) { try { loadNextTable(); } catch (Exception e) { LOG.error("Error loading table: ", e); // Ignore exception. } } } }); } } finally { loadingPool.shutdown(); } } /** * Gets the next table name to load off the head of the table loading queue. If * the queue is empty, this will block until a new table is added. */ private void loadNextTable() throws InterruptedException { // Always get the next table from the head of the deque. final TTableName tblName = tableLoadingDeque_.takeFirst(); tableLoadingSet_.remove(tblName); LOG.debug("Loading next table. Remaining items in queue: " + tableLoadingDeque_.size()); try { // TODO: Instead of calling "getOrLoad" here we could call "loadAsync". We would // just need to add a mechanism for moving loaded tables into the Catalog. catalog_.getOrLoadTable(tblName.getDb_name(), tblName.getTable_name()); } catch (DatabaseNotFoundException e) { // Ignore. } } /** * Executes all async refresh work for the specified table name. */ private void execAsyncRefreshWork(TTableName tblName) { if (!waitForCacheDirs(tblName)) return; try { // Reload the table metadata to pickup the new cached block location information. catalog_.reloadTable(tblName); } catch (CatalogException e) { LOG.error("Error reloading cached table: ", e); } } /** * Waits for all pending cache directives on a table to complete. * Returns true if a refresh is needed and false if a refresh is not needed. */ private boolean waitForCacheDirs(TTableName tblName) { boolean isRefreshNeeded = false; // Keep processing cache directives for this table until there are none left. while (true) { // Get all pending requests for this table. List<Long> cacheDirIds = null; synchronized (pendingTableCacheDirs_) { cacheDirIds = pendingTableCacheDirs_.remove(tblName); } if (cacheDirIds == null || cacheDirIds.size() == 0) return isRefreshNeeded; isRefreshNeeded = true; // Wait for each cache request to complete. for (Long dirId: cacheDirIds) { if (dirId == null) continue; try { HdfsCachingUtil.waitForDirective(dirId); } catch (Exception e) { LOG.error(String.format( "Error waiting for cache request %d to complete: ", dirId), e); } } } } }
{ "content_hash": "d0a94cdd661f1be51576313989170a56", "timestamp": "", "source": "github", "line_count": 334, "max_line_length": 89, "avg_line_length": 40.81137724550898, "alnum_prop": 0.7048639131391681, "repo_name": "rampage644/impala-cut", "id": "89818f72eb443928231f8e07b8a5d51479949236", "size": "13631", "binary": false, "copies": "2", "ref": "refs/heads/executor", "path": "fe/src/main/java/com/cloudera/impala/catalog/TableLoadingMgr.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "279767" }, { "name": "C++", "bytes": "4596364" }, { "name": "Java", "bytes": "2424265" }, { "name": "Objective-C", "bytes": "15162" }, { "name": "PHP", "bytes": "361" }, { "name": "Python", "bytes": "1254137" }, { "name": "Shell", "bytes": "95400" } ], "symlink_target": "" }
.saveErrorPopupSocial .modal-logo { position: absolute; top: -20px; left: -20px; width: 48px; height: 48px; background: url(../_resources/icons/warning-icon.png); background-size: 42px 42px; background-repeat: no-repeat; border: 4px solid #FFF; border-radius: 24px; } .saveErrorPopupSocial .tooltip.in { opacity: 1.0; } .saveErrorPopupSocial .panel1 .tooltip-inner { max-width: 266px !important; width: 266px; padding-bottom: 8px; } .saveErrorPopupSocial .panel2 { margin-top: 10px; } .saveErrorPopupSocial .panel3 { margin-top: 25px; } .saveErrorPopupSocial .panel2 .form-group { margin-left: 10px; } .saveErrorPopupSocial .modal-footer { padding-top: 30px; } .saveErrorPopupSocial .stop-asking { float: left; margin-top: -6px; margin-left: 10px; } .saveErrorPopupSocial .stop-asking label.disabled { color: #CCC; cursor: not-allowed; }
{ "content_hash": "79650d73d27120473ac4ac4552dbda63", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 55, "avg_line_length": 18.79591836734694, "alnum_prop": 0.6807817589576547, "repo_name": "anarosner/storymap-shortlist-case-studies", "id": "84945dc3b1c0faa482ee9c67618435e62a447f37", "size": "921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/storymaps/common/builder/SaveErrorPopupSocial.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "8450" }, { "name": "CSS", "bytes": "350680" }, { "name": "HTML", "bytes": "104766" }, { "name": "JavaScript", "bytes": "2942609" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Money\PHPUnit; use Money\Currencies\AggregateCurrencies; use Money\Currencies\BitcoinCurrencies; use Money\Currencies\ISOCurrencies; use Money\Formatter\IntlMoneyFormatter; use Money\Money; use NumberFormatter; use SebastianBergmann\Comparator\ComparisonFailure; use function assert; /** * The comparator is for comparing Money objects in PHPUnit tests. * * Add this to your bootstrap file: * * \SebastianBergmann\Comparator\Factory::getInstance()->register(new \Money\PHPUnit\Comparator()); * * @internal do not use within your sources: this comparator is only to be used within the test suite of this library * * @psalm-suppress PropertyNotSetInConstructor the parent implementation includes factories that cannot be initialized here */ final class Comparator extends \SebastianBergmann\Comparator\Comparator { private IntlMoneyFormatter $formatter; public function __construct() { parent::__construct(); $currencies = new AggregateCurrencies([ new ISOCurrencies(), new BitcoinCurrencies(), ]); $numberFormatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY); $this->formatter = new IntlMoneyFormatter($numberFormatter, $currencies); } /** {@inheritDoc} */ public function accepts($expected, $actual) { return $expected instanceof Money && $actual instanceof Money; } /** {@inheritDoc} */ public function assertEquals( $expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false ): void { assert($expected instanceof Money); assert($actual instanceof Money); if (! $expected->equals($actual)) { throw new ComparisonFailure($expected, $actual, $this->formatter->format($expected), $this->formatter->format($actual), false, 'Failed asserting that two Money objects are equal.'); } } }
{ "content_hash": "5a772653a3a9db8bb309cd08225dbfa3", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 193, "avg_line_length": 29.984848484848484, "alnum_prop": 0.686710459828196, "repo_name": "moneyphp/money", "id": "28a5d4ea0f93237822e27c311635f39172ed042f", "size": "1979", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/PHPUnit/Comparator.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "597" }, { "name": "PHP", "bytes": "280181" }, { "name": "Shell", "bytes": "476" } ], "symlink_target": "" }
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives //= require "lib/es5-shim.min.js" //= require "lib/jquery-1.7.2.js" //= require "lib/jquery.url-1.0.js" //= require "lib/jquery-pinOnScroll.js" //= require "lib/jquery_no_conflict.js" //= require "lib/prototype-1.6.0.js" //= require "lib/scriptaculous-1.8.0.js" //= require "lib/bootstrap-2.3.2.min.js" //= require "lib/angular-1.0.8.js" //= require "lib/angular-resource.1.0.8.min.js" //= require "lib/effects-1.8.0.js" //= require "lib/accordion-2.0.js" //= require "lib/controls-1.8.0.js" //= require "lib/dragdrop-1.8.0.js" //= require "lib/highcharts-2.3.3.min.js" //= require "lib/jquery-ui-1.7.3.custom.min.js" //= require "lib/jquery.autocomplete-1.1.js" //= require "lib/jquery.ba-throttle-debounce-1.1.min.js" //= require "lib/jquery.dirtyform.js" //= require "lib/jquery.highlight-3.0.js" //= require "lib/jquery.tipTip-1.3.js" //= require "lib/jquery.treeview-1.5pre.js" //= require "lib/jquery.validate-1.5.5.js" //= require "lib/modalbox-1.6.1.js" //= require "lib/slider-1.8.0.js" //= require "lib/trimpath-template-1.0.38.js" //= require "lib/ui.core-1.7.3.js" //= require "lib/ui.dialog-1.7.3.js" //= require "lib/lodash.js" //= require "lib/moment-2.18.1.js" //= require "lib/moment-duration-format-1.3.0.js" //= require "lib/humanize-for-gocd.js" //= require "lib/pako_inflate-1.0.5.js" //= require "ansi_up.js" //= require "crel.js" //= require "json_to_css.js" //= require "util.js" //= require "micro_content_popup.js" //= require "ajax_popup_handler.js" //= require "compare_pipelines.js" //= require "console_log_tailing.js" //= require "js-routes" //= require_directory .
{ "content_hash": "0fb13c11ddf9ffdc11277ea954c871fc", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 103, "avg_line_length": 38.175438596491226, "alnum_prop": 0.6911764705882353, "repo_name": "MFAnderson/gocd", "id": "c24070f1aba3bbb1b38cbcfd011480abcfb1e528", "size": "2777", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/webapp/WEB-INF/rails.new/app/assets/javascripts/application.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8637" }, { "name": "CSS", "bytes": "528991" }, { "name": "FreeMarker", "bytes": "182" }, { "name": "Groovy", "bytes": "18840" }, { "name": "HTML", "bytes": "664995" }, { "name": "Java", "bytes": "16802174" }, { "name": "JavaScript", "bytes": "3011856" }, { "name": "NSIS", "bytes": "19211" }, { "name": "PowerShell", "bytes": "743" }, { "name": "Ruby", "bytes": "3659389" }, { "name": "SQLPL", "bytes": "9050" }, { "name": "Shell", "bytes": "197638" }, { "name": "XSLT", "bytes": "161277" } ], "symlink_target": "" }
include ../../Library/GNU.mk Title= SDL Name= sdl Version= 1.2.15 Site= http://www.libsdl.org/ Source= http://www.libsdl.org/release/SDL-$(Version).tar.gz License= LGPL UncompressedName = sdl-$(Version) # Just in case GnuConfigureExtra += --disable-video-x11 define test_hook $(BinDir)/sdl-config --version endef
{ "content_hash": "d4313498a9b45f14a4ea0cd5019e7f3f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 60, "avg_line_length": 20.0625, "alnum_prop": 0.7133956386292835, "repo_name": "rudix-mac/rudix", "id": "3ba10d672e2758788affa111b186091ea08c726f", "size": "321", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "Ports/sdl/Makefile", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "630" }, { "name": "Dockerfile", "bytes": "350" }, { "name": "Makefile", "bytes": "163271" }, { "name": "Python", "bytes": "14491" }, { "name": "Roff", "bytes": "4890" }, { "name": "Shell", "bytes": "8327" } ], "symlink_target": "" }
package com.jetbrains.python.psi; /** * @author yole */ public interface PyBoolLiteralExpression extends PyLiteralExpression { boolean getValue(); }
{ "content_hash": "f34c645ef6fc0bcffec0e5e1e8c8e8ed", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 70, "avg_line_length": 15.6, "alnum_prop": 0.75, "repo_name": "consulo/consulo-python", "id": "32ffda1b1714f4df499d20f74227869eca123e9d", "size": "756", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python-psi-api/src/main/java/com/jetbrains/python/psi/PyBoolLiteralExpression.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "24534" }, { "name": "Java", "bytes": "6520797" }, { "name": "Lex", "bytes": "13306" }, { "name": "Python", "bytes": "1029937" }, { "name": "Roff", "bytes": "111" } ], "symlink_target": "" }
var assert = require('assert'); var adapter = require('../index.js'); var config = require('./support/config.js'); var makeSlowQuery = require('./support/makeSlowQuery.js'); var ConnectionPool = false; try { ConnectionPool = require('any-db-pool'); } catch (e) { ConnectionPool = false; } var delaySeconds = 2; var ifPoolExists = ConnectionPool ? describe : describe.skip; ifPoolExists('Slow query', function(){ 'use strict'; this.timeout((delaySeconds + 1) * 1000); var connection = false; before(function(done){ connection = adapter.createConnection(config, function(err){ assert.ifError(err); done(); }); connection.on('error', function(err){ assert.ifError(err); }); }); after(function(done){ if (connection) { connection.end(done); } else { done('connection missing'); } }); it('should take intentionally long time to finish', function(done){ makeSlowQuery(connection, delaySeconds, done); }); }); ifPoolExists('Pool', function(){ 'use strict'; this.timeout((delaySeconds + 1) * 1000); var pool = false; before(function(){ var poolParams = { min: 5, max: 15, reset: function(conn, done) { conn.query('ROLLBACK TRANSACTION', done); } }; pool = new ConnectionPool(adapter, config, poolParams); }); after(function(done){ pool.close(done); }); it('should exist', function(){ assert.ok(pool); }); ['query', 'acquire', 'release', 'close'].forEach(function(name){ it('should provide `'+name+'()` method', function(){ assert.ok(pool.query, 'There should be a `'+name+'` provided by the ConnectionPool object'); assert.ok(pool.query instanceof Function, '`'+name+'()` should be a function'); }); }); it('should run simple query', function(done){ pool.query('SELECT 1 AS test', function(err, result){ assert.ifError(err); assert.strictEqual(result.rowCount, 1, 'There should be 1 row there'); done(); }); }); it('should acquire two different connections', function(done){ var ids = {length: 0}; var todo = 2; var onAcquired = function(id){ ids[id] = true; ids.length++; if (ids.length >= todo) { onDone(); } }; var onDone = function(){ var keys = Object.keys(ids); assert.strictEqual(ids.length, todo, 'There should be '+todo+' connections acquired'); assert.strictEqual(ids.length, keys.length - 1, 'There should be '+todo+' connections acquired'); done(); }; pool.acquire(function(err, connection){ assert.ifError(err); onAcquired(connection.id); pool.release(connection); }); pool.acquire(function(err, connection){ assert.ifError(err); onAcquired(connection.id); pool.release(connection); }); }); it('should run multiple queries on multiple connections asynchronously', function(done){ var results = []; var delays = [4, 3, 2, 1]; this.timeout((delays[0]+1) * 2000); var onResult = function(value){ results.push(value); if (results.length >= delays.length) { onDone(); } }; var onDone = function(){ assert.strictEqual(results.length, delays.length, 'There should be '+delays.length+' result values'); delays.forEach(function(delay, index){ assert.strictEqual(results[delay-1], index, 'Result '+(delay-1)+' should be equal '+index); }); done(); }; delays.forEach(function(delay, index){ pool.acquire(function(err, connection){ assert.ifError(err); makeSlowQuery(connection, delay, function(){ onResult(index); pool.release(connection); }); }); }); }); });
{ "content_hash": "87a66085168474f8b5397e00dab6addb", "timestamp": "", "source": "github", "line_count": 159, "max_line_length": 104, "avg_line_length": 22.245283018867923, "alnum_prop": 0.6485722363584959, "repo_name": "Hypermediaisobar-admin/node-any-db-mssql", "id": "bd148ffcd09cd22776e5b5c883309e7905b43134", "size": "3537", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/pool.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "62025" } ], "symlink_target": "" }
#ifndef __USB100_H #define __USB100_H #if __GNUC__ >=3 #pragma GCC system_header #endif #ifdef __cplusplus extern "C" { #endif #include "ntddk.h" #define MAXIMUM_USB_STRING_LENGTH 255 #define USB_DEVICE_CLASS_RESERVED 0x00 #define USB_DEVICE_CLASS_AUDIO 0x01 #define USB_DEVICE_CLASS_COMMUNICATIONS 0x02 #define USB_DEVICE_CLASS_HUMAN_INTERFACE 0x03 #define USB_DEVICE_CLASS_MONITOR 0x04 #define USB_DEVICE_CLASS_PHYSICAL_INTERFACE 0x05 #define USB_DEVICE_CLASS_POWER 0x06 #define USB_DEVICE_CLASS_PRINTER 0x07 #define USB_DEVICE_CLASS_STORAGE 0x08 #define USB_DEVICE_CLASS_HUB 0x09 #define USB_DEVICE_CLASS_VENDOR_SPECIFIC 0xFF #define USB_RESERVED_DESCRIPTOR_TYPE 0x06 #define USB_CONFIG_POWER_DESCRIPTOR_TYPE 0x07 #define USB_INTERFACE_POWER_DESCRIPTOR_TYPE 0x08 #define USB_REQUEST_GET_STATUS 0x00 #define USB_REQUEST_CLEAR_FEATURE 0x01 #define USB_REQUEST_SET_FEATURE 0x03 #define USB_REQUEST_SET_ADDRESS 0x05 #define USB_REQUEST_GET_DESCRIPTOR 0x06 #define USB_REQUEST_SET_DESCRIPTOR 0x07 #define USB_REQUEST_GET_CONFIGURATION 0x08 #define USB_REQUEST_SET_CONFIGURATION 0x09 #define USB_REQUEST_GET_INTERFACE 0x0A #define USB_REQUEST_SET_INTERFACE 0x0B #define USB_REQUEST_SYNC_FRAME 0x0C #define USB_GETSTATUS_SELF_POWERED 0x01 #define USB_GETSTATUS_REMOTE_WAKEUP_ENABLED 0x02 #define BMREQUEST_HOST_TO_DEVICE 0 #define BMREQUEST_DEVICE_TO_HOST 1 #define BMREQUEST_STANDARD 0 #define BMREQUEST_CLASS 1 #define BMREQUEST_VENDOR 2 #define BMREQUEST_TO_DEVICE 0 #define BMREQUEST_TO_INTERFACE 1 #define BMREQUEST_TO_ENDPOINT 2 #define BMREQUEST_TO_OTHER 3 /* USB_COMMON_DESCRIPTOR.bDescriptorType constants */ #define USB_DEVICE_DESCRIPTOR_TYPE 0x01 #define USB_CONFIGURATION_DESCRIPTOR_TYPE 0x02 #define USB_STRING_DESCRIPTOR_TYPE 0x03 #define USB_INTERFACE_DESCRIPTOR_TYPE 0x04 #define USB_ENDPOINT_DESCRIPTOR_TYPE 0x05 typedef struct _USB_COMMON_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; } USB_COMMON_DESCRIPTOR, *PUSB_COMMON_DESCRIPTOR; #define USB_DESCRIPTOR_MAKE_TYPE_AND_INDEX(d, i) ((USHORT)((USHORT)d << 8 | i)) /* USB_CONFIGURATION_DESCRIPTOR.bmAttributes constants */ #define USB_CONFIG_POWERED_MASK 0xc0 #define USB_CONFIG_BUS_POWERED 0x80 #define USB_CONFIG_SELF_POWERED 0x40 #define USB_CONFIG_REMOTE_WAKEUP 0x20 #include <pshpack1.h> typedef struct _USB_CONFIGURATION_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; USHORT wTotalLength; UCHAR bNumInterfaces; UCHAR bConfigurationValue; UCHAR iConfiguration; UCHAR bmAttributes; UCHAR MaxPower; } USB_CONFIGURATION_DESCRIPTOR, *PUSB_CONFIGURATION_DESCRIPTOR; #include <poppack.h> typedef struct _USB_DEVICE_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; USHORT bcdUSB; UCHAR bDeviceClass; UCHAR bDeviceSubClass; UCHAR bDeviceProtocol; UCHAR bMaxPacketSize0; USHORT idVendor; USHORT idProduct; USHORT bcdDevice; UCHAR iManufacturer; UCHAR iProduct; UCHAR iSerialNumber; UCHAR bNumConfigurations; } USB_DEVICE_DESCRIPTOR, *PUSB_DEVICE_DESCRIPTOR; #define USB_ENDPOINT_DIRECTION_MASK 0x80 #define USB_ENDPOINT_DIRECTION_OUT(x) (!((x) & USB_ENDPOINT_DIRECTION_MASK)) #define USB_ENDPOINT_DIRECTION_IN(x) ((x) & USB_ENDPOINT_DIRECTION_MASK) /* USB_ENDPOINT_DESCRIPTOR.bmAttributes constants */ #define USB_ENDPOINT_TYPE_MASK 0x03 #define USB_ENDPOINT_TYPE_CONTROL 0x00 #define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01 #define USB_ENDPOINT_TYPE_BULK 0x02 #define USB_ENDPOINT_TYPE_INTERRUPT 0x03 #include <pshpack1.h> typedef struct _USB_ENDPOINT_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; UCHAR bEndpointAddress; UCHAR bmAttributes; USHORT wMaxPacketSize; UCHAR bInterval; } USB_ENDPOINT_DESCRIPTOR, *PUSB_ENDPOINT_DESCRIPTOR; #include <poppack.h> #define USB_FEATURE_ENDPOINT_STALL 0x0000 #define USB_FEATURE_REMOTE_WAKEUP 0x0001 typedef struct _USB_INTERFACE_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; UCHAR bInterfaceNumber; UCHAR bAlternateSetting; UCHAR bNumEndpoints; UCHAR bInterfaceClass; UCHAR bInterfaceSubClass; UCHAR bInterfaceProtocol; UCHAR iInterface; } USB_INTERFACE_DESCRIPTOR, *PUSB_INTERFACE_DESCRIPTOR; typedef struct _USB_STRING_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; WCHAR bString[1]; } USB_STRING_DESCRIPTOR, *PUSB_STRING_DESCRIPTOR; #include <pshpack1.h> typedef struct _USB_HUB_DESCRIPTOR { UCHAR bDescriptorLength; UCHAR bDescriptorType; UCHAR bNumberOfPorts; USHORT wHubCharacteristics; UCHAR bPowerOnToPowerGood; UCHAR bHubControlCurrent; UCHAR bRemoveAndPowerMask[64]; } USB_HUB_DESCRIPTOR, *PUSB_HUB_DESCRIPTOR; #include <poppack.h> #define USB_SUPPORT_D0_COMMAND 0x01 #define USB_SUPPORT_D1_COMMAND 0x02 #define USB_SUPPORT_D2_COMMAND 0x04 #define USB_SUPPORT_D3_COMMAND 0x08 #define USB_SUPPORT_D1_WAKEUP 0x10 #define USB_SUPPORT_D2_WAKEUP 0x20 typedef struct _USB_CONFIGURATION_POWER_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; UCHAR SelfPowerConsumedD0[3]; UCHAR bPowerSummaryId; UCHAR bBusPowerSavingD1; UCHAR bSelfPowerSavingD1; UCHAR bBusPowerSavingD2; UCHAR bSelfPowerSavingD2; UCHAR bBusPowerSavingD3; UCHAR bSelfPowerSavingD3; USHORT TransitionTimeFromD1; USHORT TransitionTimeFromD2; USHORT TransitionTimeFromD3; } USB_CONFIGURATION_POWER_DESCRIPTOR, *PUSB_CONFIGURATION_POWER_DESCRIPTOR; #define USB_FEATURE_INTERFACE_POWER_D0 0x0002 #define USB_FEATURE_INTERFACE_POWER_D1 0x0003 #define USB_FEATURE_INTERFACE_POWER_D2 0x0004 #define USB_FEATURE_INTERFACE_POWER_D3 0x0005 #include <pshpack1.h> typedef struct _USB_INTERFACE_POWER_DESCRIPTOR { UCHAR bLength; UCHAR bDescriptorType; UCHAR bmCapabilitiesFlags; UCHAR bBusPowerSavingD1; UCHAR bSelfPowerSavingD1; UCHAR bBusPowerSavingD2; UCHAR bSelfPowerSavingD2; UCHAR bBusPowerSavingD3; UCHAR bSelfPowerSavingD3; USHORT TransitionTimeFromD1; USHORT TransitionTimeFromD2; USHORT TransitionTimeFromD3; } USB_INTERFACE_POWER_DESCRIPTOR, *PUSB_INTERFACE_POWER_DESCRIPTOR; #include <poppack.h> #ifdef __cplusplus } #endif #endif /* __USB100_H */
{ "content_hash": "71eb0fe2f6518d71729c85939af2fdfc", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 79, "avg_line_length": 30.442396313364057, "alnum_prop": 0.7216167120799274, "repo_name": "waterhui/MinGW", "id": "53b774ba296aed5ff489adfb3a7679812b2b5fd3", "size": "7196", "binary": false, "copies": "23", "ref": "refs/heads/master", "path": "include/ddk/usb100.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "99" }, { "name": "C", "bytes": "5926289" }, { "name": "C++", "bytes": "8310854" }, { "name": "Groff", "bytes": "2090952" }, { "name": "Logos", "bytes": "7649" }, { "name": "Objective-C", "bytes": "5514" }, { "name": "Python", "bytes": "119034" }, { "name": "Shell", "bytes": "6705" } ], "symlink_target": "" }
package jkind.lustre; import java.util.List; import jkind.lustre.visitors.ExprVisitor; import jkind.util.Util; public class ArrayExpr extends Expr { public final List<Expr> elements; public ArrayExpr(Location loc, List<Expr> elements) { super(loc); this.elements = Util.safeList(elements); } public ArrayExpr(List<Expr> elements) { this(Location.NULL, elements); } @Override public <T> T accept(ExprVisitor<T> visitor) { return visitor.visit(this); } }
{ "content_hash": "1fc7595206317c63c956249954f5cee3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 54, "avg_line_length": 19.791666666666668, "alnum_prop": 0.7347368421052631, "repo_name": "agacek/jkind", "id": "4c976bff243e54dd6ffdf386fcc4e61771720fb1", "size": "475", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jkind-common/src/jkind/lustre/ArrayExpr.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ANTLR", "bytes": "6792" }, { "name": "Batchfile", "bytes": "176" }, { "name": "CSS", "bytes": "413" }, { "name": "Java", "bytes": "1026059" }, { "name": "Makefile", "bytes": "86" }, { "name": "Shell", "bytes": "1829" } ], "symlink_target": "" }
========= lib/flags ========= .. automodule :: lib.flags :members:
{ "content_hash": "cc50fcccadd8c959b5654c43525c855d", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 26, "avg_line_length": 11.833333333333334, "alnum_prop": 0.4647887323943662, "repo_name": "postfix/https-ids", "id": "8478208d3f1886a0a2d71ee30956e277c5d21cff", "size": "71", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/doc_src/lib/flags.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "178601" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/analytics/admin/v1beta/analytics_admin.proto package com.google.analytics.admin.v1beta; /** * * * <pre> * Request message for CreateGoogleAdsLink RPC * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest} */ public final class CreateGoogleAdsLinkRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) CreateGoogleAdsLinkRequestOrBuilder { private static final long serialVersionUID = 0L; // Use CreateGoogleAdsLinkRequest.newBuilder() to construct. private CreateGoogleAdsLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private CreateGoogleAdsLinkRequest() { parent_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new CreateGoogleAdsLinkRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_CreateGoogleAdsLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_CreateGoogleAdsLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.class, com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.Builder.class); } public static final int PARENT_FIELD_NUMBER = 1; private volatile java.lang.Object parent_; /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int GOOGLE_ADS_LINK_FIELD_NUMBER = 2; private com.google.analytics.admin.v1beta.GoogleAdsLink googleAdsLink_; /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the googleAdsLink field is set. */ @java.lang.Override public boolean hasGoogleAdsLink() { return googleAdsLink_ != null; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The googleAdsLink. */ @java.lang.Override public com.google.analytics.admin.v1beta.GoogleAdsLink getGoogleAdsLink() { return googleAdsLink_ == null ? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance() : googleAdsLink_; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ @java.lang.Override public com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder getGoogleAdsLinkOrBuilder() { return getGoogleAdsLink(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (googleAdsLink_ != null) { output.writeMessage(2, getGoogleAdsLink()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (googleAdsLink_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getGoogleAdsLink()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest)) { return super.equals(obj); } com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest other = (com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) obj; if (!getParent().equals(other.getParent())) return false; if (hasGoogleAdsLink() != other.hasGoogleAdsLink()) return false; if (hasGoogleAdsLink()) { if (!getGoogleAdsLink().equals(other.getGoogleAdsLink())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); if (hasGoogleAdsLink()) { hash = (37 * hash) + GOOGLE_ADS_LINK_FIELD_NUMBER; hash = (53 * hash) + getGoogleAdsLink().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Request message for CreateGoogleAdsLink RPC * </pre> * * Protobuf type {@code google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_CreateGoogleAdsLinkRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_CreateGoogleAdsLinkRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.class, com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.Builder.class); } // Construct using com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); parent_ = ""; if (googleAdsLinkBuilder_ == null) { googleAdsLink_ = null; } else { googleAdsLink_ = null; googleAdsLinkBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.analytics.admin.v1beta.AnalyticsAdminProto .internal_static_google_analytics_admin_v1beta_CreateGoogleAdsLinkRequest_descriptor; } @java.lang.Override public com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest getDefaultInstanceForType() { return com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.getDefaultInstance(); } @java.lang.Override public com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest build() { com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest buildPartial() { com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest result = new com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest(this); result.parent_ = parent_; if (googleAdsLinkBuilder_ == null) { result.googleAdsLink_ = googleAdsLink_; } else { result.googleAdsLink_ = googleAdsLinkBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) { return mergeFrom((com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest other) { if (other == com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest.getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; onChanged(); } if (other.hasGoogleAdsLink()) { mergeGoogleAdsLink(other.getGoogleAdsLink()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); break; } // case 10 case 18: { input.readMessage(getGoogleAdsLinkFieldBuilder().getBuilder(), extensionRegistry); break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private java.lang.Object parent_ = ""; /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; onChanged(); return this; } /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); onChanged(); return this; } /** * * * <pre> * Required. Example format: properties/1234 * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; onChanged(); return this; } private com.google.analytics.admin.v1beta.GoogleAdsLink googleAdsLink_; private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.GoogleAdsLink, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder, com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder> googleAdsLinkBuilder_; /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return Whether the googleAdsLink field is set. */ public boolean hasGoogleAdsLink() { return googleAdsLinkBuilder_ != null || googleAdsLink_ != null; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> * * @return The googleAdsLink. */ public com.google.analytics.admin.v1beta.GoogleAdsLink getGoogleAdsLink() { if (googleAdsLinkBuilder_ == null) { return googleAdsLink_ == null ? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance() : googleAdsLink_; } else { return googleAdsLinkBuilder_.getMessage(); } } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setGoogleAdsLink(com.google.analytics.admin.v1beta.GoogleAdsLink value) { if (googleAdsLinkBuilder_ == null) { if (value == null) { throw new NullPointerException(); } googleAdsLink_ = value; onChanged(); } else { googleAdsLinkBuilder_.setMessage(value); } return this; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder setGoogleAdsLink( com.google.analytics.admin.v1beta.GoogleAdsLink.Builder builderForValue) { if (googleAdsLinkBuilder_ == null) { googleAdsLink_ = builderForValue.build(); onChanged(); } else { googleAdsLinkBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder mergeGoogleAdsLink(com.google.analytics.admin.v1beta.GoogleAdsLink value) { if (googleAdsLinkBuilder_ == null) { if (googleAdsLink_ != null) { googleAdsLink_ = com.google.analytics.admin.v1beta.GoogleAdsLink.newBuilder(googleAdsLink_) .mergeFrom(value) .buildPartial(); } else { googleAdsLink_ = value; } onChanged(); } else { googleAdsLinkBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public Builder clearGoogleAdsLink() { if (googleAdsLinkBuilder_ == null) { googleAdsLink_ = null; onChanged(); } else { googleAdsLink_ = null; googleAdsLinkBuilder_ = null; } return this; } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1beta.GoogleAdsLink.Builder getGoogleAdsLinkBuilder() { onChanged(); return getGoogleAdsLinkFieldBuilder().getBuilder(); } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ public com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder getGoogleAdsLinkOrBuilder() { if (googleAdsLinkBuilder_ != null) { return googleAdsLinkBuilder_.getMessageOrBuilder(); } else { return googleAdsLink_ == null ? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance() : googleAdsLink_; } } /** * * * <pre> * Required. The GoogleAdsLink to create. * </pre> * * <code> * .google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 2 [(.google.api.field_behavior) = REQUIRED]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.GoogleAdsLink, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder, com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder> getGoogleAdsLinkFieldBuilder() { if (googleAdsLinkBuilder_ == null) { googleAdsLinkBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.analytics.admin.v1beta.GoogleAdsLink, com.google.analytics.admin.v1beta.GoogleAdsLink.Builder, com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder>( getGoogleAdsLink(), getParentForChildren(), isClean()); googleAdsLink_ = null; } return googleAdsLinkBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) } // @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest) private static final com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest(); } public static com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<CreateGoogleAdsLinkRequest> PARSER = new com.google.protobuf.AbstractParser<CreateGoogleAdsLinkRequest>() { @java.lang.Override public CreateGoogleAdsLinkRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<CreateGoogleAdsLinkRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<CreateGoogleAdsLinkRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.analytics.admin.v1beta.CreateGoogleAdsLinkRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
{ "content_hash": "995a6d7442fbc6a4676372e90af3c288", "timestamp": "", "source": "github", "line_count": 911, "max_line_length": 114, "avg_line_length": 32.26125137211855, "alnum_prop": 0.6599183395712828, "repo_name": "googleapis/java-analytics-admin", "id": "6010356e663597c053331177e12b1faf1db64617", "size": "29984", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/CreateGoogleAdsLinkRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "13898452" }, { "name": "Python", "bytes": "788" }, { "name": "Shell", "bytes": "20456" } ], "symlink_target": "" }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.NamingStyles; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal partial class DeclarationNameCompletionProvider { internal struct NameDeclarationInfo { public NameDeclarationInfo( ImmutableArray<SymbolKind> possibleSymbolKinds, Accessibility accessibility, DeclarationModifiers declarationModifiers, ITypeSymbol type) { PossibleSymbolKinds = possibleSymbolKinds; DeclaredAccessibility = accessibility; Modifiers = declarationModifiers; Type = type; } public ImmutableArray<SymbolKind> PossibleSymbolKinds { get; } public DeclarationModifiers Modifiers { get; } public ITypeSymbol Type { get; } public Accessibility DeclaredAccessibility { get; } internal static async Task<NameDeclarationInfo> GetDeclarationInfo(Document document, int position, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken).GetPreviousTokenIfTouchingWord(position); var semanticModel = await document.GetSemanticModelForSpanAsync(new Text.TextSpan(token.SpanStart, 0), cancellationToken).ConfigureAwait(false); NameDeclarationInfo result; if (IsParameterDeclaration(token, semanticModel, position, cancellationToken, out result) || IsTypeParameterDeclaration(token, semanticModel, position, cancellationToken, out result) || IsVariableDeclaration(token, semanticModel, position, cancellationToken, out result) || IsIncompleteMemberDeclaration(token, semanticModel, position, cancellationToken, out result) || IsFieldDeclaration(token, semanticModel, position, cancellationToken, out result) || IsMethodDeclaration(token, semanticModel, position, cancellationToken, out result) || IsPropertyDeclaration(token, semanticModel, position, cancellationToken, out result) || IsPossibleVariableOrLocalMethodDeclaration(token, semanticModel, position, cancellationToken, out result)) { return result; } return default(NameDeclarationInfo); } private static bool IsPossibleVariableOrLocalMethodDeclaration( SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ExpressionStatementSyntax>( token, semanticModel, e => e.Expression, _ => default(SyntaxTokenList), _ => ImmutableArray.Create(SymbolKind.Local), cancellationToken); return result.Type != null; } private static bool IsPropertyDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<PropertyDeclarationSyntax>( token, semanticModel, m => m.Type, m => m.Modifiers, GetPossibleDeclarations, cancellationToken); return result.Type != null; } private static bool IsMethodDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<MethodDeclarationSyntax>( token, semanticModel, m => m.ReturnType, m => m.Modifiers, GetPossibleDeclarations, cancellationToken); return result.Type != null; } private static NameDeclarationInfo IsFollowingTypeOrComma<TSyntaxNode>(SyntaxToken token, SemanticModel semanticModel, Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter, Func<TSyntaxNode, SyntaxTokenList?> modifierGetter, Func<DeclarationModifiers, ImmutableArray<SymbolKind>> possibleDeclarationComputer, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (!IsPossibleTypeToken(token) && !token.IsKind(SyntaxKind.CommaToken)) { return default(NameDeclarationInfo); } var target = token.GetAncestor<TSyntaxNode>(); if (target == null) { return default(NameDeclarationInfo); } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent != target) { return default(NameDeclarationInfo); } var typeSyntax = typeSyntaxGetter(target); if (typeSyntax == null) { return default(NameDeclarationInfo); } var modifiers = modifierGetter(target); if (modifiers == null) { return default(NameDeclarationInfo); } return new NameDeclarationInfo( possibleDeclarationComputer(GetDeclarationModifiers(modifiers.Value)), GetAccessibility(modifiers.Value), GetDeclarationModifiers(modifiers.Value), semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type); } private static NameDeclarationInfo IsLastTokenOfType<TSyntaxNode>( SyntaxToken token, SemanticModel semanticModel, Func<TSyntaxNode, SyntaxNode> typeSyntaxGetter, Func<TSyntaxNode, SyntaxTokenList?> modifierGetter, Func<DeclarationModifiers, ImmutableArray<SymbolKind>> possibleDeclarationComputer, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (!IsPossibleTypeToken(token)) { return default(NameDeclarationInfo); } var target = token.GetAncestor<TSyntaxNode>(); if (target == null) { return default(NameDeclarationInfo); } var typeSyntax = typeSyntaxGetter(target); if (typeSyntax == null || token != typeSyntax.GetLastToken()) { return default(NameDeclarationInfo); } var modifiers = modifierGetter(target); if (modifiers == null) { return default(NameDeclarationInfo); } return new NameDeclarationInfo( possibleDeclarationComputer(GetDeclarationModifiers(modifiers.Value)), GetAccessibility(modifiers.Value), GetDeclarationModifiers(modifiers.Value), semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type); } private static bool IsFieldDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, v => v.Type, v => v.Parent is FieldDeclarationSyntax f ? f.Modifiers : default(SyntaxTokenList?), GetPossibleDeclarations, cancellationToken); return result.Type != null; } private static bool IsIncompleteMemberDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<IncompleteMemberSyntax>(token, semanticModel, i => i.Type, i => i.Modifiers, GetPossibleDeclarations, cancellationToken); return result.Type != null; } private static bool IsVariableDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsFollowingTypeOrComma<VariableDeclarationSyntax>(token, semanticModel, v => v.Type, v => v.Parent is LocalDeclarationStatementSyntax l ? l.Modifiers : default(SyntaxTokenList?), d => ImmutableArray.Create(SymbolKind.Local), cancellationToken); return result.Type != null; } private static bool IsTypeParameterDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { if (token.IsKind(SyntaxKind.LessThanToken, SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TypeParameterList)) { result = new NameDeclarationInfo( ImmutableArray.Create(SymbolKind.TypeParameter), Accessibility.NotApplicable, new DeclarationModifiers(), type: null); return true; } result = default(NameDeclarationInfo); return false; } private static bool IsParameterDeclaration(SyntaxToken token, SemanticModel semanticModel, int position, CancellationToken cancellationToken, out NameDeclarationInfo result) { result = IsLastTokenOfType<ParameterSyntax>( token, semanticModel, p => p.Type, _ => default(SyntaxTokenList), _ => ImmutableArray.Create(SymbolKind.Parameter), cancellationToken); return result.Type != null; } private static bool IsPossibleTypeToken(SyntaxToken token) => token.IsKind( SyntaxKind.IdentifierToken, SyntaxKind.GreaterThanToken, SyntaxKind.CloseBracketToken) || token.Parent.IsKind(SyntaxKind.PredefinedType); private static ImmutableArray<SymbolKind> GetPossibleDeclarations(DeclarationModifiers modifiers) { if (modifiers.IsConst || modifiers.IsReadOnly) { return ImmutableArray.Create(SymbolKind.Field); } var possibleTypes = ImmutableArray.Create(SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); if (modifiers.IsAbstract || modifiers.IsVirtual || modifiers.IsSealed || modifiers.IsOverride) { possibleTypes = possibleTypes.Remove(SymbolKind.Field); } if (modifiers.IsAsync || modifiers.IsPartial) { possibleTypes = possibleTypes.Remove(SymbolKind.Property); } return possibleTypes; } private static DeclarationModifiers GetDeclarationModifiers(SyntaxTokenList modifiers) { var declarationModifiers = new DeclarationModifiers(); foreach (var modifer in modifiers) { switch (modifer.Kind()) { case SyntaxKind.StaticKeyword: declarationModifiers = declarationModifiers.WithIsStatic(true); continue; case SyntaxKind.AbstractKeyword: declarationModifiers = declarationModifiers.WithIsAbstract(true); continue; case SyntaxKind.NewKeyword: declarationModifiers = declarationModifiers.WithIsNew(true); continue; case SyntaxKind.UnsafeKeyword: declarationModifiers = declarationModifiers.WithIsUnsafe(true); continue; case SyntaxKind.ReadOnlyKeyword: declarationModifiers = declarationModifiers.WithIsReadOnly(true); continue; case SyntaxKind.VirtualKeyword: declarationModifiers = declarationModifiers.WithIsVirtual(true); continue; case SyntaxKind.OverrideKeyword: declarationModifiers = declarationModifiers.WithIsOverride(true); continue; case SyntaxKind.SealedKeyword: declarationModifiers = declarationModifiers.WithIsSealed(true); continue; case SyntaxKind.ConstKeyword: declarationModifiers = declarationModifiers.WithIsConst(true); continue; case SyntaxKind.AsyncKeyword: declarationModifiers = declarationModifiers.WithAsync(true); continue; case SyntaxKind.PartialKeyword: declarationModifiers = declarationModifiers.WithPartial(true); continue; } } return declarationModifiers; } private static Accessibility GetAccessibility(SyntaxTokenList modifiers) { for (int i = modifiers.Count - 1; i >= 0; i--) { var modifier = modifiers[i]; switch (modifier.Kind()) { case SyntaxKind.PrivateKeyword: return Accessibility.Private; case SyntaxKind.PublicKeyword: return Accessibility.Public; case SyntaxKind.ProtectedKeyword: return Accessibility.Protected; case SyntaxKind.InternalKeyword: return Accessibility.Internal; } } return Accessibility.NotApplicable; } } } }
{ "content_hash": "a8211be558bd9d4ffefdb1e45a193255", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 161, "avg_line_length": 46.44767441860465, "alnum_prop": 0.5625860558267618, "repo_name": "zooba/roslyn", "id": "dbeea2dae62dcdb50291bd559b8578ffd614b811", "size": "15980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Features/CSharp/Portable/Completion/CompletionProviders/DeclarationNameCompletionProvider.DeclarationInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "10490" }, { "name": "C#", "bytes": "93850864" }, { "name": "C++", "bytes": "5392" }, { "name": "F#", "bytes": "3632" }, { "name": "Groovy", "bytes": "10141" }, { "name": "Makefile", "bytes": "3294" }, { "name": "PowerShell", "bytes": "104698" }, { "name": "Shell", "bytes": "8363" }, { "name": "Visual Basic", "bytes": "72726084" } ], "symlink_target": "" }
title: Contributing layout: contribute.hbs --- # Contributing Thank you for your interest in contributing to Node.js, there are multiple ways and places you can contribute and we're here to help facilitate that. ## Reporting an Issue If you have found what you believe to be an issue with Node.js please do not hesitate to file an issue on the GitHub project. When filing your issue please make sure you can express the issue with a reproducible test case, and that test case should not include any external dependencies. That is to say, the test case can be executed without anything more than Node.js itself. When reporting an issue we also need as much information about your environment that you can include. We never know what information will be pertinent when trying narrow down the issue. Please include at least the following information: * Version of Node * Platform you're running on (OS X, SunOS, Linux, Windows) * Architecture you're running on (32bit or 64bit and x86 or ARM) The Node.js project is currently managed across a number of separate GitHub repositories, each with their own separate issues database. If possible, please direct any issues you are reporting to the appropriate repository but don't worry if things happen to get put in the wrong place, the community of contributors will be more than happy to help get you pointed in the right direction. * To report issues specific to Node.js, please use [nodejs/node](https://github.com/nodejs/node) * To report issues specific to this website, please use [nodejs/nodejs.org](https://github.com/nodejs/nodejs.org/issues) ## Code contributions If you'd like to fix bugs or add a new feature to Node.js, please make sure you consult the [Node.js Development Policy](/en/get-involved/development/). Before any contribution can be accepted and be part of the project, it needs to be reviewed by existing collaborators in accordance to the guidelines established by the [Node.js Development Policy](/en/get-involved/development/). ## Becoming a collaborator By becoming a collaborator, contributors can have even more impact on the project. They can help other contributors by reviewing their contributions, triage issues and take an even bigger part in shaping the project's future. The Node.js project is always looking for people who are interested in becoming collaborators. If you're interested, make sure you familiarize yourself with the [Node.js Development Policy](/en/get-involved/development/).
{ "content_hash": "602d8d6ee2a462fb844904abf88ecaa8", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 447, "avg_line_length": 77.78125, "alnum_prop": 0.795098433105665, "repo_name": "marocchino/new.nodejs.org", "id": "85dd85c648ee4115675b003369c16d2bb96d7825", "size": "2493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "locale/en/get-involved/contribute.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46160" }, { "name": "HTML", "bytes": "34035" }, { "name": "JavaScript", "bytes": "34519" } ], "symlink_target": "" }
layout: default title: Global Day of Coderetreat Registration --- {% include_relative README.md %}
{ "content_hash": "37b11b5f743216e27fb1317346147950", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 45, "avg_line_length": 14.571428571428571, "alnum_prop": 0.7352941176470589, "repo_name": "coderetreat/coderetreat.github.io", "id": "fc151e327e5063ed00cfb424088705b3e5daae2e", "size": "106", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "register-event.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "53239" }, { "name": "HTML", "bytes": "46960" }, { "name": "JavaScript", "bytes": "60075" }, { "name": "Liquid", "bytes": "2778" }, { "name": "Ruby", "bytes": "5954" }, { "name": "Shell", "bytes": "786" } ], "symlink_target": "" }
using namespace seqan; using namespace std; bool myVergleich (GMatch<int> const & i,GMatch<int> const & j) { return (i.score >= j.score); } int sortiereMatches (String<GMatch<int> > & unsortetResults) { std::sort (begin(unsortetResults), end(unsortetResults), myVergleich); return 0; } template<typename TScore> int GPostProcessMatches(String<GMatch<TScore> > & matches) { sort (begin(unsortetResults), end(unsortetResults), myVergleich); //sortiereMatches(matches); return 0; } #endif // GINGER_GSEARCH_GPOSTPROCESSMATCHES_H_
{ "content_hash": "281d8534984f568319b17efa8c836fd0", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 71, "avg_line_length": 25.571428571428573, "alnum_prop": 0.7430167597765364, "repo_name": "bkahlert/seqan-research", "id": "218e763645d8a723349a197e2db79e79674bdd7d", "size": "715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raw/pmsb13/pmsb13-data-20130530/sources/qhuulr654q26tohr/2013-05-19T13-24-28.864+0200/sandbox/PMSB_group6/include/seqan/GSearch/GPostProcessMatches.h", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "Awk", "bytes": "44044" }, { "name": "Batchfile", "bytes": "37736" }, { "name": "C", "bytes": "1261223" }, { "name": "C++", "bytes": "277576131" }, { "name": "CMake", "bytes": "5546616" }, { "name": "CSS", "bytes": "271972" }, { "name": "GLSL", "bytes": "2280" }, { "name": "Groff", "bytes": "2694006" }, { "name": "HTML", "bytes": "15207297" }, { "name": "JavaScript", "bytes": "362928" }, { "name": "LSL", "bytes": "22561" }, { "name": "Makefile", "bytes": "6418610" }, { "name": "Objective-C", "bytes": "3730085" }, { "name": "PHP", "bytes": "3302" }, { "name": "Perl", "bytes": "10468" }, { "name": "PostScript", "bytes": "22762" }, { "name": "Python", "bytes": "9267035" }, { "name": "R", "bytes": "230698" }, { "name": "Rebol", "bytes": "283" }, { "name": "Shell", "bytes": "437340" }, { "name": "Tcl", "bytes": "15439" }, { "name": "TeX", "bytes": "738415" }, { "name": "VimL", "bytes": "12685" } ], "symlink_target": "" }
<?php /** * Class WC_Log_Handler_DB file. * * @package WooCommerce\Log Handlers */ if ( ! defined( 'ABSPATH' ) ) { exit; // Exit if accessed directly. } /** * Handles log entries by writing to database. * * @class WC_Log_Handler_DB * @version 1.0.0 * @package WooCommerce/Classes/Log_Handlers */ class WC_Log_Handler_DB extends WC_Log_Handler { /** * Handle a log entry. * * @param int $timestamp Log timestamp. * @param string $level emergency|alert|critical|error|warning|notice|info|debug. * @param string $message Log message. * @param array $context { * Additional information for log handlers. * * @type string $source Optional. Source will be available in log table. * If no source is provided, attempt to provide sensible default. * } * * @see WC_Log_Handler_DB::get_log_source() for default source. * * @return bool False if value was not handled and true if value was handled. */ public function handle( $timestamp, $level, $message, $context ) { if ( isset( $context['source'] ) && $context['source'] ) { $source = $context['source']; } else { $source = $this->get_log_source(); } return $this->add( $timestamp, $level, $message, $source, $context ); } /** * Add a log entry to chosen file. * * @param int $timestamp Log timestamp. * @param string $level emergency|alert|critical|error|warning|notice|info|debug. * @param string $message Log message. * @param string $source Log source. Useful for filtering and sorting. * @param array $context Context will be serialized and stored in database. * * @return bool True if write was successful. */ protected static function add( $timestamp, $level, $message, $source, $context ) { global $wpdb; $insert = array( 'timestamp' => date( 'Y-m-d H:i:s', $timestamp ), 'level' => WC_Log_Levels::get_level_severity( $level ), 'message' => $message, 'source' => $source, ); $format = array( '%s', '%d', '%s', '%s', '%s', // possible serialized context. ); if ( ! empty( $context ) ) { $insert['context'] = serialize( $context ); // @codingStandardsIgnoreLine. } return false !== $wpdb->insert( "{$wpdb->prefix}woocommerce_log", $insert, $format ); } /** * Clear all logs from the DB. * * @return bool True if flush was successful. */ public static function flush() { global $wpdb; return $wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}woocommerce_log" ); } /** * Clear entries for a chosen handle/source. * * @param string $source Log source. * @return bool */ public function clear( $source ) { global $wpdb; return $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_log WHERE source = %s", $source ) ); } /** * Delete selected logs from DB. * * @param int|string|array $log_ids Log ID or array of Log IDs to be deleted. * * @return bool */ public static function delete( $log_ids ) { global $wpdb; if ( ! is_array( $log_ids ) ) { $log_ids = array( $log_ids ); } $format = array_fill( 0, count( $log_ids ), '%d' ); $query_in = '(' . implode( ',', $format ) . ')'; return $wpdb->query( "DELETE FROM {$wpdb->prefix}woocommerce_log WHERE log_id IN {$query_in}" ); // @codingStandardsIgnoreLine. } /** * Delete all logs older than a defined timestamp. * * @since 3.4.0 * @param integer $timestamp Timestamp to delete logs before. */ public static function delete_logs_before_timestamp( $timestamp = 0 ) { if ( ! $timestamp ) { return; } global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}woocommerce_log WHERE timestamp < %d", $timestamp ) ); } /** * Get appropriate source based on file name. * * Try to provide an appropriate source in case none is provided. * * @return string Text to use as log source. "" (empty string) if none is found. */ protected static function get_log_source() { static $ignore_files = array( 'class-wc-log-handler-db', 'class-wc-logger' ); /** * PHP < 5.3.6 correct behavior * * @see http://php.net/manual/en/function.debug-backtrace.php#refsect1-function.debug-backtrace-parameters */ if ( defined( 'DEBUG_BACKTRACE_IGNORE_ARGS' ) ) { $debug_backtrace_arg = DEBUG_BACKTRACE_IGNORE_ARGS; // phpcs:ignore PHPCompatibility.PHP.NewConstants.debug_backtrace_ignore_argsFound } else { $debug_backtrace_arg = false; } $trace = debug_backtrace( $debug_backtrace_arg ); // @codingStandardsIgnoreLine. foreach ( $trace as $t ) { if ( isset( $t['file'] ) ) { $filename = pathinfo( $t['file'], PATHINFO_FILENAME ); if ( ! in_array( $filename, $ignore_files, true ) ) { return $filename; } } } return ''; } }
{ "content_hash": "7f1c163819c0d72c69579dfdf2c56f63", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 137, "avg_line_length": 25.52910052910053, "alnum_prop": 0.6238341968911917, "repo_name": "cimocimocimo/staydrysystems.com", "id": "e654eb92b808cbe54257d6d5694da4ce34aef451", "size": "4825", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "web/app/plugins/woocommerce/includes/log-handlers/class-wc-log-handler-db.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3511566" }, { "name": "HTML", "bytes": "409791" }, { "name": "Hack", "bytes": "3132" }, { "name": "JavaScript", "bytes": "4604537" }, { "name": "PHP", "bytes": "18711665" }, { "name": "XSLT", "bytes": "4267" } ], "symlink_target": "" }
package com.dihanov.musiq.di.modules; import com.dihanov.musiq.di.annotations.PerActivity; import com.dihanov.musiq.ui.settings.profile.userlovedtracks.UserLovedTracksContract; import com.dihanov.musiq.ui.settings.profile.userlovedtracks.UserLovedTracksPresenter; import com.dihanov.musiq.ui.settings.profile.userlovedtracks.UserLovedTracksView; import dagger.Binds; import dagger.Module; @Module public abstract class UserLovedTracksModule { @Binds @PerActivity abstract UserLovedTracksContract.View bindUserLovedTracksView(UserLovedTracksView view); @Binds @PerActivity abstract UserLovedTracksContract.Presenter bindUserLovedTracksPresenter(UserLovedTracksPresenter presenter); }
{ "content_hash": "b5c58a8eb5faf8726859b1039d8de1b8", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 112, "avg_line_length": 35.55, "alnum_prop": 0.8382559774964838, "repo_name": "DDihanov/musiQ", "id": "ba3f9ef1a0754d0de2337da1d39022f7ab4b814c", "size": "711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/dihanov/musiq/di/modules/UserLovedTracksModule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "453590" } ], "symlink_target": "" }
import os from django.conf import settings from django.core.management.base import BaseCommand from django.utils import translation from openbudgets.apps.transport.incoming.importers.initial import InitImporter class Command(BaseCommand): help = 'Loads initial data for the instance from formatted CSV files.' # Also need for the language settings issue described below. can_import_settings = False def __init__(self): # Make django respect our language settings in management commands. # We need to enforce this for modeltranslation to work as expected, and # work around a hardcoded value for this in Django itself. # https://groups.google.com/forum/?fromgroups#!topic/django-modeltranslation/JBgEBfWZZ9A translation.activate(settings.MODELTRANSLATION_DEFAULT_LANGUAGE) super(Command, self).__init__() def handle(self, *args, **options): self.stdout.write('Loading initial data from CSV sources.') fixtures = os.listdir(settings.FIXTURE_DIRS[0]) csvs = sorted([filename for filename in fixtures if filename.endswith('.csv')]) for csv in csvs: self.stdout.write('Writing data from ' + csv + ' ...') f = settings.FIXTURE_DIRS[0] + '/' + csv importer = InitImporter(f) importer.save() self.stdout.write("Data from CSV sources loaded. We are ready to rock.")
{ "content_hash": "7ccf010683400b97264e6e50d958d3ea", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 96, "avg_line_length": 39.55555555555556, "alnum_prop": 0.6867977528089888, "repo_name": "shaib/openbudgets", "id": "615f10dad115c68f123031565541a7408c977fc1", "size": "1424", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "openbudgets/commons/management/commands/loadcsv.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "355833" }, { "name": "JavaScript", "bytes": "1185878" }, { "name": "Python", "bytes": "487714" } ], "symlink_target": "" }
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactRouter"] = factory(require("react")); else root["ReactRouter"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_4__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.createMemoryHistory = exports.hashHistory = exports.browserHistory = exports.applyRouterMiddleware = exports.formatPattern = exports.useRouterHistory = exports.match = exports.routerShape = exports.locationShape = exports.RouterContext = exports.createRoutes = exports.Route = exports.Redirect = exports.IndexRoute = exports.IndexRedirect = exports.withRouter = exports.IndexLink = exports.Link = exports.Router = undefined; var _RouteUtils = __webpack_require__(5); Object.defineProperty(exports, 'createRoutes', { enumerable: true, get: function get() { return _RouteUtils.createRoutes; } }); var _PropTypes = __webpack_require__(16); Object.defineProperty(exports, 'locationShape', { enumerable: true, get: function get() { return _PropTypes.locationShape; } }); Object.defineProperty(exports, 'routerShape', { enumerable: true, get: function get() { return _PropTypes.routerShape; } }); var _PatternUtils = __webpack_require__(8); Object.defineProperty(exports, 'formatPattern', { enumerable: true, get: function get() { return _PatternUtils.formatPattern; } }); var _Router2 = __webpack_require__(40); var _Router3 = _interopRequireDefault(_Router2); var _Link2 = __webpack_require__(24); var _Link3 = _interopRequireDefault(_Link2); var _IndexLink2 = __webpack_require__(36); var _IndexLink3 = _interopRequireDefault(_IndexLink2); var _withRouter2 = __webpack_require__(51); var _withRouter3 = _interopRequireDefault(_withRouter2); var _IndexRedirect2 = __webpack_require__(37); var _IndexRedirect3 = _interopRequireDefault(_IndexRedirect2); var _IndexRoute2 = __webpack_require__(38); var _IndexRoute3 = _interopRequireDefault(_IndexRoute2); var _Redirect2 = __webpack_require__(26); var _Redirect3 = _interopRequireDefault(_Redirect2); var _Route2 = __webpack_require__(39); var _Route3 = _interopRequireDefault(_Route2); var _RouterContext2 = __webpack_require__(17); var _RouterContext3 = _interopRequireDefault(_RouterContext2); var _match2 = __webpack_require__(49); var _match3 = _interopRequireDefault(_match2); var _useRouterHistory2 = __webpack_require__(31); var _useRouterHistory3 = _interopRequireDefault(_useRouterHistory2); var _applyRouterMiddleware2 = __webpack_require__(42); var _applyRouterMiddleware3 = _interopRequireDefault(_applyRouterMiddleware2); var _browserHistory2 = __webpack_require__(43); var _browserHistory3 = _interopRequireDefault(_browserHistory2); var _hashHistory2 = __webpack_require__(47); var _hashHistory3 = _interopRequireDefault(_hashHistory2); var _createMemoryHistory2 = __webpack_require__(28); var _createMemoryHistory3 = _interopRequireDefault(_createMemoryHistory2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.Router = _Router3.default; /* components */ exports.Link = _Link3.default; exports.IndexLink = _IndexLink3.default; exports.withRouter = _withRouter3.default; /* components (configuration) */ exports.IndexRedirect = _IndexRedirect3.default; exports.IndexRoute = _IndexRoute3.default; exports.Redirect = _Redirect3.default; exports.Route = _Route3.default; /* utils */ exports.RouterContext = _RouterContext3.default; exports.match = _match3.default; exports.useRouterHistory = _useRouterHistory3.default; exports.applyRouterMiddleware = _applyRouterMiddleware3.default; /* histories */ exports.browserHistory = _browserHistory3.default; exports.hashHistory = _hashHistory3.default; exports.createMemoryHistory = _createMemoryHistory3.default; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (true) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( format.replace(/%s/g, function() { return args[argIndex++]; }) ); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { var ReactIs = __webpack_require__(23); // By explicitly using `prop-types` you are opting into new development behavior. // http://fb.me/prop-types-in-prod var throwOnDirectAccess = true; module.exports = __webpack_require__(65)(ReactIs.isElement, throwOnDirectAccess); } else { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = require('./factoryWithThrowingShims')(); } /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; var React = __webpack_require__(4); var factory = __webpack_require__(52); if (typeof React === 'undefined') { throw Error( 'create-react-class could not find the React object. If you are using script tags, ' + 'make sure that React is being loaded before create-react-class.' ); } // Hack to grab NoopUpdateQueue from isomorphic React var ReactNoopUpdateQueue = new React.Component().updater; module.exports = factory( React.Component, React.isValidElement, ReactNoopUpdateQueue ); /***/ }), /* 4 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.isReactChildren = isReactChildren; exports.createRouteFromReactElement = createRouteFromReactElement; exports.createRoutesFromReactChildren = createRoutesFromReactChildren; exports.createRoutes = createRoutes; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isValidChild(object) { return object == null || _react2.default.isValidElement(object); } function isReactChildren(object) { return isValidChild(object) || Array.isArray(object) && object.every(isValidChild); } function createRoute(defaultProps, props) { return _extends({}, defaultProps, props); } function createRouteFromReactElement(element) { var type = element.type; var route = createRoute(type.defaultProps, element.props); if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route); if (childRoutes.length) route.childRoutes = childRoutes; delete route.children; } return route; } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * const routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ function createRoutesFromReactChildren(children, parentRoute) { var routes = []; _react2.default.Children.forEach(children, function (element) { if (_react2.default.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute); if (route) routes.push(route); } else { routes.push(createRouteFromReactElement(element)); } } }); return routes; } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes); } else if (routes && !Array.isArray(routes)) { routes = [routes]; } return routes; } /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.createPath = exports.parsePath = exports.getQueryStringValueFromPath = exports.stripQueryStringValueFromPath = exports.addQueryStringValueToPath = undefined; var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var addQueryStringValueToPath = exports.addQueryStringValueToPath = function addQueryStringValueToPath(path, key, value) { var _parsePath = parsePath(path), pathname = _parsePath.pathname, search = _parsePath.search, hash = _parsePath.hash; return createPath({ pathname: pathname, search: search + (search.indexOf('?') === -1 ? '?' : '&') + key + '=' + value, hash: hash }); }; var stripQueryStringValueFromPath = exports.stripQueryStringValueFromPath = function stripQueryStringValueFromPath(path, key) { var _parsePath2 = parsePath(path), pathname = _parsePath2.pathname, search = _parsePath2.search, hash = _parsePath2.hash; return createPath({ pathname: pathname, search: search.replace(new RegExp('([?&])' + key + '=[a-zA-Z0-9]+(&?)'), function (match, prefix, suffix) { return prefix === '?' ? prefix : suffix; }), hash: hash }); }; var getQueryStringValueFromPath = exports.getQueryStringValueFromPath = function getQueryStringValueFromPath(path, key) { var _parsePath3 = parsePath(path), search = _parsePath3.search; var match = search.match(new RegExp('[?&]' + key + '=([a-zA-Z0-9]+)')); return match && match[1]; }; var extractPath = function extractPath(string) { var match = string.match(/^(https?:)?\/\/[^\/]*/); return match == null ? string : string.substring(match[0].length); }; var parsePath = exports.parsePath = function parsePath(path) { var pathname = extractPath(path); var search = ''; var hash = ''; true ? (0, _warning2.default)(path === pathname, 'A path must be pathname + search + hash only, not a full URL like "%s"', path) : void 0; var hashIndex = pathname.indexOf('#'); if (hashIndex !== -1) { hash = pathname.substring(hashIndex); pathname = pathname.substring(0, hashIndex); } var searchIndex = pathname.indexOf('?'); if (searchIndex !== -1) { search = pathname.substring(searchIndex); pathname = pathname.substring(0, searchIndex); } if (pathname === '') pathname = '/'; return { pathname: pathname, search: search, hash: hash }; }; var createPath = exports.createPath = function createPath(location) { if (location == null || typeof location === 'string') return location; var basename = location.basename, pathname = location.pathname, search = location.search, hash = location.hash; var path = (basename || '') + pathname; if (search && search !== '?') path += search; if (hash) path += hash; return path; }; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = function() {}; if (true) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var key = 2; key < len; key++) { args[key - 2] = arguments[key]; } if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (format.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch(x) {} } }; } module.exports = warning; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compilePattern = compilePattern; exports.matchPattern = matchPattern; exports.getParamNames = getParamNames; exports.getParams = getParams; exports.formatPattern = formatPattern; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function _compilePattern(pattern) { var regexpSource = ''; var paramNames = []; var tokens = []; var match = void 0, lastIndex = 0, matcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|\*\*|\*|\(|\)|\\\(|\\\)/g; while (match = matcher.exec(pattern)) { if (match.index !== lastIndex) { tokens.push(pattern.slice(lastIndex, match.index)); regexpSource += escapeRegExp(pattern.slice(lastIndex, match.index)); } if (match[1]) { regexpSource += '([^/]+)'; paramNames.push(match[1]); } else if (match[0] === '**') { regexpSource += '(.*)'; paramNames.push('splat'); } else if (match[0] === '*') { regexpSource += '(.*?)'; paramNames.push('splat'); } else if (match[0] === '(') { regexpSource += '(?:'; } else if (match[0] === ')') { regexpSource += ')?'; } else if (match[0] === '\\(') { regexpSource += '\\('; } else if (match[0] === '\\)') { regexpSource += '\\)'; } tokens.push(match[0]); lastIndex = matcher.lastIndex; } if (lastIndex !== pattern.length) { tokens.push(pattern.slice(lastIndex, pattern.length)); regexpSource += escapeRegExp(pattern.slice(lastIndex, pattern.length)); } return { pattern: pattern, regexpSource: regexpSource, paramNames: paramNames, tokens: tokens }; } var CompiledPatternsCache = Object.create(null); function compilePattern(pattern) { if (!CompiledPatternsCache[pattern]) CompiledPatternsCache[pattern] = _compilePattern(pattern); return CompiledPatternsCache[pattern]; } /** * Attempts to match a pattern on the given pathname. Patterns may use * the following special characters: * * - :paramName Matches a URL segment up to the next /, ?, or #. The * captured string is considered a "param" * - () Wraps a segment of the URL that is optional * - * Consumes (non-greedy) all characters up to the next * character in the pattern, or to the end of the URL if * there is none * - ** Consumes (greedy) all characters up to the next character * in the pattern, or to the end of the URL if there is none * * The function calls callback(error, matched) when finished. * The return value is an object with the following properties: * * - remainingPathname * - paramNames * - paramValues */ function matchPattern(pattern, pathname) { // Ensure pattern starts with leading slash for consistency with pathname. if (pattern.charAt(0) !== '/') { pattern = '/' + pattern; } var _compilePattern2 = compilePattern(pattern), regexpSource = _compilePattern2.regexpSource, paramNames = _compilePattern2.paramNames, tokens = _compilePattern2.tokens; if (pattern.charAt(pattern.length - 1) !== '/') { regexpSource += '/?'; // Allow optional path separator at end. } // Special-case patterns like '*' for catch-all routes. if (tokens[tokens.length - 1] === '*') { regexpSource += '$'; } var match = pathname.match(new RegExp('^' + regexpSource, 'i')); if (match == null) { return null; } var matchedPath = match[0]; var remainingPathname = pathname.substr(matchedPath.length); if (remainingPathname) { // Require that the match ends at a path separator, if we didn't match // the full path, so any remaining pathname is a new path segment. if (matchedPath.charAt(matchedPath.length - 1) !== '/') { return null; } // If there is a remaining pathname, treat the path separator as part of // the remaining pathname for properly continuing the match. remainingPathname = '/' + remainingPathname; } return { remainingPathname: remainingPathname, paramNames: paramNames, paramValues: match.slice(1).map(function (v) { return v && decodeURIComponent(v); }) }; } function getParamNames(pattern) { return compilePattern(pattern).paramNames; } function getParams(pattern, pathname) { var match = matchPattern(pattern, pathname); if (!match) { return null; } var paramNames = match.paramNames, paramValues = match.paramValues; var params = {}; paramNames.forEach(function (paramName, index) { params[paramName] = paramValues[index]; }); return params; } /** * Returns a version of the given pattern with params interpolated. Throws * if there is a dynamic segment of the pattern for which there is no param. */ function formatPattern(pattern, params) { params = params || {}; var _compilePattern3 = compilePattern(pattern), tokens = _compilePattern3.tokens; var parenCount = 0, pathname = '', splatIndex = 0, parenHistory = []; var token = void 0, paramName = void 0, paramValue = void 0; for (var i = 0, len = tokens.length; i < len; ++i) { token = tokens[i]; if (token === '*' || token === '**') { paramValue = Array.isArray(params.splat) ? params.splat[splatIndex++] : params.splat; !(paramValue != null || parenCount > 0) ? true ? (0, _invariant2.default)(false, 'Missing splat #%s for path "%s"', splatIndex, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue != null) pathname += encodeURI(paramValue); } else if (token === '(') { parenHistory[parenCount] = ''; parenCount += 1; } else if (token === ')') { var parenText = parenHistory.pop(); parenCount -= 1; if (parenCount) parenHistory[parenCount - 1] += parenText;else pathname += parenText; } else if (token === '\\(') { pathname += '('; } else if (token === '\\)') { pathname += ')'; } else if (token.charAt(0) === ':') { paramName = token.substring(1); paramValue = params[paramName]; !(paramValue != null || parenCount > 0) ? true ? (0, _invariant2.default)(false, 'Missing "%s" parameter for path "%s"', paramName, pattern) : (0, _invariant2.default)(false) : void 0; if (paramValue == null) { if (parenCount) { parenHistory[parenCount - 1] = ''; var curTokenIdx = tokens.indexOf(token); var tokensSubset = tokens.slice(curTokenIdx, tokens.length); var nextParenIdx = -1; for (var _i = 0; _i < tokensSubset.length; _i++) { if (tokensSubset[_i] == ')') { nextParenIdx = _i; break; } } !(nextParenIdx > 0) ? true ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren at segment "%s"', pattern, tokensSubset.join('')) : (0, _invariant2.default)(false) : void 0; // jump to ending paren i = curTokenIdx + nextParenIdx - 1; } } else if (parenCount) parenHistory[parenCount - 1] += encodeURIComponent(paramValue);else pathname += encodeURIComponent(paramValue); } else { if (parenCount) parenHistory[parenCount - 1] += token;else pathname += token; } } !(parenCount <= 0) ? true ? (0, _invariant2.default)(false, 'Path "%s" is missing end paren', pattern) : (0, _invariant2.default)(false) : void 0; return pathname.replace(/\/+/g, '/'); } /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = routerWarning; exports._resetWarned = _resetWarned; var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var warned = {}; function routerWarning(falseToWarn, message) { // Only issue deprecation warnings once. if (message.indexOf('deprecated') !== -1) { if (warned[message]) { return; } warned[message] = true; } message = '[react-router] ' + message; for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } _warning2.default.apply(undefined, [falseToWarn, message].concat(args)); } function _resetWarned() { warned = {}; } /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.locationsAreEqual = exports.statesAreEqual = exports.createLocation = exports.createQuery = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); var _PathUtils = __webpack_require__(6); var _Actions = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createQuery = exports.createQuery = function createQuery(props) { return _extends(Object.create(null), props); }; var createLocation = exports.createLocation = function createLocation() { var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '/'; var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _Actions.POP; var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var object = typeof input === 'string' ? (0, _PathUtils.parsePath)(input) : input; true ? (0, _warning2.default)(!object.path, 'Location descriptor objects should have a `pathname`, not a `path`.') : void 0; var pathname = object.pathname || '/'; var search = object.search || ''; var hash = object.hash || ''; var state = object.state; return { pathname: pathname, search: search, hash: hash, state: state, action: action, key: key }; }; var isDate = function isDate(object) { return Object.prototype.toString.call(object) === '[object Date]'; }; var statesAreEqual = exports.statesAreEqual = function statesAreEqual(a, b) { if (a === b) return true; var typeofA = typeof a === 'undefined' ? 'undefined' : _typeof(a); var typeofB = typeof b === 'undefined' ? 'undefined' : _typeof(b); if (typeofA !== typeofB) return false; !(typeofA !== 'function') ? true ? (0, _invariant2.default)(false, 'You must not store functions in location state') : (0, _invariant2.default)(false) : void 0; // Not the same object, but same type. if (typeofA === 'object') { !!(isDate(a) && isDate(b)) ? true ? (0, _invariant2.default)(false, 'You must not store Date objects in location state') : (0, _invariant2.default)(false) : void 0; if (!Array.isArray(a)) { var keysofA = Object.keys(a); var keysofB = Object.keys(b); return keysofA.length === keysofB.length && keysofA.every(function (key) { return statesAreEqual(a[key], b[key]); }); } return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return statesAreEqual(item, b[index]); }); } // All other serializable types (string, number, boolean) // should be strict equal. return false; }; var locationsAreEqual = exports.locationsAreEqual = function locationsAreEqual(a, b) { return a.key === b.key && // a.action === b.action && // Different action !== location change. a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && statesAreEqual(a.state, b.state); }; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.routes = exports.route = exports.components = exports.component = exports.history = undefined; exports.falsy = falsy; var _propTypes = __webpack_require__(2); function falsy(props, propName, componentName) { if (props[propName]) return new Error('<' + componentName + '> should not have a "' + propName + '" prop'); } var history = exports.history = (0, _propTypes.shape)({ listen: _propTypes.func.isRequired, push: _propTypes.func.isRequired, replace: _propTypes.func.isRequired, go: _propTypes.func.isRequired, goBack: _propTypes.func.isRequired, goForward: _propTypes.func.isRequired }); var component = exports.component = _propTypes.elementType; var components = exports.components = (0, _propTypes.oneOfType)([component, _propTypes.object]); var route = exports.route = (0, _propTypes.oneOfType)([_propTypes.object, _propTypes.element]); var routes = exports.routes = (0, _propTypes.oneOfType)([route, (0, _propTypes.arrayOf)(route)]); /***/ }), /* 12 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; /** * Indicates that navigation was caused by a call to history.push. */ var PUSH = exports.PUSH = 'PUSH'; /** * Indicates that navigation was caused by a call to history.replace. */ var REPLACE = exports.REPLACE = 'REPLACE'; /** * Indicates that navigation was caused by some other action such * as using a browser's back/forward buttons and/or manually manipulating * the URL in a browser's location bar. This is the default. * * See https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate * for more information. */ var POP = exports.POP = 'POP'; /***/ }), /* 13 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; var addEventListener = exports.addEventListener = function addEventListener(node, event, listener) { return node.addEventListener ? node.addEventListener(event, listener, false) : node.attachEvent('on' + event, listener); }; var removeEventListener = exports.removeEventListener = function removeEventListener(node, event, listener) { return node.removeEventListener ? node.removeEventListener(event, listener, false) : node.detachEvent('on' + event, listener); }; /** * Returns true if the HTML5 history API is supported. Taken from Modernizr. * * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586 */ var supportsHistory = exports.supportsHistory = function supportsHistory() { var ua = window.navigator.userAgent; if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false; return window.history && 'pushState' in window.history; }; /** * Returns false if using go(n) with hash history causes a full page reload. */ var supportsGoWithoutReloadUsingHash = exports.supportsGoWithoutReloadUsingHash = function supportsGoWithoutReloadUsingHash() { return window.navigator.userAgent.indexOf('Firefox') === -1; }; /** * Returns true if browser fires popstate on hash change. * IE10 and IE11 do not. */ var supportsPopstateOnHashchange = exports.supportsPopstateOnHashchange = function supportsPopstateOnHashchange() { return window.navigator.userAgent.indexOf('Trident') === -1; }; /** * Returns true if a given popstate event is an extraneous WebKit event. * Accounts for the fact that Chrome on iOS fires real popstate events * containing undefined state when pressing the back button. */ var isExtraneousPopstateEvent = exports.isExtraneousPopstateEvent = function isExtraneousPopstateEvent(event) { return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1; }; /***/ }), /* 14 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; exports.loopAsync = loopAsync; exports.mapAsync = mapAsync; function loopAsync(turns, work, callback) { var currentTurn = 0, isDone = false; var sync = false, hasNext = false, doneArgs = void 0; function done() { isDone = true; if (sync) { // Iterate instead of recursing if possible. doneArgs = [].concat(Array.prototype.slice.call(arguments)); return; } callback.apply(this, arguments); } function next() { if (isDone) { return; } hasNext = true; if (sync) { // Iterate instead of recursing if possible. return; } sync = true; while (!isDone && currentTurn < turns && hasNext) { hasNext = false; work.call(this, currentTurn++, next, done); } sync = false; if (isDone) { // This means the loop finished synchronously. callback.apply(this, doneArgs); return; } if (currentTurn >= turns && hasNext) { isDone = true; callback(); } } next(); } function mapAsync(array, work, callback) { var length = array.length; var values = []; if (length === 0) return callback(null, values); var isDone = false, doneCount = 0; function done(index, error, value) { if (isDone) return; if (error) { isDone = true; callback(error); } else { values[index] = value; isDone = ++doneCount === length; if (isDone) callback(null, values); } } array.forEach(function (item, index) { work(item, index, function (error, value) { done(index, error, value); }); }); } /***/ }), /* 15 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ContextProvider = ContextProvider; exports.ContextSubscriber = ContextSubscriber; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(2); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Works around issues with context updates failing to propagate. // Caveat: the context value is expected to never change its identity. // https://github.com/facebook/react/issues/2517 // https://github.com/reactjs/react-router/issues/470 var contextProviderShape = _propTypes2.default.shape({ subscribe: _propTypes2.default.func.isRequired, eventIndex: _propTypes2.default.number.isRequired }); function makeContextName(name) { return '@@contextSubscriber/' + name; } var prefixUnsafeLifecycleMethods = parseFloat(_react2.default.version) >= 16.3; function ContextProvider(name) { var _childContextTypes, _config; var contextName = makeContextName(name); var listenersKey = contextName + '/listeners'; var eventIndexKey = contextName + '/eventIndex'; var subscribeKey = contextName + '/subscribe'; var config = (_config = { childContextTypes: (_childContextTypes = {}, _childContextTypes[contextName] = contextProviderShape.isRequired, _childContextTypes), getChildContext: function getChildContext() { var _ref; return _ref = {}, _ref[contextName] = { eventIndex: this[eventIndexKey], subscribe: this[subscribeKey] }, _ref; }, // this method will be updated to UNSAFE_componentWillMount below for React versions >= 16.3 componentWillMount: function componentWillMount() { this[listenersKey] = []; this[eventIndexKey] = 0; }, // this method will be updated to UNSAFE_componentWillReceiveProps below for React versions >= 16.3 componentWillReceiveProps: function componentWillReceiveProps() { this[eventIndexKey]++; }, componentDidUpdate: function componentDidUpdate() { var _this = this; this[listenersKey].forEach(function (listener) { return listener(_this[eventIndexKey]); }); } }, _config[subscribeKey] = function (listener) { var _this2 = this; // No need to immediately call listener here. this[listenersKey].push(listener); return function () { _this2[listenersKey] = _this2[listenersKey].filter(function (item) { return item !== listener; }); }; }, _config); if (prefixUnsafeLifecycleMethods) { config.UNSAFE_componentWillMount = config.componentWillMount; config.UNSAFE_componentWillReceiveProps = config.componentWillReceiveProps; delete config.componentWillMount; delete config.componentWillReceiveProps; } return config; } function ContextSubscriber(name) { var _contextTypes, _config2; var contextName = makeContextName(name); var lastRenderedEventIndexKey = contextName + '/lastRenderedEventIndex'; var handleContextUpdateKey = contextName + '/handleContextUpdate'; var unsubscribeKey = contextName + '/unsubscribe'; var config = (_config2 = { contextTypes: (_contextTypes = {}, _contextTypes[contextName] = contextProviderShape, _contextTypes), getInitialState: function getInitialState() { var _ref2; if (!this.context[contextName]) { return {}; } return _ref2 = {}, _ref2[lastRenderedEventIndexKey] = this.context[contextName].eventIndex, _ref2; }, componentDidMount: function componentDidMount() { if (!this.context[contextName]) { return; } this[unsubscribeKey] = this.context[contextName].subscribe(this[handleContextUpdateKey]); }, // this method will be updated to UNSAFE_componentWillReceiveProps below for React versions >= 16.3 componentWillReceiveProps: function componentWillReceiveProps() { var _setState; if (!this.context[contextName]) { return; } this.setState((_setState = {}, _setState[lastRenderedEventIndexKey] = this.context[contextName].eventIndex, _setState)); }, componentWillUnmount: function componentWillUnmount() { if (!this[unsubscribeKey]) { return; } this[unsubscribeKey](); this[unsubscribeKey] = null; } }, _config2[handleContextUpdateKey] = function (eventIndex) { if (eventIndex !== this.state[lastRenderedEventIndexKey]) { var _setState2; this.setState((_setState2 = {}, _setState2[lastRenderedEventIndexKey] = eventIndex, _setState2)); } }, _config2); if (prefixUnsafeLifecycleMethods) { config.UNSAFE_componentWillReceiveProps = config.componentWillReceiveProps; delete config.componentWillReceiveProps; } return config; } /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.locationShape = exports.routerShape = undefined; var _propTypes = __webpack_require__(2); var routerShape = exports.routerShape = (0, _propTypes.shape)({ push: _propTypes.func.isRequired, replace: _propTypes.func.isRequired, go: _propTypes.func.isRequired, goBack: _propTypes.func.isRequired, goForward: _propTypes.func.isRequired, setRouteLeaveHook: _propTypes.func.isRequired, isActive: _propTypes.func.isRequired }); var locationShape = exports.locationShape = (0, _propTypes.shape)({ pathname: _propTypes.string.isRequired, search: _propTypes.string.isRequired, state: _propTypes.object, action: _propTypes.string.isRequired, key: _propTypes.string }); /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _reactIs = __webpack_require__(23); var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _getRouteParams = __webpack_require__(46); var _getRouteParams2 = _interopRequireDefault(_getRouteParams); var _ContextUtils = __webpack_require__(15); var _RouteUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * A <RouterContext> renders the component tree for a given router state * and sets the history object and the current location in context. */ var RouterContext = (0, _createReactClass2.default)({ displayName: 'RouterContext', mixins: [(0, _ContextUtils.ContextProvider)('router')], propTypes: { router: _propTypes.object.isRequired, location: _propTypes.object.isRequired, routes: _propTypes.array.isRequired, params: _propTypes.object.isRequired, components: _propTypes.array.isRequired, createElement: _propTypes.func.isRequired }, getDefaultProps: function getDefaultProps() { return { createElement: _react2.default.createElement }; }, childContextTypes: { router: _propTypes.object.isRequired }, getChildContext: function getChildContext() { return { router: this.props.router }; }, createElement: function createElement(component, props) { return component == null ? null : this.props.createElement(component, props); }, render: function render() { var _this = this; var _props = this.props, location = _props.location, routes = _props.routes, params = _props.params, components = _props.components, router = _props.router; var element = null; if (components) { element = components.reduceRight(function (element, components, index) { if (components == null) return element; // Don't create new children; use the grandchildren. var route = routes[index]; var routeParams = (0, _getRouteParams2.default)(route, params); var props = { location: location, params: params, route: route, router: router, routeParams: routeParams, routes: routes }; if ((0, _RouteUtils.isReactChildren)(element)) { props.children = element; } else if (element) { for (var prop in element) { if (Object.prototype.hasOwnProperty.call(element, prop)) props[prop] = element[prop]; } } // Handle components is object for { [name]: component } but not valid element // type of react, such as React.memo, React.lazy and so on. if ((typeof components === 'undefined' ? 'undefined' : _typeof(components)) === 'object' && !(0, _reactIs.isValidElementType)(components)) { var elements = {}; for (var key in components) { if (Object.prototype.hasOwnProperty.call(components, key)) { // Pass through the key as a prop to createElement to allow // custom createElement functions to know which named component // they're rendering, for e.g. matching up to fetched data. elements[key] = _this.createElement(components[key], _extends({ key: key }, props)); } } return elements; } return _this.createElement(components, props); }, element); } !(element === null || element === false || _react2.default.isValidElement(element)) ? true ? (0, _invariant2.default)(false, 'The root route must render a single element') : (0, _invariant2.default)(false) : void 0; return element; } }); exports.default = RouterContext; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.go = exports.replaceLocation = exports.pushLocation = exports.startListener = exports.getUserConfirmation = exports.getCurrentLocation = undefined; var _LocationUtils = __webpack_require__(10); var _DOMUtils = __webpack_require__(13); var _DOMStateStorage = __webpack_require__(32); var _PathUtils = __webpack_require__(6); var _ExecutionEnvironment = __webpack_require__(19); var PopStateEvent = 'popstate'; var HashChangeEvent = 'hashchange'; var needsHashchangeListener = _ExecutionEnvironment.canUseDOM && !(0, _DOMUtils.supportsPopstateOnHashchange)(); var _createLocation = function _createLocation(historyState) { var key = historyState && historyState.key; return (0, _LocationUtils.createLocation)({ pathname: window.location.pathname, search: window.location.search, hash: window.location.hash, state: key ? (0, _DOMStateStorage.readState)(key) : undefined }, undefined, key); }; var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation() { var historyState = void 0; try { historyState = window.history.state || {}; } catch (error) { // IE 11 sometimes throws when accessing window.history.state // See https://github.com/ReactTraining/history/pull/289 historyState = {}; } return _createLocation(historyState); }; var getUserConfirmation = exports.getUserConfirmation = function getUserConfirmation(message, callback) { return callback(window.confirm(message)); }; // eslint-disable-line no-alert var startListener = exports.startListener = function startListener(listener) { var handlePopState = function handlePopState(event) { if ((0, _DOMUtils.isExtraneousPopstateEvent)(event)) // Ignore extraneous popstate events in WebKit return; listener(_createLocation(event.state)); }; (0, _DOMUtils.addEventListener)(window, PopStateEvent, handlePopState); var handleUnpoppedHashChange = function handleUnpoppedHashChange() { return listener(getCurrentLocation()); }; if (needsHashchangeListener) { (0, _DOMUtils.addEventListener)(window, HashChangeEvent, handleUnpoppedHashChange); } return function () { (0, _DOMUtils.removeEventListener)(window, PopStateEvent, handlePopState); if (needsHashchangeListener) { (0, _DOMUtils.removeEventListener)(window, HashChangeEvent, handleUnpoppedHashChange); } }; }; var updateLocation = function updateLocation(location, updateState) { var state = location.state, key = location.key; if (state !== undefined) (0, _DOMStateStorage.saveState)(key, state); updateState({ key: key }, (0, _PathUtils.createPath)(location)); }; var pushLocation = exports.pushLocation = function pushLocation(location) { return updateLocation(location, function (state, path) { return window.history.pushState(state, null, path); }); }; var replaceLocation = exports.replaceLocation = function replaceLocation(location) { return updateLocation(location, function (state, path) { return window.history.replaceState(state, null, path); }); }; var go = exports.go = function go(n) { if (n) window.history.go(n); }; /***/ }), /* 19 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; var canUseDOM = exports.canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _AsyncUtils = __webpack_require__(57); var _PathUtils = __webpack_require__(6); var _runTransitionHook = __webpack_require__(21); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _Actions = __webpack_require__(12); var _LocationUtils = __webpack_require__(10); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createHistory = function createHistory() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var getCurrentLocation = options.getCurrentLocation, getUserConfirmation = options.getUserConfirmation, pushLocation = options.pushLocation, replaceLocation = options.replaceLocation, go = options.go, keyLength = options.keyLength; var currentLocation = void 0; var pendingLocation = void 0; var beforeListeners = []; var listeners = []; var allKeys = []; var getCurrentIndex = function getCurrentIndex() { if (pendingLocation && pendingLocation.action === _Actions.POP) return allKeys.indexOf(pendingLocation.key); if (currentLocation) return allKeys.indexOf(currentLocation.key); return -1; }; var updateLocation = function updateLocation(nextLocation) { var currentIndex = getCurrentIndex(); currentLocation = nextLocation; if (currentLocation.action === _Actions.PUSH) { allKeys = [].concat(allKeys.slice(0, currentIndex + 1), [currentLocation.key]); } else if (currentLocation.action === _Actions.REPLACE) { allKeys[currentIndex] = currentLocation.key; } listeners.forEach(function (listener) { return listener(currentLocation); }); }; var listenBefore = function listenBefore(listener) { beforeListeners.push(listener); return function () { return beforeListeners = beforeListeners.filter(function (item) { return item !== listener; }); }; }; var listen = function listen(listener) { listeners.push(listener); return function () { return listeners = listeners.filter(function (item) { return item !== listener; }); }; }; var confirmTransitionTo = function confirmTransitionTo(location, callback) { (0, _AsyncUtils.loopAsync)(beforeListeners.length, function (index, next, done) { (0, _runTransitionHook2.default)(beforeListeners[index], location, function (result) { return result != null ? done(result) : next(); }); }, function (message) { if (getUserConfirmation && typeof message === 'string') { getUserConfirmation(message, function (ok) { return callback(ok !== false); }); } else { callback(message !== false); } }); }; var transitionTo = function transitionTo(nextLocation) { if (currentLocation && (0, _LocationUtils.locationsAreEqual)(currentLocation, nextLocation) || pendingLocation && (0, _LocationUtils.locationsAreEqual)(pendingLocation, nextLocation)) return; // Nothing to do pendingLocation = nextLocation; confirmTransitionTo(nextLocation, function (ok) { if (pendingLocation !== nextLocation) return; // Transition was interrupted during confirmation pendingLocation = null; if (ok) { // Treat PUSH to same path like REPLACE to be consistent with browsers if (nextLocation.action === _Actions.PUSH) { var prevPath = (0, _PathUtils.createPath)(currentLocation); var nextPath = (0, _PathUtils.createPath)(nextLocation); if (nextPath === prevPath && (0, _LocationUtils.statesAreEqual)(currentLocation.state, nextLocation.state)) nextLocation.action = _Actions.REPLACE; } if (nextLocation.action === _Actions.POP) { updateLocation(nextLocation); } else if (nextLocation.action === _Actions.PUSH) { if (pushLocation(nextLocation) !== false) updateLocation(nextLocation); } else if (nextLocation.action === _Actions.REPLACE) { if (replaceLocation(nextLocation) !== false) updateLocation(nextLocation); } } else if (currentLocation && nextLocation.action === _Actions.POP) { var prevIndex = allKeys.indexOf(currentLocation.key); var nextIndex = allKeys.indexOf(nextLocation.key); if (prevIndex !== -1 && nextIndex !== -1) go(prevIndex - nextIndex); // Restore the URL } }); }; var push = function push(input) { return transitionTo(createLocation(input, _Actions.PUSH)); }; var replace = function replace(input) { return transitionTo(createLocation(input, _Actions.REPLACE)); }; var goBack = function goBack() { return go(-1); }; var goForward = function goForward() { return go(1); }; var createKey = function createKey() { return Math.random().toString(36).substr(2, keyLength || 6); }; var createHref = function createHref(location) { return (0, _PathUtils.createPath)(location); }; var createLocation = function createLocation(location, action) { var key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : createKey(); return (0, _LocationUtils.createLocation)(location, action, key); }; return { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, transitionTo: transitionTo, push: push, replace: replace, go: go, goBack: goBack, goForward: goForward, createKey: createKey, createPath: _PathUtils.createPath, createHref: createHref, createLocation: createLocation }; }; exports.default = createHistory; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var runTransitionHook = function runTransitionHook(hook, location, callback) { var result = hook(location, callback); if (hook.length < 2) { // Assume the hook runs synchronously and automatically // call the callback with the return value. callback(result); } else { true ? (0, _warning2.default)(result === undefined, 'You should not "return" in a transition hook with a callback argument; ' + 'call the callback instead') : void 0; } }; exports.default = runTransitionHook; /***/ }), /* 22 */ /***/ (function(module, exports) { /* object-assign (c) Sindre Sorhus @license MIT */ 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; if (false) { module.exports = require('./cjs/react-is.production.min.js'); } else { module.exports = __webpack_require__(67); } /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _PropTypes = __webpack_require__(16); var _ContextUtils = __webpack_require__(15); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function resolveToLocation(to, router) { return typeof to === 'function' ? to(router.location) : to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> */ var Link = (0, _createReactClass2.default)({ displayName: 'Link', mixins: [(0, _ContextUtils.ContextSubscriber)('router')], contextTypes: { router: _PropTypes.routerShape }, propTypes: { to: (0, _propTypes.oneOfType)([_propTypes.string, _propTypes.object, _propTypes.func]), activeStyle: _propTypes.object, activeClassName: _propTypes.string, onlyActiveOnIndex: _propTypes.bool.isRequired, onClick: _propTypes.func, target: _propTypes.string, innerRef: (0, _propTypes.oneOfType)([_propTypes.string, _propTypes.func]) }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; var router = this.context.router; !router ? true ? (0, _invariant2.default)(false, '<Link>s rendered outside of a router context cannot navigate.') : (0, _invariant2.default)(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); router.push(resolveToLocation(this.props.to, router)); }, render: function render() { var _props = this.props, to = _props.to, activeClassName = _props.activeClassName, activeStyle = _props.activeStyle, onlyActiveOnIndex = _props.onlyActiveOnIndex, innerRef = _props.innerRef, props = _objectWithoutProperties(_props, ['to', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex', 'innerRef']); // Ignore if rendered outside the context of router to simplify unit testing. var router = this.context.router; if (router) { // If user does not specify a `to` prop, return an empty anchor tag. if (!to) { return _react2.default.createElement('a', _extends({}, props, { ref: innerRef })); } var toLocation = resolveToLocation(to, router); props.href = router.createHref(toLocation); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(toLocation, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return _react2.default.createElement('a', _extends({}, props, { onClick: this.handleClick, ref: innerRef })); } }); exports.default = Link; /***/ }), /* 25 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; exports.isPromise = isPromise; function isPromise(obj) { return obj && typeof obj.then === 'function'; } /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = __webpack_require__(5); var _PatternUtils = __webpack_require__(8); var _InternalPropTypes = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ /* eslint-disable react/require-render-return */ var Redirect = (0, _createReactClass2.default)({ displayName: 'Redirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element) { var route = (0, _RouteUtils.createRouteFromReactElement)(element); if (route.from) route.path = route.from; route.onEnter = function (nextState, replace) { var location = nextState.location, params = nextState.params; var pathname = void 0; if (route.to.charAt(0) === '/') { pathname = (0, _PatternUtils.formatPattern)(route.to, params); } else if (!route.to) { pathname = location.pathname; } else { var routeIndex = nextState.routes.indexOf(route); var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1); var pattern = parentPattern.replace(/\/*$/, '/') + route.to; pathname = (0, _PatternUtils.formatPattern)(pattern, params); } replace({ pathname: pathname, query: route.query || location.query, state: route.state || location.state }); }; return route; }, getRoutePattern: function getRoutePattern(routes, routeIndex) { var parentPattern = ''; for (var i = routeIndex; i >= 0; i--) { var route = routes[i]; var pattern = route.path || ''; parentPattern = pattern.replace(/\/*$/, '/') + parentPattern; if (pattern.indexOf('/') === 0) break; } return '/' + parentPattern; } }, propTypes: { path: _propTypes.string, from: _propTypes.string, // Alias for path to: _propTypes.string.isRequired, query: _propTypes.object, state: _propTypes.object, onEnter: _InternalPropTypes.falsy, children: _InternalPropTypes.falsy }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<Redirect> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = Redirect; /***/ }), /* 27 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.createRouterObject = createRouterObject; exports.assignRouterState = assignRouterState; function createRouterObject(history, transitionManager, state) { var router = _extends({}, history, { setRouteLeaveHook: transitionManager.listenBeforeLeavingRoute, isActive: transitionManager.isActive }); return assignRouterState(router, state); } function assignRouterState(router, _ref) { var location = _ref.location, params = _ref.params, routes = _ref.routes; router.location = location; router.params = params; router.routes = routes; return router; } /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = createMemoryHistory; var _useQueries = __webpack_require__(34); var _useQueries2 = _interopRequireDefault(_useQueries); var _useBasename = __webpack_require__(33); var _useBasename2 = _interopRequireDefault(_useBasename); var _createMemoryHistory = __webpack_require__(62); var _createMemoryHistory2 = _interopRequireDefault(_createMemoryHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createMemoryHistory(options) { // signatures and type checking differ between `useQueries` and // `createMemoryHistory`, have to create `memoryHistory` first because // `useQueries` doesn't understand the signature var memoryHistory = (0, _createMemoryHistory2.default)(options); var createHistory = function createHistory() { return memoryHistory; }; var history = (0, _useQueries2.default)((0, _useBasename2.default)(createHistory))(options); return history; } /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = createRouterHistory; var _useRouterHistory = __webpack_require__(31); var _useRouterHistory2 = _interopRequireDefault(_useRouterHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); function createRouterHistory(createHistory) { var history = void 0; if (canUseDOM) history = (0, _useRouterHistory2.default)(createHistory)(); return history; } /***/ }), /* 30 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = createTransitionManager; var _routerWarning = __webpack_require__(9); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _computeChangedRoutes2 = __webpack_require__(44); var _computeChangedRoutes3 = _interopRequireDefault(_computeChangedRoutes2); var _TransitionUtils = __webpack_require__(41); var _TransitionUtils2 = _interopRequireDefault(_TransitionUtils); var _isActive2 = __webpack_require__(48); var _isActive3 = _interopRequireDefault(_isActive2); var _getComponents = __webpack_require__(45); var _getComponents2 = _interopRequireDefault(_getComponents); var _matchRoutes = __webpack_require__(50); var _matchRoutes2 = _interopRequireDefault(_matchRoutes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function hasAnyProperties(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return true; }return false; } function createTransitionManager(history, routes) { var state = {}; var _getTransitionUtils = (0, _TransitionUtils2.default)(), runEnterHooks = _getTransitionUtils.runEnterHooks, runChangeHooks = _getTransitionUtils.runChangeHooks, runLeaveHooks = _getTransitionUtils.runLeaveHooks; // Signature should be (location, indexOnly), but needs to support (path, // query, indexOnly) function isActive(location, indexOnly) { location = history.createLocation(location); return (0, _isActive3.default)(location, indexOnly, state.location, state.routes, state.params); } var partialNextState = void 0; function match(location, callback) { if (partialNextState && partialNextState.location === location) { // Continue from where we left off. finishMatch(partialNextState, callback); } else { (0, _matchRoutes2.default)(routes, location, function (error, nextState) { if (error) { callback(error); } else if (nextState) { finishMatch(_extends({}, nextState, { location: location }), callback); } else { callback(); } }); } } function finishMatch(nextState, callback) { var _computeChangedRoutes = (0, _computeChangedRoutes3.default)(state, nextState), leaveRoutes = _computeChangedRoutes.leaveRoutes, changeRoutes = _computeChangedRoutes.changeRoutes, enterRoutes = _computeChangedRoutes.enterRoutes; runLeaveHooks(leaveRoutes, state); // Tear down confirmation hooks for left routes leaveRoutes.filter(function (route) { return enterRoutes.indexOf(route) === -1; }).forEach(removeListenBeforeHooksForRoute); // change and enter hooks are run in series runChangeHooks(changeRoutes, state, nextState, function (error, redirectInfo) { if (error || redirectInfo) return handleErrorOrRedirect(error, redirectInfo); runEnterHooks(enterRoutes, nextState, finishEnterHooks); }); function finishEnterHooks(error, redirectInfo) { if (error || redirectInfo) return handleErrorOrRedirect(error, redirectInfo); // TODO: Fetch components after state is updated. (0, _getComponents2.default)(nextState, function (error, components) { if (error) { callback(error); } else { // TODO: Make match a pure function and have some other API // for "match and update state". callback(null, null, state = _extends({}, nextState, { components: components })); } }); } function handleErrorOrRedirect(error, redirectInfo) { if (error) callback(error);else callback(null, redirectInfo); } } var RouteGuid = 1; function getRouteID(route) { var create = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return route.__id__ || create && (route.__id__ = RouteGuid++); } var RouteHooks = Object.create(null); function getRouteHooksForRoutes(routes) { return routes.map(function (route) { return RouteHooks[getRouteID(route)]; }).filter(function (hook) { return hook; }); } function transitionHook(location, callback) { (0, _matchRoutes2.default)(routes, location, function (error, nextState) { if (nextState == null) { // TODO: We didn't actually match anything, but hang // onto error/nextState so we don't have to matchRoutes // again in the listen callback. callback(); return; } // Cache some state here so we don't have to // matchRoutes() again in the listen callback. partialNextState = _extends({}, nextState, { location: location }); var hooks = getRouteHooksForRoutes((0, _computeChangedRoutes3.default)(state, partialNextState).leaveRoutes); var result = void 0; for (var i = 0, len = hooks.length; result == null && i < len; ++i) { // Passing the location arg here indicates to // the user that this is a transition hook. result = hooks[i](location); } callback(result); }); } /* istanbul ignore next: untestable with Karma */ function beforeUnloadHook() { // Synchronously check to see if any route hooks want // to prevent the current window/tab from closing. if (state.routes) { var hooks = getRouteHooksForRoutes(state.routes); var message = void 0; for (var i = 0, len = hooks.length; typeof message !== 'string' && i < len; ++i) { // Passing no args indicates to the user that this is a // beforeunload hook. We don't know the next location. message = hooks[i](); } return message; } } var unlistenBefore = void 0, unlistenBeforeUnload = void 0; function removeListenBeforeHooksForRoute(route) { var routeID = getRouteID(route); if (!routeID) { return; } delete RouteHooks[routeID]; if (!hasAnyProperties(RouteHooks)) { // teardown transition & beforeunload hooks if (unlistenBefore) { unlistenBefore(); unlistenBefore = null; } if (unlistenBeforeUnload) { unlistenBeforeUnload(); unlistenBeforeUnload = null; } } } /** * Registers the given hook function to run before leaving the given route. * * During a normal transition, the hook function receives the next location * as its only argument and can return either a prompt message (string) to show the user, * to make sure they want to leave the page; or `false`, to prevent the transition. * Any other return value will have no effect. * * During the beforeunload event (in browsers) the hook receives no arguments. * In this case it must return a prompt message to prevent the transition. * * Returns a function that may be used to unbind the listener. */ function listenBeforeLeavingRoute(route, hook) { var thereWereNoRouteHooks = !hasAnyProperties(RouteHooks); var routeID = getRouteID(route, true); RouteHooks[routeID] = hook; if (thereWereNoRouteHooks) { // setup transition & beforeunload hooks unlistenBefore = history.listenBefore(transitionHook); if (history.listenBeforeUnload) unlistenBeforeUnload = history.listenBeforeUnload(beforeUnloadHook); } return function () { removeListenBeforeHooksForRoute(route); }; } /** * This is the API for stateful environments. As the location * changes, we update state and call the listener. We can also * gracefully handle errors and redirects. */ function listen(listener) { function historyListener(location) { if (state.location === location) { listener(null, state); } else { match(location, function (error, redirectLocation, nextState) { if (error) { listener(error); } else if (redirectLocation) { history.replace(redirectLocation); } else if (nextState) { listener(null, nextState); } else { true ? (0, _routerWarning2.default)(false, 'Location "%s" did not match any routes', location.pathname + location.search + location.hash) : void 0; } }); } } // TODO: Only use a single history listener. Otherwise we'll end up with // multiple concurrent calls to match. // Set up the history listener first in case the initial match redirects. var unsubscribe = history.listen(historyListener); if (state.location) { // Picking up on a matchContext. listener(null, state); } else { historyListener(history.getCurrentLocation()); } return unsubscribe; } return { isActive: isActive, match: match, listenBeforeLeavingRoute: listenBeforeLeavingRoute, listen: listen }; } /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = useRouterHistory; var _useQueries = __webpack_require__(34); var _useQueries2 = _interopRequireDefault(_useQueries); var _useBasename = __webpack_require__(33); var _useBasename2 = _interopRequireDefault(_useBasename); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function useRouterHistory(createHistory) { return function (options) { var history = (0, _useQueries2.default)((0, _useBasename2.default)(createHistory))(options); return history; }; } /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.readState = exports.saveState = undefined; var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var QuotaExceededErrors = { QuotaExceededError: true, QUOTA_EXCEEDED_ERR: true }; var SecurityErrors = { SecurityError: true }; var KeyPrefix = '@@History/'; var createKey = function createKey(key) { return KeyPrefix + key; }; var saveState = exports.saveState = function saveState(key, state) { if (!window.sessionStorage) { // Session storage is not available or hidden. // sessionStorage is undefined in Internet Explorer when served via file protocol. true ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available') : void 0; return; } try { if (state == null) { window.sessionStorage.removeItem(createKey(key)); } else { window.sessionStorage.setItem(createKey(key), JSON.stringify(state)); } } catch (error) { if (SecurityErrors[error.name]) { // Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any // attempt to access window.sessionStorage. true ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available due to security settings') : void 0; return; } if (QuotaExceededErrors[error.name] && window.sessionStorage.length === 0) { // Safari "private mode" throws QuotaExceededError. true ? (0, _warning2.default)(false, '[history] Unable to save state; sessionStorage is not available in Safari private mode') : void 0; return; } throw error; } }; var readState = exports.readState = function readState(key) { var json = void 0; try { json = window.sessionStorage.getItem(createKey(key)); } catch (error) { if (SecurityErrors[error.name]) { // Blocking cookies in Chrome/Firefox/Safari throws SecurityError on any // attempt to access window.sessionStorage. true ? (0, _warning2.default)(false, '[history] Unable to read state; sessionStorage is not available due to security settings') : void 0; return undefined; } } if (json) { try { return JSON.parse(json); } catch (error) { // Ignore invalid JSON. } } return undefined; }; /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _runTransitionHook = __webpack_require__(21); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _PathUtils = __webpack_require__(6); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var useBasename = function useBasename(createHistory) { return function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var history = createHistory(options); var basename = options.basename; var addBasename = function addBasename(location) { if (!location) return location; if (basename && location.basename == null) { if (location.pathname.toLowerCase().indexOf(basename.toLowerCase()) === 0) { location.pathname = location.pathname.substring(basename.length); location.basename = basename; if (location.pathname === '') location.pathname = '/'; } else { location.basename = ''; } } return location; }; var prependBasename = function prependBasename(location) { if (!basename) return location; var object = typeof location === 'string' ? (0, _PathUtils.parsePath)(location) : location; var pname = object.pathname; var normalizedBasename = basename.slice(-1) === '/' ? basename : basename + '/'; var normalizedPathname = pname.charAt(0) === '/' ? pname.slice(1) : pname; var pathname = normalizedBasename + normalizedPathname; return _extends({}, object, { pathname: pathname }); }; // Override all read methods with basename-aware versions. var getCurrentLocation = function getCurrentLocation() { return addBasename(history.getCurrentLocation()); }; var listenBefore = function listenBefore(hook) { return history.listenBefore(function (location, callback) { return (0, _runTransitionHook2.default)(hook, addBasename(location), callback); }); }; var listen = function listen(listener) { return history.listen(function (location) { return listener(addBasename(location)); }); }; // Override all write methods with basename-aware versions. var push = function push(location) { return history.push(prependBasename(location)); }; var replace = function replace(location) { return history.replace(prependBasename(location)); }; var createPath = function createPath(location) { return history.createPath(prependBasename(location)); }; var createHref = function createHref(location) { return history.createHref(prependBasename(location)); }; var createLocation = function createLocation(location) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return addBasename(history.createLocation.apply(history, [prependBasename(location)].concat(args))); }; return _extends({}, history, { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, push: push, replace: replace, createPath: createPath, createHref: createHref, createLocation: createLocation }); }; }; exports.default = useBasename; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _queryString = __webpack_require__(66); var _runTransitionHook = __webpack_require__(21); var _runTransitionHook2 = _interopRequireDefault(_runTransitionHook); var _LocationUtils = __webpack_require__(10); var _PathUtils = __webpack_require__(6); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultStringifyQuery = function defaultStringifyQuery(query) { return (0, _queryString.stringify)(query).replace(/%20/g, '+'); }; var defaultParseQueryString = _queryString.parse; /** * Returns a new createHistory function that may be used to create * history objects that know how to handle URL queries. */ var useQueries = function useQueries(createHistory) { return function () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var history = createHistory(options); var stringifyQuery = options.stringifyQuery, parseQueryString = options.parseQueryString; if (typeof stringifyQuery !== 'function') stringifyQuery = defaultStringifyQuery; if (typeof parseQueryString !== 'function') parseQueryString = defaultParseQueryString; var decodeQuery = function decodeQuery(location) { if (!location) return location; if (location.query == null) location.query = parseQueryString(location.search.substring(1)); return location; }; var encodeQuery = function encodeQuery(location, query) { if (query == null) return location; var object = typeof location === 'string' ? (0, _PathUtils.parsePath)(location) : location; var queryString = stringifyQuery(query); var search = queryString ? '?' + queryString : ''; return _extends({}, object, { search: search }); }; // Override all read methods with query-aware versions. var getCurrentLocation = function getCurrentLocation() { return decodeQuery(history.getCurrentLocation()); }; var listenBefore = function listenBefore(hook) { return history.listenBefore(function (location, callback) { return (0, _runTransitionHook2.default)(hook, decodeQuery(location), callback); }); }; var listen = function listen(listener) { return history.listen(function (location) { return listener(decodeQuery(location)); }); }; // Override all write methods with query-aware versions. var push = function push(location) { return history.push(encodeQuery(location, location.query)); }; var replace = function replace(location) { return history.replace(encodeQuery(location, location.query)); }; var createPath = function createPath(location) { return history.createPath(encodeQuery(location, location.query)); }; var createHref = function createHref(location) { return history.createHref(encodeQuery(location, location.query)); }; var createLocation = function createLocation(location) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var newLocation = history.createLocation.apply(history, [encodeQuery(location, location.query)].concat(args)); if (location.query) newLocation.query = (0, _LocationUtils.createQuery)(location.query); return decodeQuery(newLocation); }; return _extends({}, history, { getCurrentLocation: getCurrentLocation, listenBefore: listenBefore, listen: listen, push: push, replace: replace, createPath: createPath, createHref: createHref, createLocation: createLocation }); }; }; exports.default = useQueries; /***/ }), /* 35 */ /***/ (function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _Link = __webpack_require__(24); var _Link2 = _interopRequireDefault(_Link); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * An <IndexLink> is used to link to an <IndexRoute>. */ var IndexLink = (0, _createReactClass2.default)({ displayName: 'IndexLink', render: function render() { return _react2.default.createElement(_Link2.default, _extends({}, this.props, { onlyActiveOnIndex: true })); } }); exports.default = IndexLink; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _routerWarning = __webpack_require__(9); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _Redirect = __webpack_require__(26); var _Redirect2 = _interopRequireDefault(_Redirect); var _InternalPropTypes = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * An <IndexRedirect> is used to redirect from an indexRoute. */ /* eslint-disable react/require-render-return */ var IndexRedirect = (0, _createReactClass2.default)({ displayName: 'IndexRedirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _Redirect2.default.createRouteFromReactElement(element); } else { true ? (0, _routerWarning2.default)(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0; } } }, propTypes: { to: _propTypes.string.isRequired, query: _propTypes.object, state: _propTypes.object, onEnter: _InternalPropTypes.falsy, children: _InternalPropTypes.falsy }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = IndexRedirect; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _routerWarning = __webpack_require__(9); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = __webpack_require__(5); var _InternalPropTypes = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ /* eslint-disable react/require-render-return */ var IndexRoute = (0, _createReactClass2.default)({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = (0, _RouteUtils.createRouteFromReactElement)(element); } else { true ? (0, _routerWarning2.default)(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: _InternalPropTypes.falsy, component: _InternalPropTypes.component, components: _InternalPropTypes.components, getComponent: _propTypes.func, getComponents: _propTypes.func }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = IndexRoute; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _RouteUtils = __webpack_require__(5); var _InternalPropTypes = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * A <Route> is used to declare which components are rendered to the * page when the URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is * requested, the tree is searched depth-first to find a route whose * path matches the URL. When one is found, all routes in the tree * that lead to it are considered "active" and their components are * rendered into the DOM, nested in the same order as in the tree. */ /* eslint-disable react/require-render-return */ var Route = (0, _createReactClass2.default)({ displayName: 'Route', statics: { createRouteFromReactElement: _RouteUtils.createRouteFromReactElement }, propTypes: { path: _propTypes.string, component: _InternalPropTypes.component, components: _InternalPropTypes.components, getComponent: _propTypes.func, getComponents: _propTypes.func }, /* istanbul ignore next: sanity check */ render: function render() { true ? true ? (0, _invariant2.default)(false, '<Route> elements are for router configuration only and should not be rendered') : (0, _invariant2.default)(false) : void 0; } }); exports.default = Route; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _propTypes = __webpack_require__(2); var _createTransitionManager2 = __webpack_require__(30); var _createTransitionManager3 = _interopRequireDefault(_createTransitionManager2); var _InternalPropTypes = __webpack_require__(11); var _RouterContext = __webpack_require__(17); var _RouterContext2 = _interopRequireDefault(_RouterContext); var _RouteUtils = __webpack_require__(5); var _RouterUtils = __webpack_require__(27); var _routerWarning = __webpack_require__(9); var _routerWarning2 = _interopRequireDefault(_routerWarning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var propTypes = { history: _propTypes.object, children: _InternalPropTypes.routes, routes: _InternalPropTypes.routes, // alias for children render: _propTypes.func, createElement: _propTypes.func, onError: _propTypes.func, onUpdate: _propTypes.func, // PRIVATE: For client-side rehydration of server match. matchContext: _propTypes.object }; var prefixUnsafeLifecycleMethods = parseFloat(_react2.default.version) >= 16.3; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = (0, _createReactClass2.default)({ displayName: 'Router', propTypes: propTypes, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return _react2.default.createElement(_RouterContext2.default, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, createRouterObject: function createRouterObject(state) { var matchContext = this.props.matchContext; if (matchContext) { return matchContext.router; } var history = this.props.history; return (0, _RouterUtils.createRouterObject)(history, this.transitionManager, state); }, createTransitionManager: function createTransitionManager() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext.transitionManager; } var history = this.props.history; var _props = this.props, routes = _props.routes, children = _props.children; !history.getCurrentLocation ? true ? (0, _invariant2.default)(false, 'You have provided a history object created with history v4.x or v2.x ' + 'and earlier. This version of React Router is only compatible with v3 ' + 'history objects. Please change to history v3.x.') : (0, _invariant2.default)(false) : void 0; return (0, _createTransitionManager3.default)(history, (0, _RouteUtils.createRoutes)(routes || children)); }, // this method will be updated to UNSAFE_componentWillMount below for React versions >= 16.3 componentWillMount: function componentWillMount() { var _this = this; this.transitionManager = this.createTransitionManager(); this.router = this.createRouterObject(this.state); this._unlisten = this.transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { // Keep the identity of this.router because of a caveat in ContextUtils: // they only work if the object identity is preserved. (0, _RouterUtils.assignRouterState)(_this.router, state); _this.setState(state, _this.props.onUpdate); } }); }, // this method will be updated to UNSAFE_componentWillReceiveProps below for React versions >= 16.3 /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { true ? (0, _routerWarning2.default)(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : void 0; true ? (0, _routerWarning2.default)((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : void 0; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state, location = _state.location, routes = _state.routes, params = _state.params, components = _state.components; var _props2 = this.props, createElement = _props2.createElement, render = _props2.render, props = _objectWithoutProperties(_props2, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); if (prefixUnsafeLifecycleMethods) { Router.prototype.UNSAFE_componentWillReceiveProps = Router.prototype.componentWillReceiveProps; Router.prototype.UNSAFE_componentWillMount = Router.prototype.componentWillMount; delete Router.prototype.componentWillReceiveProps; delete Router.prototype.componentWillMount; } exports.default = Router; /***/ }), /* 41 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.default = getTransitionUtils; var _AsyncUtils = __webpack_require__(14); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var PendingHooks = function PendingHooks() { var _this = this; _classCallCheck(this, PendingHooks); this.hooks = []; this.add = function (hook) { return _this.hooks.push(hook); }; this.remove = function (hook) { return _this.hooks = _this.hooks.filter(function (h) { return h !== hook; }); }; this.has = function (hook) { return _this.hooks.indexOf(hook) !== -1; }; this.clear = function () { return _this.hooks = []; }; }; function getTransitionUtils() { var enterHooks = new PendingHooks(); var changeHooks = new PendingHooks(); function createTransitionHook(hook, route, asyncArity, pendingHooks) { var isSync = hook.length < asyncArity; var transitionHook = function transitionHook() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } hook.apply(route, args); if (isSync) { var callback = args[args.length - 1]; // Assume hook executes synchronously and // automatically call the callback. callback(); } }; pendingHooks.add(transitionHook); return transitionHook; } function getEnterHooks(routes) { return routes.reduce(function (hooks, route) { if (route.onEnter) hooks.push(createTransitionHook(route.onEnter, route, 3, enterHooks)); return hooks; }, []); } function getChangeHooks(routes) { return routes.reduce(function (hooks, route) { if (route.onChange) hooks.push(createTransitionHook(route.onChange, route, 4, changeHooks)); return hooks; }, []); } function runTransitionHooks(length, iter, callback) { if (!length) { callback(); return; } var redirectInfo = void 0; function replace(location) { redirectInfo = location; } (0, _AsyncUtils.loopAsync)(length, function (index, next, done) { iter(index, replace, function (error) { if (error || redirectInfo) { done(error, redirectInfo); // No need to continue. } else { next(); } }); }, callback); } /** * Runs all onEnter hooks in the given array of routes in order * with onEnter(nextState, replace, callback) and calls * callback(error, redirectInfo) when finished. The first hook * to use replace short-circuits the loop. * * If a hook needs to run asynchronously, it may use the callback * function. However, doing so will cause the transition to pause, * which could lead to a non-responsive UI if the hook is slow. */ function runEnterHooks(routes, nextState, callback) { enterHooks.clear(); var hooks = getEnterHooks(routes); return runTransitionHooks(hooks.length, function (index, replace, next) { var wrappedNext = function wrappedNext() { if (enterHooks.has(hooks[index])) { next.apply(undefined, arguments); enterHooks.remove(hooks[index]); } }; hooks[index](nextState, replace, wrappedNext); }, callback); } /** * Runs all onChange hooks in the given array of routes in order * with onChange(prevState, nextState, replace, callback) and calls * callback(error, redirectInfo) when finished. The first hook * to use replace short-circuits the loop. * * If a hook needs to run asynchronously, it may use the callback * function. However, doing so will cause the transition to pause, * which could lead to a non-responsive UI if the hook is slow. */ function runChangeHooks(routes, state, nextState, callback) { changeHooks.clear(); var hooks = getChangeHooks(routes); return runTransitionHooks(hooks.length, function (index, replace, next) { var wrappedNext = function wrappedNext() { if (changeHooks.has(hooks[index])) { next.apply(undefined, arguments); changeHooks.remove(hooks[index]); } }; hooks[index](state, nextState, replace, wrappedNext); }, callback); } /** * Runs all onLeave hooks in the given array of routes in order. */ function runLeaveHooks(routes, prevState) { for (var i = 0, len = routes.length; i < len; ++i) { if (routes[i].onLeave) routes[i].onLeave.call(routes[i], prevState); } } return { runEnterHooks: runEnterHooks, runChangeHooks: runChangeHooks, runLeaveHooks: runLeaveHooks }; } /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _RouterContext = __webpack_require__(17); var _RouterContext2 = _interopRequireDefault(_RouterContext); var _routerWarning = __webpack_require__(9); var _routerWarning2 = _interopRequireDefault(_routerWarning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = function () { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } if (true) { middlewares.forEach(function (middleware, index) { true ? (0, _routerWarning2.default)(middleware.renderRouterContext || middleware.renderRouteComponent, 'The middleware specified at index ' + index + ' does not appear to be ' + 'a valid React Router middleware.') : void 0; }); } var withContext = middlewares.map(function (middleware) { return middleware.renderRouterContext; }).filter(Boolean); var withComponent = middlewares.map(function (middleware) { return middleware.renderRouteComponent; }).filter(Boolean); var makeCreateElement = function makeCreateElement() { var baseCreateElement = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _react.createElement; return function (Component, props) { return withComponent.reduceRight(function (previous, renderRouteComponent) { return renderRouteComponent(previous, props); }, baseCreateElement(Component, props)); }; }; return function (renderProps) { return withContext.reduceRight(function (previous, renderRouterContext) { return renderRouterContext(previous, renderProps); }, _react2.default.createElement(_RouterContext2.default, _extends({}, renderProps, { createElement: makeCreateElement(renderProps.createElement) }))); }; }; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createBrowserHistory = __webpack_require__(60); var _createBrowserHistory2 = _interopRequireDefault(_createBrowserHistory); var _createRouterHistory = __webpack_require__(29); var _createRouterHistory2 = _interopRequireDefault(_createRouterHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _createRouterHistory2.default)(_createBrowserHistory2.default); /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _PatternUtils = __webpack_require__(8); function routeParamsChanged(route, prevState, nextState) { if (!route.path) return false; var paramNames = (0, _PatternUtils.getParamNames)(route.path); return paramNames.some(function (paramName) { return prevState.params[paramName] !== nextState.params[paramName]; }); } /** * Returns an object of { leaveRoutes, changeRoutes, enterRoutes } determined by * the change from prevState to nextState. We leave routes if either * 1) they are not in the next state or 2) they are in the next state * but their params have changed (i.e. /users/123 => /users/456). * * leaveRoutes are ordered starting at the leaf route of the tree * we're leaving up to the common parent route. enterRoutes are ordered * from the top of the tree we're entering down to the leaf route. * * changeRoutes are any routes that didn't leave or enter during * the transition. */ function computeChangedRoutes(prevState, nextState) { var prevRoutes = prevState && prevState.routes; var nextRoutes = nextState.routes; var leaveRoutes = void 0, changeRoutes = void 0, enterRoutes = void 0; if (prevRoutes) { var parentIsLeaving = false; leaveRoutes = prevRoutes.filter(function (route) { if (parentIsLeaving) { return true; } else { var isLeaving = nextRoutes.indexOf(route) === -1 || routeParamsChanged(route, prevState, nextState); if (isLeaving) parentIsLeaving = true; return isLeaving; } }); // onLeave hooks start at the leaf route. leaveRoutes.reverse(); enterRoutes = []; changeRoutes = []; nextRoutes.forEach(function (route) { var isNew = prevRoutes.indexOf(route) === -1; var paramsChanged = leaveRoutes.indexOf(route) !== -1; if (isNew || paramsChanged) enterRoutes.push(route);else changeRoutes.push(route); }); } else { leaveRoutes = []; changeRoutes = []; enterRoutes = nextRoutes; } return { leaveRoutes: leaveRoutes, changeRoutes: changeRoutes, enterRoutes: enterRoutes }; } exports.default = computeChangedRoutes; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _AsyncUtils = __webpack_require__(14); var _PromiseUtils = __webpack_require__(25); function getComponentsForRoute(nextState, route, callback) { if (route.component || route.components) { callback(null, route.component || route.components); return; } var getComponent = route.getComponent || route.getComponents; if (getComponent) { var componentReturn = getComponent.call(route, nextState, callback); if ((0, _PromiseUtils.isPromise)(componentReturn)) componentReturn.then(function (component) { return callback(null, component); }, callback); } else { callback(); } } /** * Asynchronously fetches all components needed for the given router * state and calls callback(error, components) when finished. * * Note: This operation may finish synchronously if no routes have an * asynchronous getComponents method. */ function getComponents(nextState, callback) { (0, _AsyncUtils.mapAsync)(nextState.routes, function (route, index, callback) { getComponentsForRoute(nextState, route, callback); }, callback); } exports.default = getComponents; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _PatternUtils = __webpack_require__(8); /** * Extracts an object of params the given route cares about from * the given params object. */ function getRouteParams(route, params) { var routeParams = {}; if (!route.path) return routeParams; (0, _PatternUtils.getParamNames)(route.path).forEach(function (p) { if (Object.prototype.hasOwnProperty.call(params, p)) { routeParams[p] = params[p]; } }); return routeParams; } exports.default = getRouteParams; /***/ }), /* 47 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _createHashHistory = __webpack_require__(61); var _createHashHistory2 = _interopRequireDefault(_createHashHistory); var _createRouterHistory = __webpack_require__(29); var _createRouterHistory2 = _interopRequireDefault(_createRouterHistory); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _createRouterHistory2.default)(_createHashHistory2.default); /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.default = isActive; var _PatternUtils = __webpack_require__(8); function deepEqual(a, b) { if (a == b) return true; if (a == null || b == null) return false; if (Array.isArray(a)) { return Array.isArray(b) && a.length === b.length && a.every(function (item, index) { return deepEqual(item, b[index]); }); } if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') { for (var p in a) { if (!Object.prototype.hasOwnProperty.call(a, p)) { continue; } if (a[p] === undefined) { if (b[p] !== undefined) { return false; } } else if (!Object.prototype.hasOwnProperty.call(b, p)) { return false; } else if (!deepEqual(a[p], b[p])) { return false; } } return true; } return String(a) === String(b); } /** * Returns true if the current pathname matches the supplied one, net of * leading and trailing slash normalization. This is sufficient for an * indexOnly route match. */ function pathIsActive(pathname, currentPathname) { // Normalize leading slash for consistency. Leading slash on pathname has // already been normalized in isActive. See caveat there. if (currentPathname.charAt(0) !== '/') { currentPathname = '/' + currentPathname; } // Normalize the end of both path names too. Maybe `/foo/` shouldn't show // `/foo` as active, but in this case, we would already have failed the // match. if (pathname.charAt(pathname.length - 1) !== '/') { pathname += '/'; } if (currentPathname.charAt(currentPathname.length - 1) !== '/') { currentPathname += '/'; } return currentPathname === pathname; } /** * Returns true if the given pathname matches the active routes and params. */ function routeIsActive(pathname, routes, params) { var remainingPathname = pathname, paramNames = [], paramValues = []; // for...of would work here but it's probably slower post-transpilation. for (var i = 0, len = routes.length; i < len; ++i) { var route = routes[i]; var pattern = route.path || ''; if (pattern.charAt(0) === '/') { remainingPathname = pathname; paramNames = []; paramValues = []; } if (remainingPathname !== null && pattern) { var matched = (0, _PatternUtils.matchPattern)(pattern, remainingPathname); if (matched) { remainingPathname = matched.remainingPathname; paramNames = [].concat(paramNames, matched.paramNames); paramValues = [].concat(paramValues, matched.paramValues); } else { remainingPathname = null; } if (remainingPathname === '') { // We have an exact match on the route. Just check that all the params // match. // FIXME: This doesn't work on repeated params. return paramNames.every(function (paramName, index) { return String(paramValues[index]) === String(params[paramName]); }); } } } return false; } /** * Returns true if all key/value pairs in the given query are * currently active. */ function queryIsActive(query, activeQuery) { if (activeQuery == null) return query == null; if (query == null) return true; return deepEqual(query, activeQuery); } /** * Returns true if a <Link> to the given pathname/query combination is * currently active. */ function isActive(_ref, indexOnly, currentLocation, routes, params) { var pathname = _ref.pathname, query = _ref.query; if (currentLocation == null) return false; // TODO: This is a bit ugly. It keeps around support for treating pathnames // without preceding slashes as absolute paths, but possibly also works // around the same quirks with basenames as in matchRoutes. if (pathname.charAt(0) !== '/') { pathname = '/' + pathname; } if (!pathIsActive(pathname, currentLocation.pathname)) { // The path check is necessary and sufficient for indexOnly, but otherwise // we still need to check the routes. if (indexOnly || !routeIsActive(pathname, routes, params)) { return false; } } return queryIsActive(query, currentLocation.query); } /***/ }), /* 49 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _Actions = __webpack_require__(12); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _createMemoryHistory = __webpack_require__(28); var _createMemoryHistory2 = _interopRequireDefault(_createMemoryHistory); var _createTransitionManager = __webpack_require__(30); var _createTransitionManager2 = _interopRequireDefault(_createTransitionManager); var _RouteUtils = __webpack_require__(5); var _RouterUtils = __webpack_require__(27); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /** * A high-level API to be used for server-side rendering. * * This function matches a location to a set of routes and calls * callback(error, redirectLocation, renderProps) when finished. * * Note: You probably don't want to use this in a browser unless you're using * server-side rendering with async routes. */ function match(_ref, callback) { var history = _ref.history, routes = _ref.routes, location = _ref.location, options = _objectWithoutProperties(_ref, ['history', 'routes', 'location']); !(history || location) ? true ? (0, _invariant2.default)(false, 'match needs a history or a location') : (0, _invariant2.default)(false) : void 0; history = history ? history : (0, _createMemoryHistory2.default)(options); var transitionManager = (0, _createTransitionManager2.default)(history, (0, _RouteUtils.createRoutes)(routes)); if (location) { // Allow match({ location: '/the/path', ... }) location = history.createLocation(location); } else { location = history.getCurrentLocation(); } transitionManager.match(location, function (error, redirectLocation, nextState) { var renderProps = void 0; if (nextState) { var router = (0, _RouterUtils.createRouterObject)(history, transitionManager, nextState); renderProps = _extends({}, nextState, { router: router, matchContext: { transitionManager: transitionManager, router: router } }); } callback(error, redirectLocation && history.createLocation(redirectLocation, _Actions.REPLACE), renderProps); }); } exports.default = match; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = matchRoutes; var _AsyncUtils = __webpack_require__(14); var _PromiseUtils = __webpack_require__(25); var _PatternUtils = __webpack_require__(8); var _routerWarning = __webpack_require__(9); var _routerWarning2 = _interopRequireDefault(_routerWarning); var _RouteUtils = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getChildRoutes(route, location, paramNames, paramValues, callback) { if (route.childRoutes) { return [null, route.childRoutes]; } if (!route.getChildRoutes) { return []; } var sync = true, result = void 0; var partialNextState = { location: location, params: createParams(paramNames, paramValues) }; var childRoutesReturn = route.getChildRoutes(partialNextState, function (error, childRoutes) { childRoutes = !error && (0, _RouteUtils.createRoutes)(childRoutes); if (sync) { result = [error, childRoutes]; return; } callback(error, childRoutes); }); if ((0, _PromiseUtils.isPromise)(childRoutesReturn)) childRoutesReturn.then(function (childRoutes) { return callback(null, (0, _RouteUtils.createRoutes)(childRoutes)); }, callback); sync = false; return result; // Might be undefined. } function getIndexRoute(route, location, paramNames, paramValues, callback) { if (route.indexRoute) { callback(null, route.indexRoute); } else if (route.getIndexRoute) { var partialNextState = { location: location, params: createParams(paramNames, paramValues) }; var indexRoutesReturn = route.getIndexRoute(partialNextState, function (error, indexRoute) { callback(error, !error && (0, _RouteUtils.createRoutes)(indexRoute)[0]); }); if ((0, _PromiseUtils.isPromise)(indexRoutesReturn)) indexRoutesReturn.then(function (indexRoute) { return callback(null, (0, _RouteUtils.createRoutes)(indexRoute)[0]); }, callback); } else if (route.childRoutes || route.getChildRoutes) { var onChildRoutes = function onChildRoutes(error, childRoutes) { if (error) { callback(error); return; } var pathless = childRoutes.filter(function (childRoute) { return !childRoute.path; }); (0, _AsyncUtils.loopAsync)(pathless.length, function (index, next, done) { getIndexRoute(pathless[index], location, paramNames, paramValues, function (error, indexRoute) { if (error || indexRoute) { var routes = [pathless[index]].concat(Array.isArray(indexRoute) ? indexRoute : [indexRoute]); done(error, routes); } else { next(); } }); }, function (err, routes) { callback(null, routes); }); }; var result = getChildRoutes(route, location, paramNames, paramValues, onChildRoutes); if (result) { onChildRoutes.apply(undefined, result); } } else { callback(); } } function assignParams(params, paramNames, paramValues) { return paramNames.reduce(function (params, paramName, index) { var paramValue = paramValues && paramValues[index]; if (Array.isArray(params[paramName])) { params[paramName].push(paramValue); } else if (paramName in params) { params[paramName] = [params[paramName], paramValue]; } else { params[paramName] = paramValue; } return params; }, params); } function createParams(paramNames, paramValues) { return assignParams({}, paramNames, paramValues); } function matchRouteDeep(route, location, remainingPathname, paramNames, paramValues, callback) { var pattern = route.path || ''; if (pattern.charAt(0) === '/') { remainingPathname = location.pathname; paramNames = []; paramValues = []; } // Only try to match the path if the route actually has a pattern, and if // we're not just searching for potential nested absolute paths. if (remainingPathname !== null && pattern) { try { var matched = (0, _PatternUtils.matchPattern)(pattern, remainingPathname); if (matched) { remainingPathname = matched.remainingPathname; paramNames = [].concat(paramNames, matched.paramNames); paramValues = [].concat(paramValues, matched.paramValues); } else { remainingPathname = null; } } catch (error) { callback(error); } // By assumption, pattern is non-empty here, which is the prerequisite for // actually terminating a match. if (remainingPathname === '') { var match = { routes: [route], params: createParams(paramNames, paramValues) }; getIndexRoute(route, location, paramNames, paramValues, function (error, indexRoute) { if (error) { callback(error); } else { if (Array.isArray(indexRoute)) { var _match$routes; true ? (0, _routerWarning2.default)(indexRoute.every(function (route) { return !route.path; }), 'Index routes should not have paths') : void 0; (_match$routes = match.routes).push.apply(_match$routes, indexRoute); } else if (indexRoute) { true ? (0, _routerWarning2.default)(!indexRoute.path, 'Index routes should not have paths') : void 0; match.routes.push(indexRoute); } callback(null, match); } }); return; } } if (remainingPathname != null || route.childRoutes) { // Either a) this route matched at least some of the path or b) // we don't have to load this route's children asynchronously. In // either case continue checking for matches in the subtree. var onChildRoutes = function onChildRoutes(error, childRoutes) { if (error) { callback(error); } else if (childRoutes) { // Check the child routes to see if any of them match. matchRoutes(childRoutes, location, function (error, match) { if (error) { callback(error); } else if (match) { // A child route matched! Augment the match and pass it up the stack. match.routes.unshift(route); callback(null, match); } else { callback(); } }, remainingPathname, paramNames, paramValues); } else { callback(); } }; var result = getChildRoutes(route, location, paramNames, paramValues, onChildRoutes); if (result) { onChildRoutes.apply(undefined, result); } } else { callback(); } } /** * Asynchronously matches the given location to a set of routes and calls * callback(error, state) when finished. The state object will have the * following properties: * * - routes An array of routes that matched, in hierarchical order * - params An object of URL parameters * * Note: This operation may finish synchronously if no routes have an * asynchronous getChildRoutes method. */ function matchRoutes(routes, location, callback, remainingPathname) { var paramNames = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var paramValues = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : []; if (remainingPathname === undefined) { // TODO: This is a little bit ugly, but it works around a quirk in history // that strips the leading slash from pathnames when using basenames with // trailing slashes. if (location.pathname.charAt(0) !== '/') { location = _extends({}, location, { pathname: '/' + location.pathname }); } remainingPathname = location.pathname; } (0, _AsyncUtils.loopAsync)(routes.length, function (index, next, done) { matchRouteDeep(routes[index], location, remainingPathname, paramNames, paramValues, function (error, match) { if (error || match) { done(error, match); } else { next(); } }); }, callback); } /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = withRouter; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(4); var _react2 = _interopRequireDefault(_react); var _createReactClass = __webpack_require__(3); var _createReactClass2 = _interopRequireDefault(_createReactClass); var _hoistNonReactStatics = __webpack_require__(63); var _hoistNonReactStatics2 = _interopRequireDefault(_hoistNonReactStatics); var _ContextUtils = __webpack_require__(15); var _PropTypes = __webpack_require__(16); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = (0, _createReactClass2.default)({ displayName: 'WithRouter', mixins: [(0, _ContextUtils.ContextSubscriber)('router')], contextTypes: { router: _PropTypes.routerShape }, propTypes: { router: _PropTypes.routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? true ? (0, _invariant2.default)(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : (0, _invariant2.default)(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; if (!router) { return _react2.default.createElement(WrappedComponent, this.props); } var params = router.params, location = router.location, routes = router.routes; var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return _react2.default.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return (0, _hoistNonReactStatics2.default)(WithRouter, WrappedComponent); } /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; var _assign = __webpack_require__(22); var emptyObject = __webpack_require__(54); var _invariant = __webpack_require__(55); if (true) { var warning = __webpack_require__(56); } var MIXINS_KEY = 'mixins'; // Helper function to allow the creation of anonymous functions which do not // have .name set to the name of the variable being assigned to. function identity(fn) { return fn; } var ReactPropTypeLocationNames; if (true) { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } else { ReactPropTypeLocationNames = {}; } function factory(ReactComponent, isValidElement, ReactNoopUpdateQueue) { /** * Policies that describe methods in `ReactClassInterface`. */ var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or host components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: 'DEFINE_MANY', /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: 'DEFINE_MANY', /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: 'DEFINE_MANY', /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: 'DEFINE_MANY', /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: 'DEFINE_MANY', // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: 'DEFINE_MANY_MERGED', /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: 'DEFINE_MANY_MERGED', /** * @return {object} * @optional */ getChildContext: 'DEFINE_MANY_MERGED', /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @required */ render: 'DEFINE_ONCE', // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: 'DEFINE_MANY', /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: 'DEFINE_MANY', /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: 'DEFINE_MANY', /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: 'DEFINE_ONCE', /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: 'DEFINE_MANY', /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: 'DEFINE_MANY', /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillMount`. * * @optional */ UNSAFE_componentWillMount: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillReceiveProps`. * * @optional */ UNSAFE_componentWillReceiveProps: 'DEFINE_MANY', /** * Replacement for (deprecated) `componentWillUpdate`. * * @optional */ UNSAFE_componentWillUpdate: 'DEFINE_MANY', // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: 'OVERRIDE_BASE' }; /** * Similar to ReactClassInterface but for static methods. */ var ReactClassStaticInterface = { /** * This method is invoked after a component is instantiated and when it * receives new props. Return an object to update state in response to * prop changes. Return null to indicate no change to state. * * If an object is returned, its keys will be merged into the existing state. * * @return {object || null} * @optional */ getDerivedStateFromProps: 'DEFINE_MANY_MERGED' }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function(Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function(Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function(Constructor, childContextTypes) { if (true) { validateTypeDef(Constructor, childContextTypes, 'childContext'); } Constructor.childContextTypes = _assign( {}, Constructor.childContextTypes, childContextTypes ); }, contextTypes: function(Constructor, contextTypes) { if (true) { validateTypeDef(Constructor, contextTypes, 'context'); } Constructor.contextTypes = _assign( {}, Constructor.contextTypes, contextTypes ); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function(Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction( Constructor.getDefaultProps, getDefaultProps ); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function(Constructor, propTypes) { if (true) { validateTypeDef(Constructor, propTypes, 'prop'); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function(Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function() {} }; function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an _invariant so components // don't show up in prod but only in __DEV__ if (true) { warning( typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName ); } } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { _invariant( specPolicy === 'OVERRIDE_BASE', 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name ); } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { _invariant( specPolicy === 'DEFINE_MANY' || specPolicy === 'DEFINE_MANY_MERGED', 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name ); } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { if (true) { var typeofSpec = typeof spec; var isMixinValid = typeofSpec === 'object' && spec !== null; if (true) { warning( isMixinValid, "%s: You're attempting to include a mixin that is either null " + 'or not an object. Check the mixins included by the component, ' + 'as well as any mixins they include themselves. ' + 'Expected object but got %s.', Constructor.displayName || 'ReactClass', spec === null ? null : typeofSpec ); } } return; } _invariant( typeof spec !== 'function', "ReactClass: You're attempting to " + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.' ); _invariant( !isValidElement(spec), "ReactClass: You're attempting to " + 'use a component as a mixin. Instead, just use a regular object.' ); var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. _invariant( isReactClassMethod && (specPolicy === 'DEFINE_MANY_MERGED' || specPolicy === 'DEFINE_MANY'), 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name ); // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === 'DEFINE_MANY_MERGED') { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === 'DEFINE_MANY') { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (true) { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; _invariant( !isReserved, 'ReactClass: You are attempting to define a reserved ' + 'property, `%s`, that shouldn\'t be on the "statics" key. Define it ' + 'as an instance property instead; it will still be accessible on the ' + 'constructor.', name ); var isAlreadyDefined = name in Constructor; if (isAlreadyDefined) { var specPolicy = ReactClassStaticInterface.hasOwnProperty(name) ? ReactClassStaticInterface[name] : null; _invariant( specPolicy === 'DEFINE_MANY_MERGED', 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name ); Constructor[name] = createMergedResultFunction(Constructor[name], property); return; } Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { _invariant( one && two && typeof one === 'object' && typeof two === 'object', 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.' ); for (var key in two) { if (two.hasOwnProperty(key)) { _invariant( one[key] === undefined, 'mergeIntoWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (true) { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function(newThis) { for ( var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++ ) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { if (true) { warning( false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName ); } } else if (!args.length) { if (true) { warning( false, 'bind(): You are binding a component method to the component. ' + 'React does this for you automatically in a high-performance ' + 'way, so you can safely remove this call. See %s', componentName ); } return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } var IsMountedPreMixin = { componentDidMount: function() { this.__isMounted = true; } }; var IsMountedPostMixin = { componentWillUnmount: function() { this.__isMounted = false; } }; /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function(newState, callback) { this.updater.enqueueReplaceState(this, newState, callback); }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function() { if (true) { warning( this.__didWarnIsMounted, '%s: isMounted is deprecated. Instead, make sure to clean up ' + 'subscriptions and pending requests in componentWillUnmount to ' + 'prevent memory leaks.', (this.constructor && this.constructor.displayName) || this.name || 'Component' ); this.__didWarnIsMounted = true; } return !!this.__isMounted; } }; var ReactClassComponent = function() {}; _assign( ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin ); /** * Creates a composite component class given a class specification. * See https://facebook.github.io/react/docs/top-level-api.html#react.createclass * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ function createClass(spec) { // To keep our warnings more understandable, we'll use a little hack here to // ensure that Constructor.name !== 'Constructor'. This makes sure we don't // unnecessarily identify a class without displayName as 'Constructor'. var Constructor = identity(function(props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (true) { warning( this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory' ); } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (true) { // We allow auto-mocks to proceed as if they're returning null. if ( initialState === undefined && this.getInitialState._isMockFunction ) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } _invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent' ); this.state = initialState; }); Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, IsMountedPreMixin); mixSpecIntoComponent(Constructor, spec); mixSpecIntoComponent(Constructor, IsMountedPostMixin); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (true) { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } _invariant( Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.' ); if (true) { warning( !Constructor.prototype.componentShouldUpdate, '%s has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.', spec.displayName || 'A component' ); warning( !Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component' ); warning( !Constructor.prototype.UNSAFE_componentWillRecieveProps, '%s has a method called UNSAFE_componentWillRecieveProps(). ' + 'Did you mean UNSAFE_componentWillReceiveProps()?', spec.displayName || 'A component' ); } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; } return createClass; } module.exports = factory; /***/ }), /* 53 */ /***/ (function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; var emptyObject = {}; if (true) { Object.freeze(emptyObject); } module.exports = emptyObject; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; if (true) { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } module.exports = invariant; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ 'use strict'; var emptyFunction = __webpack_require__(53); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (true) { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } module.exports = warning; /***/ }), /* 57 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; var loopAsync = exports.loopAsync = function loopAsync(turns, work, callback) { var currentTurn = 0, isDone = false; var isSync = false, hasNext = false, doneArgs = void 0; var done = function done() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } isDone = true; if (isSync) { // Iterate instead of recursing if possible. doneArgs = args; return; } callback.apply(undefined, args); }; var next = function next() { if (isDone) return; hasNext = true; if (isSync) return; // Iterate instead of recursing if possible. isSync = true; while (!isDone && currentTurn < turns && hasNext) { hasNext = false; work(currentTurn++, next, done); } isSync = false; if (isDone) { // This means the loop finished synchronously. callback.apply(undefined, doneArgs); return; } if (currentTurn >= turns && hasNext) { isDone = true; callback(); } }; next(); }; /***/ }), /* 58 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.replaceLocation = exports.pushLocation = exports.startListener = exports.getCurrentLocation = exports.go = exports.getUserConfirmation = undefined; var _BrowserProtocol = __webpack_require__(18); Object.defineProperty(exports, 'getUserConfirmation', { enumerable: true, get: function get() { return _BrowserProtocol.getUserConfirmation; } }); Object.defineProperty(exports, 'go', { enumerable: true, get: function get() { return _BrowserProtocol.go; } }); var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); var _LocationUtils = __webpack_require__(10); var _DOMUtils = __webpack_require__(13); var _DOMStateStorage = __webpack_require__(32); var _PathUtils = __webpack_require__(6); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var HashChangeEvent = 'hashchange'; var getHashPath = function getHashPath() { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! var href = window.location.href; var hashIndex = href.indexOf('#'); return hashIndex === -1 ? '' : href.substring(hashIndex + 1); }; var pushHashPath = function pushHashPath(path) { return window.location.hash = path; }; var replaceHashPath = function replaceHashPath(path) { var hashIndex = window.location.href.indexOf('#'); window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path); }; var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation(pathCoder, queryKey) { var path = pathCoder.decodePath(getHashPath()); var key = (0, _PathUtils.getQueryStringValueFromPath)(path, queryKey); var state = void 0; if (key) { path = (0, _PathUtils.stripQueryStringValueFromPath)(path, queryKey); state = (0, _DOMStateStorage.readState)(key); } var init = (0, _PathUtils.parsePath)(path); init.state = state; return (0, _LocationUtils.createLocation)(init, undefined, key); }; var prevLocation = void 0; var startListener = exports.startListener = function startListener(listener, pathCoder, queryKey) { var handleHashChange = function handleHashChange() { var path = getHashPath(); var encodedPath = pathCoder.encodePath(path); if (path !== encodedPath) { // Always be sure we have a properly-encoded hash. replaceHashPath(encodedPath); } else { var currentLocation = getCurrentLocation(pathCoder, queryKey); if (prevLocation && currentLocation.key && prevLocation.key === currentLocation.key) return; // Ignore extraneous hashchange events prevLocation = currentLocation; listener(currentLocation); } }; // Ensure the hash is encoded properly. var path = getHashPath(); var encodedPath = pathCoder.encodePath(path); if (path !== encodedPath) replaceHashPath(encodedPath); (0, _DOMUtils.addEventListener)(window, HashChangeEvent, handleHashChange); return function () { return (0, _DOMUtils.removeEventListener)(window, HashChangeEvent, handleHashChange); }; }; var updateLocation = function updateLocation(location, pathCoder, queryKey, updateHash) { var state = location.state, key = location.key; var path = pathCoder.encodePath((0, _PathUtils.createPath)(location)); if (state !== undefined) { path = (0, _PathUtils.addQueryStringValueToPath)(path, queryKey, key); (0, _DOMStateStorage.saveState)(key, state); } prevLocation = location; updateHash(path); }; var pushLocation = exports.pushLocation = function pushLocation(location, pathCoder, queryKey) { return updateLocation(location, pathCoder, queryKey, function (path) { if (getHashPath() !== path) { pushHashPath(path); } else { true ? (0, _warning2.default)(false, 'You cannot PUSH the same path using hash history') : void 0; } }); }; var replaceLocation = exports.replaceLocation = function replaceLocation(location, pathCoder, queryKey) { return updateLocation(location, pathCoder, queryKey, function (path) { if (getHashPath() !== path) replaceHashPath(path); }); }; /***/ }), /* 59 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.replaceLocation = exports.pushLocation = exports.getCurrentLocation = exports.go = exports.getUserConfirmation = undefined; var _BrowserProtocol = __webpack_require__(18); Object.defineProperty(exports, 'getUserConfirmation', { enumerable: true, get: function get() { return _BrowserProtocol.getUserConfirmation; } }); Object.defineProperty(exports, 'go', { enumerable: true, get: function get() { return _BrowserProtocol.go; } }); var _LocationUtils = __webpack_require__(10); var _PathUtils = __webpack_require__(6); var getCurrentLocation = exports.getCurrentLocation = function getCurrentLocation() { return (0, _LocationUtils.createLocation)(window.location); }; var pushLocation = exports.pushLocation = function pushLocation(location) { window.location.href = (0, _PathUtils.createPath)(location); return false; // Don't update location }; var replaceLocation = exports.replaceLocation = function replaceLocation(location) { window.location.replace((0, _PathUtils.createPath)(location)); return false; // Don't update location }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionEnvironment = __webpack_require__(19); var _BrowserProtocol = __webpack_require__(18); var BrowserProtocol = _interopRequireWildcard(_BrowserProtocol); var _RefreshProtocol = __webpack_require__(59); var RefreshProtocol = _interopRequireWildcard(_RefreshProtocol); var _DOMUtils = __webpack_require__(13); var _createHistory = __webpack_require__(20); var _createHistory2 = _interopRequireDefault(_createHistory); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Creates and returns a history object that uses HTML5's history API * (pushState, replaceState, and the popstate event) to manage history. * This is the recommended method of managing history in browsers because * it provides the cleanest URLs. * * Note: In browsers that do not support the HTML5 history API full * page reloads will be used to preserve clean URLs. You can force this * behavior using { forceRefresh: true } in options. */ var createBrowserHistory = function createBrowserHistory() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; !_ExecutionEnvironment.canUseDOM ? true ? (0, _invariant2.default)(false, 'Browser history needs a DOM') : (0, _invariant2.default)(false) : void 0; var useRefresh = options.forceRefresh || !(0, _DOMUtils.supportsHistory)(); var Protocol = useRefresh ? RefreshProtocol : BrowserProtocol; var getUserConfirmation = Protocol.getUserConfirmation, getCurrentLocation = Protocol.getCurrentLocation, pushLocation = Protocol.pushLocation, replaceLocation = Protocol.replaceLocation, go = Protocol.go; var history = (0, _createHistory2.default)(_extends({ getUserConfirmation: getUserConfirmation }, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: go })); var listenerCount = 0, stopListener = void 0; var startListener = function startListener(listener, before) { if (++listenerCount === 1) stopListener = BrowserProtocol.startListener(history.transitionTo); var unlisten = before ? history.listenBefore(listener) : history.listen(listener); return function () { unlisten(); if (--listenerCount === 0) stopListener(); }; }; var listenBefore = function listenBefore(listener) { return startListener(listener, true); }; var listen = function listen(listener) { return startListener(listener, false); }; return _extends({}, history, { listenBefore: listenBefore, listen: listen }); }; exports.default = createBrowserHistory; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _ExecutionEnvironment = __webpack_require__(19); var _DOMUtils = __webpack_require__(13); var _HashProtocol = __webpack_require__(58); var HashProtocol = _interopRequireWildcard(_HashProtocol); var _createHistory = __webpack_require__(20); var _createHistory2 = _interopRequireDefault(_createHistory); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DefaultQueryKey = '_k'; var addLeadingSlash = function addLeadingSlash(path) { return path.charAt(0) === '/' ? path : '/' + path; }; var HashPathCoders = { hashbang: { encodePath: function encodePath(path) { return path.charAt(0) === '!' ? path : '!' + path; }, decodePath: function decodePath(path) { return path.charAt(0) === '!' ? path.substring(1) : path; } }, noslash: { encodePath: function encodePath(path) { return path.charAt(0) === '/' ? path.substring(1) : path; }, decodePath: addLeadingSlash }, slash: { encodePath: addLeadingSlash, decodePath: addLeadingSlash } }; var createHashHistory = function createHashHistory() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; !_ExecutionEnvironment.canUseDOM ? true ? (0, _invariant2.default)(false, 'Hash history needs a DOM') : (0, _invariant2.default)(false) : void 0; var queryKey = options.queryKey, hashType = options.hashType; true ? (0, _warning2.default)(queryKey !== false, 'Using { queryKey: false } no longer works. Instead, just don\'t ' + 'use location state if you don\'t want a key in your URL query string') : void 0; if (typeof queryKey !== 'string') queryKey = DefaultQueryKey; if (hashType == null) hashType = 'slash'; if (!(hashType in HashPathCoders)) { true ? (0, _warning2.default)(false, 'Invalid hash type: %s', hashType) : void 0; hashType = 'slash'; } var pathCoder = HashPathCoders[hashType]; var getUserConfirmation = HashProtocol.getUserConfirmation; var getCurrentLocation = function getCurrentLocation() { return HashProtocol.getCurrentLocation(pathCoder, queryKey); }; var pushLocation = function pushLocation(location) { return HashProtocol.pushLocation(location, pathCoder, queryKey); }; var replaceLocation = function replaceLocation(location) { return HashProtocol.replaceLocation(location, pathCoder, queryKey); }; var history = (0, _createHistory2.default)(_extends({ getUserConfirmation: getUserConfirmation }, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: HashProtocol.go })); var listenerCount = 0, stopListener = void 0; var startListener = function startListener(listener, before) { if (++listenerCount === 1) stopListener = HashProtocol.startListener(history.transitionTo, pathCoder, queryKey); var unlisten = before ? history.listenBefore(listener) : history.listen(listener); return function () { unlisten(); if (--listenerCount === 0) stopListener(); }; }; var listenBefore = function listenBefore(listener) { return startListener(listener, true); }; var listen = function listen(listener) { return startListener(listener, false); }; var goIsSupportedWithoutReload = (0, _DOMUtils.supportsGoWithoutReloadUsingHash)(); var go = function go(n) { true ? (0, _warning2.default)(goIsSupportedWithoutReload, 'Hash history go(n) causes a full page reload in this browser') : void 0; history.go(n); }; var createHref = function createHref(path) { return '#' + pathCoder.encodePath(history.createHref(path)); }; return _extends({}, history, { listenBefore: listenBefore, listen: listen, go: go, createHref: createHref }); }; exports.default = createHashHistory; /***/ }), /* 62 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _warning = __webpack_require__(7); var _warning2 = _interopRequireDefault(_warning); var _invariant = __webpack_require__(1); var _invariant2 = _interopRequireDefault(_invariant); var _LocationUtils = __webpack_require__(10); var _PathUtils = __webpack_require__(6); var _createHistory = __webpack_require__(20); var _createHistory2 = _interopRequireDefault(_createHistory); var _Actions = __webpack_require__(12); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var createStateStorage = function createStateStorage(entries) { return entries.filter(function (entry) { return entry.state; }).reduce(function (memo, entry) { memo[entry.key] = entry.state; return memo; }, {}); }; var createMemoryHistory = function createMemoryHistory() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (Array.isArray(options)) { options = { entries: options }; } else if (typeof options === 'string') { options = { entries: [options] }; } var getCurrentLocation = function getCurrentLocation() { var entry = entries[current]; var path = (0, _PathUtils.createPath)(entry); var key = void 0, state = void 0; if (entry.key) { key = entry.key; state = readState(key); } var init = (0, _PathUtils.parsePath)(path); return (0, _LocationUtils.createLocation)(_extends({}, init, { state: state }), undefined, key); }; var canGo = function canGo(n) { var index = current + n; return index >= 0 && index < entries.length; }; var go = function go(n) { if (!n) return; if (!canGo(n)) { true ? (0, _warning2.default)(false, 'Cannot go(%s) there is not enough history', n) : void 0; return; } current += n; var currentLocation = getCurrentLocation(); // Change action to POP history.transitionTo(_extends({}, currentLocation, { action: _Actions.POP })); }; var pushLocation = function pushLocation(location) { current += 1; if (current < entries.length) entries.splice(current); entries.push(location); saveState(location.key, location.state); }; var replaceLocation = function replaceLocation(location) { entries[current] = location; saveState(location.key, location.state); }; var history = (0, _createHistory2.default)(_extends({}, options, { getCurrentLocation: getCurrentLocation, pushLocation: pushLocation, replaceLocation: replaceLocation, go: go })); var _options = options, entries = _options.entries, current = _options.current; if (typeof entries === 'string') { entries = [entries]; } else if (!Array.isArray(entries)) { entries = ['/']; } entries = entries.map(function (entry) { return (0, _LocationUtils.createLocation)(entry); }); if (current == null) { current = entries.length - 1; } else { !(current >= 0 && current < entries.length) ? true ? (0, _invariant2.default)(false, 'Current index must be >= 0 and < %s, was %s', entries.length, current) : (0, _invariant2.default)(false) : void 0; } var storage = createStateStorage(entries); var saveState = function saveState(key, state) { return storage[key] = state; }; var readState = function readState(key) { return storage[key]; }; return _extends({}, history, { canGo: canGo }); }; exports.default = createMemoryHistory; /***/ }), /* 63 */ /***/ (function(module, exports) { 'use strict'; /** * Copyright 2015, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDefaultProps: true, getDerivedStateFromProps: true, mixins: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var defineProperty = Object.defineProperty; var getOwnPropertyNames = Object.getOwnPropertyNames; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var getPrototypeOf = Object.getPrototypeOf; var objectPrototype = getPrototypeOf && getPrototypeOf(Object); function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components if (objectPrototype) { var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } } var keys = getOwnPropertyNames(sourceComponent); if (getOwnPropertySymbols) { keys = keys.concat(getOwnPropertySymbols(sourceComponent)); } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!REACT_STATICS[key] && !KNOWN_STATICS[key] && (!blacklist || !blacklist[key])) { var descriptor = getOwnPropertyDescriptor(sourceComponent, key); try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) {} } } return targetComponent; } return targetComponent; } module.exports = hoistNonReactStatics; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var printWarning = function() {}; if (true) { var ReactPropTypesSecret = __webpack_require__(35); var loggedTypeFailures = {}; var has = Function.call.bind(Object.prototype.hasOwnProperty); printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function() { if (true) { loggedTypeFailures = {}; } } module.exports = checkPropTypes; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var ReactIs = __webpack_require__(23); var assign = __webpack_require__(22); var ReactPropTypesSecret = __webpack_require__(35); var checkPropTypes = __webpack_require__(64); var has = Function.call.bind(Object.prototype.hasOwnProperty); var printWarning = function() {}; if (true) { printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } function emptyFunctionThatReturnsNull() { return null; } module.exports = function(isValidElement, throwOnDirectAccess) { /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; // Important! // Keep this list in sync with production version in `./factoryWithThrowingShims.js`. var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), symbol: createPrimitiveTypeChecker('symbol'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker, }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ /** * We use an Error-like object for backward compatibility as people may call * PropTypes directly and inspect their output. However, we don't use real * Errors anymore. We don't inspect their stack anyway, and creating them * is prohibitively expensive if they are created too often, such as what * happens in oneOfType() for any type before the one that matched. */ function PropTypeError(message) { this.message = message; this.stack = ''; } // Make `instanceof Error` still work for returned errors. PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate) { if (true) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { // New behavior only for users of `prop-types` package var err = new Error( 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use `PropTypes.checkPropTypes()` to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); err.name = 'Invariant Violation'; throw err; } else if (("development") !== 'production' && typeof console !== 'undefined') { // Old behavior for people using React.PropTypes var cacheKey = componentName + ':' + propName; if ( !manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3 ) { printWarning( 'You are manually calling a React.PropTypes validation ' + 'function for the `' + propFullName + '` prop on `' + componentName + '`. This is deprecated ' + 'and will throw in the standalone `prop-types` package. ' + 'You may be seeing this warning due to a third-party PropTypes ' + 'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.' ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.')); } return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createElementTypeTypeChecker() { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactIs.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement type.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { if (true) { if (arguments.length > 1) { printWarning( 'Invalid arguments supplied to oneOf, expected an array, got ' + arguments.length + ' arguments. ' + 'A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).' ); } else { printWarning('Invalid argument supplied to oneOf, expected an array.'); } } return emptyFunctionThatReturnsNull; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type = getPreciseType(value); if (type === 'symbol') { return String(value); } return value; }); return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + String(propValue) + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (has(propValue, key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? printWarning('Invalid argument supplied to oneOfType, expected an instance of array.') : void 0; return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== 'function') { printWarning( 'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' + 'received ' + getPostfixForTypeWarning(checker) + ' at index ' + i + '.' ); return emptyFunctionThatReturnsNull; } } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) { return null; } } return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createStrictShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } // We need to check all keys in case some are required but missing from // props. var allKeys = assign({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (!checker) { return new PropTypeError( 'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' + '\nBad object: ' + JSON.stringify(props[propName], null, ' ') + '\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ') ); } var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { // Native Symbol. if (propType === 'symbol') { return true; } // falsy value can't be a Symbol if (!propValue) { return false; } // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol' if (propValue['@@toStringTag'] === 'Symbol') { return true; } // Fallback for non-spec compliant Symbols which are polyfilled. if (typeof Symbol === 'function' && propValue instanceof Symbol) { return true; } return false; } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } if (isSymbol(propType, propValue)) { return 'symbol'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { if (typeof propValue === 'undefined' || propValue === null) { return '' + propValue; } var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns a string that is postfixed to a warning about an invalid type. // For example, "undefined" or "of type array" function getPostfixForTypeWarning(value) { var type = getPreciseType(value); switch (type) { case 'array': case 'object': return 'an ' + type; case 'boolean': case 'date': case 'regexp': return 'a ' + type; default: return type; } } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var strictUriEncode = __webpack_require__(68); var objectAssign = __webpack_require__(22); function encoderForArrayFormat(opts) { switch (opts.arrayFormat) { case 'index': return function (key, value, index) { return value === null ? [ encode(key, opts), '[', index, ']' ].join('') : [ encode(key, opts), '[', encode(index, opts), ']=', encode(value, opts) ].join(''); }; case 'bracket': return function (key, value) { return value === null ? encode(key, opts) : [ encode(key, opts), '[]=', encode(value, opts) ].join(''); }; default: return function (key, value) { return value === null ? encode(key, opts) : [ encode(key, opts), '=', encode(value, opts) ].join(''); }; } } function parserForArrayFormat(opts) { var result; switch (opts.arrayFormat) { case 'index': return function (key, value, accumulator) { result = /\[(\d*)\]$/.exec(key); key = key.replace(/\[\d*\]$/, ''); if (!result) { accumulator[key] = value; return; } if (accumulator[key] === undefined) { accumulator[key] = {}; } accumulator[key][result[1]] = value; }; case 'bracket': return function (key, value, accumulator) { result = /(\[\])$/.exec(key); key = key.replace(/\[\]$/, ''); if (!result) { accumulator[key] = value; return; } else if (accumulator[key] === undefined) { accumulator[key] = [value]; return; } accumulator[key] = [].concat(accumulator[key], value); }; default: return function (key, value, accumulator) { if (accumulator[key] === undefined) { accumulator[key] = value; return; } accumulator[key] = [].concat(accumulator[key], value); }; } } function encode(value, opts) { if (opts.encode) { return opts.strict ? strictUriEncode(value) : encodeURIComponent(value); } return value; } function keysSorter(input) { if (Array.isArray(input)) { return input.sort(); } else if (typeof input === 'object') { return keysSorter(Object.keys(input)).sort(function (a, b) { return Number(a) - Number(b); }).map(function (key) { return input[key]; }); } return input; } exports.extract = function (str) { return str.split('?')[1] || ''; }; exports.parse = function (str, opts) { opts = objectAssign({arrayFormat: 'none'}, opts); var formatter = parserForArrayFormat(opts); // Create an object with no prototype // https://github.com/sindresorhus/query-string/issues/47 var ret = Object.create(null); if (typeof str !== 'string') { return ret; } str = str.trim().replace(/^(\?|#|&)/, ''); if (!str) { return ret; } str.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); // Firefox (pre 40) decodes `%3D` to `=` // https://github.com/sindresorhus/query-string/pull/37 var key = parts.shift(); var val = parts.length > 0 ? parts.join('=') : undefined; // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); formatter(decodeURIComponent(key), val, ret); }); return Object.keys(ret).sort().reduce(function (result, key) { var val = ret[key]; if (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) { // Sort object keys, not values result[key] = keysSorter(val); } else { result[key] = val; } return result; }, Object.create(null)); }; exports.stringify = function (obj, opts) { var defaults = { encode: true, strict: true, arrayFormat: 'none' }; opts = objectAssign(defaults, opts); var formatter = encoderForArrayFormat(opts); return obj ? Object.keys(obj).sort().map(function (key) { var val = obj[key]; if (val === undefined) { return ''; } if (val === null) { return encode(key, opts); } if (Array.isArray(val)) { var result = []; val.slice().forEach(function (val2) { if (val2 === undefined) { return; } result.push(formatter(key, val2, result.length)); }); return result.join('&'); } return encode(key, opts) + '=' + encode(val, opts); }).filter(function (x) { return x.length > 0; }).join('&') : ''; }; /***/ }), /* 67 */ /***/ (function(module, exports, __webpack_require__) { /** @license React v16.8.6 * react-is.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; if (true) { (function() { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for('react.async_mode') : 0xeacf; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE); } /** * Forked from fbjs/warning: * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js * * Only change is we use console.warn instead of console.error, * and do nothing when 'console' is not supported. * This really simplifies the code. * --- * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var lowPriorityWarning = function () {}; { var printWarning = function (format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.warn(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; lowPriorityWarning = function (condition, format) { if (format === undefined) { throw new Error('`lowPriorityWarning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var lowPriorityWarning$1 = lowPriorityWarning; function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } // AsyncMode is deprecated along with isAsyncMode var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; // AsyncMode should be deprecated function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; lowPriorityWarning$1(false, 'The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 17+. Update your code to use ' + 'ReactIs.isConcurrentMode() instead. It has the exact same API.'); } } return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports.typeOf = typeOf; exports.AsyncMode = AsyncMode; exports.ConcurrentMode = ConcurrentMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode; exports.Suspense = Suspense; exports.isValidElementType = isValidElementType; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; })(); } /***/ }), /* 68 */ /***/ (function(module, exports) { 'use strict'; module.exports = function (str) { return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); }; /***/ }) /******/ ]) }); ;
{ "content_hash": "4b8c75994ed48f06e81757faf9da9982", "timestamp": "", "source": "github", "line_count": 7346, "max_line_length": 433, "avg_line_length": 31.418050639803976, "alnum_prop": 0.634423324393298, "repo_name": "sufuf3/cdnjs", "id": "4fc5df1a9fae2b432b195c7674d6ad5966b118b3", "size": "230797", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "ajax/libs/react-router/3.2.4/ReactRouter.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
A text-based ruby game simulating the process of running a retail clothing brand. The player will get to run through all five phases of retail: 1. Design 1. Manufacture 1. Shipment 1. Marketing 1. Sales
{ "content_hash": "cc9d65dd1d527a487c13564143938e73", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 81, "avg_line_length": 22.77777777777778, "alnum_prop": 0.7804878048780488, "repo_name": "KylaBendrik/Retail-Tycoon", "id": "f6b93141844f10a91f2b2d3b261170f86427359b", "size": "221", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "7711" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Qt 4.8: browserwidget.ui Example File (demos/sqlbrowser/browserwidget.ui)</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <h1 class="title">browserwidget.ui Example File</h1> <span class="small-subtitle">demos/sqlbrowser/browserwidget.ui</span> <!-- $$$demos/sqlbrowser/browserwidget.ui-description --> <div class="descr"> <a name="details"></a> <pre class="cpp"> &lt;ui version=&quot;4.0&quot; &gt; &lt;author&gt;&lt;/author&gt; &lt;comment&gt;&lt;/comment&gt; &lt;exportmacro&gt;&lt;/exportmacro&gt; &lt;class&gt;Browser&lt;/class&gt; &lt;widget class=&quot;QWidget&quot; name=&quot;Browser&quot; &gt; &lt;property name=&quot;geometry&quot; &gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;765&lt;/width&gt; &lt;height&gt;515&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name=&quot;windowTitle&quot; &gt; &lt;string&gt;Qt SQL Browser&lt;/string&gt; &lt;/property&gt; &lt;layout class=&quot;QVBoxLayout&quot; &gt; &lt;property name=&quot;margin&quot; &gt; &lt;number&gt;8&lt;/number&gt; &lt;/property&gt; &lt;property name=&quot;spacing&quot; &gt; &lt;number&gt;6&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;widget class=&quot;QSplitter&quot; name=&quot;splitter_2&quot; &gt; &lt;property name=&quot;sizePolicy&quot; &gt; &lt;sizepolicy&gt; &lt;hsizetype&gt;7&lt;/hsizetype&gt; &lt;vsizetype&gt;7&lt;/vsizetype&gt; &lt;horstretch&gt;0&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name=&quot;orientation&quot; &gt; &lt;enum&gt;Qt::Horizontal&lt;/enum&gt; &lt;/property&gt; &lt;widget class=&quot;ConnectionWidget&quot; name=&quot;connectionWidget&quot; &gt; &lt;property name=&quot;sizePolicy&quot; &gt; &lt;sizepolicy&gt; &lt;hsizetype&gt;13&lt;/hsizetype&gt; &lt;vsizetype&gt;7&lt;/vsizetype&gt; &lt;horstretch&gt;1&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;/widget&gt; &lt;widget class=&quot;QTableView&quot; name=&quot;table&quot; &gt; &lt;property name=&quot;sizePolicy&quot; &gt; &lt;sizepolicy&gt; &lt;hsizetype&gt;7&lt;/hsizetype&gt; &lt;vsizetype&gt;7&lt;/vsizetype&gt; &lt;horstretch&gt;2&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name=&quot;contextMenuPolicy&quot; &gt; &lt;enum&gt;Qt::ActionsContextMenu&lt;/enum&gt; &lt;/property&gt; &lt;property name=&quot;selectionBehavior&quot; &gt; &lt;enum&gt;QAbstractItemView::SelectRows&lt;/enum&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class=&quot;QGroupBox&quot; name=&quot;groupBox&quot; &gt; &lt;property name=&quot;sizePolicy&quot; &gt; &lt;sizepolicy&gt; &lt;hsizetype&gt;5&lt;/hsizetype&gt; &lt;vsizetype&gt;3&lt;/vsizetype&gt; &lt;horstretch&gt;0&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name=&quot;maximumSize&quot; &gt; &lt;size&gt; &lt;width&gt;16777215&lt;/width&gt; &lt;height&gt;180&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;property name=&quot;title&quot; &gt; &lt;string&gt;SQL Query&lt;/string&gt; &lt;/property&gt; &lt;layout class=&quot;QVBoxLayout&quot; &gt; &lt;property name=&quot;margin&quot; &gt; &lt;number&gt;9&lt;/number&gt; &lt;/property&gt; &lt;property name=&quot;spacing&quot; &gt; &lt;number&gt;6&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;widget class=&quot;QTextEdit&quot; name=&quot;sqlEdit&quot; &gt; &lt;property name=&quot;sizePolicy&quot; &gt; &lt;sizepolicy&gt; &lt;hsizetype&gt;7&lt;/hsizetype&gt; &lt;vsizetype&gt;3&lt;/vsizetype&gt; &lt;horstretch&gt;0&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name=&quot;minimumSize&quot; &gt; &lt;size&gt; &lt;width&gt;0&lt;/width&gt; &lt;height&gt;18&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;property name=&quot;baseSize&quot; &gt; &lt;size&gt; &lt;width&gt;0&lt;/width&gt; &lt;height&gt;120&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item&gt; &lt;layout class=&quot;QHBoxLayout&quot; &gt; &lt;property name=&quot;margin&quot; &gt; &lt;number&gt;1&lt;/number&gt; &lt;/property&gt; &lt;property name=&quot;spacing&quot; &gt; &lt;number&gt;6&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;spacer&gt; &lt;property name=&quot;orientation&quot; &gt; &lt;enum&gt;Qt::Horizontal&lt;/enum&gt; &lt;/property&gt; &lt;property name=&quot;sizeHint&quot; &gt; &lt;size&gt; &lt;width&gt;40&lt;/width&gt; &lt;height&gt;20&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;/spacer&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;clearButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;&amp;amp;Clear&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class=&quot;QPushButton&quot; name=&quot;submitButton&quot; &gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;&amp;amp;Submit&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;action name=&quot;insertRowAction&quot; &gt; &lt;property name=&quot;enabled&quot; &gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;&amp;amp;Insert Row&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot; &gt; &lt;string&gt;Inserts a new Row&lt;/string&gt; &lt;/property&gt; &lt;/action&gt; &lt;action name=&quot;deleteRowAction&quot; &gt; &lt;property name=&quot;enabled&quot; &gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name=&quot;text&quot; &gt; &lt;string&gt;&amp;amp;Delete Row&lt;/string&gt; &lt;/property&gt; &lt;property name=&quot;statusTip&quot; &gt; &lt;string&gt;Deletes the current Row&lt;/string&gt; &lt;/property&gt; &lt;/action&gt; &lt;/widget&gt; &lt;pixmapfunction&gt;&lt;/pixmapfunction&gt; &lt;customwidgets&gt; &lt;customwidget&gt; &lt;class&gt;ConnectionWidget&lt;/class&gt; &lt;extends&gt;QTreeView&lt;/extends&gt; &lt;header&gt;connectionwidget.h&lt;/header&gt; &lt;container&gt;0&lt;/container&gt; &lt;pixmap&gt;&lt;/pixmap&gt; &lt;/customwidget&gt; &lt;/customwidgets&gt; &lt;tabstops&gt; &lt;tabstop&gt;sqlEdit&lt;/tabstop&gt; &lt;tabstop&gt;clearButton&lt;/tabstop&gt; &lt;tabstop&gt;submitButton&lt;/tabstop&gt; &lt;tabstop&gt;connectionWidget&lt;/tabstop&gt; &lt;tabstop&gt;table&lt;/tabstop&gt; &lt;/tabstops&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt;</pre> </div> <!-- @@@demos/sqlbrowser/browserwidget.ui --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2013 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
{ "content_hash": "a8dab44d40eea9fbfab54b1a6acf7955", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 221, "avg_line_length": 41.86533665835412, "alnum_prop": 0.568858708601382, "repo_name": "stephaneAG/PengPod700", "id": "747a2777a30b8799bf5979356dad63246f2321dd", "size": "16788", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "QtEsrc/qt-everywhere-opensource-src-4.8.5/doc/html/demos-sqlbrowser-browserwidget-ui.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "167426" }, { "name": "Batchfile", "bytes": "25368" }, { "name": "C", "bytes": "3755463" }, { "name": "C#", "bytes": "9282" }, { "name": "C++", "bytes": "177871700" }, { "name": "CSS", "bytes": "600936" }, { "name": "GAP", "bytes": "758872" }, { "name": "GLSL", "bytes": "32226" }, { "name": "Groff", "bytes": "106542" }, { "name": "HTML", "bytes": "273585110" }, { "name": "IDL", "bytes": "1194" }, { "name": "JavaScript", "bytes": "435912" }, { "name": "Makefile", "bytes": "289373" }, { "name": "Objective-C", "bytes": "1898658" }, { "name": "Objective-C++", "bytes": "3222428" }, { "name": "PHP", "bytes": "6074" }, { "name": "Perl", "bytes": "291672" }, { "name": "Prolog", "bytes": "102468" }, { "name": "Python", "bytes": "22546" }, { "name": "QML", "bytes": "3580408" }, { "name": "QMake", "bytes": "2191574" }, { "name": "Scilab", "bytes": "2390" }, { "name": "Shell", "bytes": "116533" }, { "name": "TypeScript", "bytes": "42452" }, { "name": "Visual Basic", "bytes": "8370" }, { "name": "XQuery", "bytes": "25094" }, { "name": "XSLT", "bytes": "252382" } ], "symlink_target": "" }
package main import ( "bufio" "os/exec" "strings" "testing" "time" "github.com/docker/docker/pkg/stringid" "github.com/kr/pty" ) // #9860 func TestAttachClosedOnContainerStop(t *testing.T) { defer deleteAllContainers() cmd := exec.Command(dockerBinary, "run", "-dti", "busybox", "sleep", "2") out, _, err := runCommandWithOutput(cmd) if err != nil { t.Fatalf("failed to start container: %v (%v)", out, err) } id := strings.TrimSpace(out) if err := waitRun(id); err != nil { t.Fatal(err) } done := make(chan struct{}) go func() { defer close(done) _, tty, err := pty.Open() if err != nil { t.Fatalf("could not open pty: %v", err) } attachCmd := exec.Command(dockerBinary, "attach", id) attachCmd.Stdin = tty attachCmd.Stdout = tty attachCmd.Stderr = tty if err := attachCmd.Run(); err != nil { t.Fatalf("attach returned error %s", err) } }() waitCmd := exec.Command(dockerBinary, "wait", id) if out, _, err = runCommandWithOutput(waitCmd); err != nil { t.Fatalf("error thrown while waiting for container: %s, %v", out, err) } select { case <-done: case <-time.After(attachWait): t.Fatal("timed out without attach returning") } logDone("attach - return after container finished") } func TestAttachAfterDetach(t *testing.T) { defer deleteAllContainers() name := "detachtest" cpty, tty, err := pty.Open() if err != nil { t.Fatalf("Could not open pty: %v", err) } cmd := exec.Command(dockerBinary, "run", "-ti", "--name", name, "busybox") cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty detached := make(chan struct{}) go func() { if err := cmd.Run(); err != nil { t.Fatalf("attach returned error %s", err) } close(detached) }() time.Sleep(500 * time.Millisecond) if err := waitRun(name); err != nil { t.Fatal(err) } cpty.Write([]byte{16}) time.Sleep(100 * time.Millisecond) cpty.Write([]byte{17}) <-detached cpty, tty, err = pty.Open() if err != nil { t.Fatalf("Could not open pty: %v", err) } cmd = exec.Command(dockerBinary, "attach", name) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty if err := cmd.Start(); err != nil { t.Fatal(err) } bytes := make([]byte, 10) var nBytes int readErr := make(chan error, 1) go func() { time.Sleep(500 * time.Millisecond) cpty.Write([]byte("\n")) time.Sleep(500 * time.Millisecond) nBytes, err = cpty.Read(bytes) cpty.Close() readErr <- err }() select { case err := <-readErr: if err != nil { t.Fatal(err) } case <-time.After(2 * time.Second): t.Fatal("timeout waiting for attach read") } if err := cmd.Wait(); err != nil { t.Fatal(err) } if !strings.Contains(string(bytes[:nBytes]), "/ #") { t.Fatalf("failed to get a new prompt. got %s", string(bytes[:nBytes])) } logDone("attach - reconnect after detaching") } // TestAttachDetach checks that attach in tty mode can be detached using the long container ID func TestAttachDetach(t *testing.T) { out, _, _ := dockerCmd(t, "run", "-itd", "busybox", "cat") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { t.Fatal(err) } cpty, tty, err := pty.Open() if err != nil { t.Fatal(err) } defer cpty.Close() cmd := exec.Command(dockerBinary, "attach", id) cmd.Stdin = tty stdout, err := cmd.StdoutPipe() if err != nil { t.Fatal(err) } defer stdout.Close() if err := cmd.Start(); err != nil { t.Fatal(err) } if err := waitRun(id); err != nil { t.Fatalf("error waiting for container to start: %v", err) } if _, err := cpty.Write([]byte("hello\n")); err != nil { t.Fatal(err) } out, err = bufio.NewReader(stdout).ReadString('\n') if err != nil { t.Fatal(err) } if strings.TrimSpace(out) != "hello" { t.Fatalf("exepected 'hello', got %q", out) } // escape sequence if _, err := cpty.Write([]byte{16}); err != nil { t.Fatal(err) } time.Sleep(100 * time.Millisecond) if _, err := cpty.Write([]byte{17}); err != nil { t.Fatal(err) } ch := make(chan struct{}) go func() { cmd.Wait() ch <- struct{}{} }() running, err := inspectField(id, "State.Running") if err != nil { t.Fatal(err) } if running != "true" { t.Fatal("exepected container to still be running") } go func() { dockerCmd(t, "kill", id) }() select { case <-ch: case <-time.After(10 * time.Millisecond): t.Fatal("timed out waiting for container to exit") } logDone("attach - detach") } // TestAttachDetachTruncatedID checks that attach in tty mode can be detached func TestAttachDetachTruncatedID(t *testing.T) { out, _, _ := dockerCmd(t, "run", "-itd", "busybox", "cat") id := stringid.TruncateID(strings.TrimSpace(out)) if err := waitRun(id); err != nil { t.Fatal(err) } cpty, tty, err := pty.Open() if err != nil { t.Fatal(err) } defer cpty.Close() cmd := exec.Command(dockerBinary, "attach", id) cmd.Stdin = tty stdout, err := cmd.StdoutPipe() if err != nil { t.Fatal(err) } defer stdout.Close() if err := cmd.Start(); err != nil { t.Fatal(err) } if _, err := cpty.Write([]byte("hello\n")); err != nil { t.Fatal(err) } out, err = bufio.NewReader(stdout).ReadString('\n') if err != nil { t.Fatal(err) } if strings.TrimSpace(out) != "hello" { t.Fatalf("exepected 'hello', got %q", out) } // escape sequence if _, err := cpty.Write([]byte{16}); err != nil { t.Fatal(err) } time.Sleep(100 * time.Millisecond) if _, err := cpty.Write([]byte{17}); err != nil { t.Fatal(err) } ch := make(chan struct{}) go func() { cmd.Wait() ch <- struct{}{} }() running, err := inspectField(id, "State.Running") if err != nil { t.Fatal(err) } if running != "true" { t.Fatal("exepected container to still be running") } go func() { dockerCmd(t, "kill", id) }() select { case <-ch: case <-time.After(10 * time.Millisecond): t.Fatal("timed out waiting for container to exit") } logDone("attach - detach truncated ID") }
{ "content_hash": "dd44cdb0c10fedb53b81fdbb0bf7f474", "timestamp": "", "source": "github", "line_count": 286, "max_line_length": 94, "avg_line_length": 20.594405594405593, "alnum_prop": 0.6164685908319185, "repo_name": "bleuchtang/docker", "id": "ebc3804e3e8a71c11f466f4aaadd09c37688d23d", "size": "5910", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "integration-cli/docker_cli_attach_unix_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2485864" }, { "name": "Makefile", "bytes": "4547" }, { "name": "Perl", "bytes": "2199" }, { "name": "Shell", "bytes": "184676" }, { "name": "VimL", "bytes": "683" } ], "symlink_target": "" }
<!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_05) on Wed Oct 29 15:05:24 CET 2014 --> <title>ModuleController</title> <meta name="date" content="2014-10-29"> <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="ModuleController"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9,"i2":9,"i3":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="class-use/ModuleController.html">Use</a></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><a href="../controller/FileMonitorTest.html" title="class in controller"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../controller/ProfileController.html" title="class in controller"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?controller/ModuleController.html" target="_top">Frames</a></li> <li><a href="ModuleController.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">controller</div> <h2 title="Class ModuleController" class="title">Class ModuleController</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>controller.ModuleController</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">ModuleController</span> extends java.lang.Object</pre> <div class="block">Manages the extraction modules and provides a set of generic modules to instantiate new <a href="../modules/AbstractModule.html" title="class in modules"><code>AbstractModule</code></a>s.</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>static java.util.HashMap&lt;java.lang.String,<a href="../model/GenericModule.html" title="class in model">GenericModule</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../controller/ModuleController.html#genericModules">genericModules</a></span></code> <div class="block">HashMap of all available <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s.</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="../controller/ModuleController.html#ModuleController--">ModuleController</a></span>()</code> <div class="block">Constructor will initialize the set of available <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s.</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="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>static <a href="../model/GenericModule.html" title="class in model">GenericModule</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../controller/ModuleController.html#getGenericModule-java.lang.String-">getGenericModule</a></span>(java.lang.String&nbsp;moduleName)</code> <div class="block">Returns a <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a> with a specific name.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static java.util.Collection&lt;<a href="../model/GenericModule.html" title="class in model">GenericModule</a>&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../controller/ModuleController.html#getGenericModuleSet--">getGenericModuleSet</a></span>()</code> <div class="block">Returns a collection of all available <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>static <a href="../modules/AbstractModule.html" title="class in modules">AbstractModule</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../controller/ModuleController.html#getModuleInstance-java.lang.Class-">getModuleInstance</a></span>(java.lang.Class&lt;? extends <a href="../modules/AbstractModule.html" title="class in modules">AbstractModule</a>&gt;&nbsp;moduleClass)</code> <div class="block">Creates an <a href="../modules/AbstractModule.html" title="class in modules"><code>AbstractModule</code></a> instance from a class.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>static <a href="../modules/AbstractModule.html" title="class in modules">AbstractModule</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../controller/ModuleController.html#loadModule-java.lang.String-">loadModule</a></span>(java.lang.String&nbsp;moduleName)</code> <div class="block">Returns a newly created <a href="../modules/AbstractModule.html" title="class in modules"><code>AbstractModule</code></a> instance.</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="genericModules"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>genericModules</h4> <pre>public static&nbsp;java.util.HashMap&lt;java.lang.String,<a href="../model/GenericModule.html" title="class in model">GenericModule</a>&gt; genericModules</pre> <div class="block">HashMap of all available <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s. The hash String is the module name</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ModuleController--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ModuleController</h4> <pre>public&nbsp;ModuleController()</pre> <div class="block">Constructor will initialize the set of available <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s.</div> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getModuleInstance-java.lang.Class-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getModuleInstance</h4> <pre>public static&nbsp;<a href="../modules/AbstractModule.html" title="class in modules">AbstractModule</a>&nbsp;getModuleInstance(java.lang.Class&lt;? extends <a href="../modules/AbstractModule.html" title="class in modules">AbstractModule</a>&gt;&nbsp;moduleClass)</pre> <div class="block">Creates an <a href="../modules/AbstractModule.html" title="class in modules"><code>AbstractModule</code></a> instance from a class.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>moduleClass</code> - </dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>created AbstractModule instance</dd> </dl> </li> </ul> <a name="loadModule-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>loadModule</h4> <pre>public static&nbsp;<a href="../modules/AbstractModule.html" title="class in modules">AbstractModule</a>&nbsp;loadModule(java.lang.String&nbsp;moduleName)</pre> <div class="block">Returns a newly created <a href="../modules/AbstractModule.html" title="class in modules"><code>AbstractModule</code></a> instance. Looks up at the set of <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s to find the right class to be instantiated, based on the module name.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>moduleName</code> - </dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>instance of AbstractModule</dd> </dl> </li> </ul> <a name="getGenericModule-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getGenericModule</h4> <pre>public static&nbsp;<a href="../model/GenericModule.html" title="class in model">GenericModule</a>&nbsp;getGenericModule(java.lang.String&nbsp;moduleName)</pre> <div class="block">Returns a <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a> with a specific name.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>moduleName</code> - the name of the GenericModule</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the GenericModule</dd> </dl> </li> </ul> <a name="getGenericModuleSet--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getGenericModuleSet</h4> <pre>public static&nbsp;java.util.Collection&lt;<a href="../model/GenericModule.html" title="class in model">GenericModule</a>&gt;&nbsp;getGenericModuleSet()</pre> <div class="block">Returns a collection of all available <a href="../model/GenericModule.html" title="class in model"><code>GenericModule</code></a>s.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>GenericModule collection</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="class-use/ModuleController.html">Use</a></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><a href="../controller/FileMonitorTest.html" title="class in controller"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../controller/ProfileController.html" title="class in controller"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../index.html?controller/ModuleController.html" target="_top">Frames</a></li> <li><a href="ModuleController.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>
{ "content_hash": "9876620b7efcbc79fbc1185230c2b0e1", "timestamp": "", "source": "github", "line_count": 391, "max_line_length": 389, "avg_line_length": 40.34271099744245, "alnum_prop": 0.6723722581463167, "repo_name": "pericles-project/pet", "id": "2f671936f99066772c8b814fb877be3e50bad4db", "size": "15774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gh-pages/javadoc/controller/ModuleController.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4363" }, { "name": "HTML", "bytes": "10026" }, { "name": "Java", "bytes": "947953" }, { "name": "JavaScript", "bytes": "218253" }, { "name": "Perl", "bytes": "10698669" } ], "symlink_target": "" }
package com.google.cloud.storage.contrib.nio; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.storage.contrib.nio.testing.LocalStorageHelper; import com.google.common.collect.Iterables; import com.google.common.testing.EqualsTester; import com.google.common.testing.NullPointerTester; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.IOException; import java.net.URI; import java.net.URLDecoder; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.ProviderMismatchException; /** * Unit tests for {@link CloudStoragePath}. */ @RunWith(JUnit4.class) public class CloudStoragePathTest { @Rule public final ExpectedException thrown = ExpectedException.none(); @Before public void before() { CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); } @Test public void testCreate_neverRemoveExtraSlashes() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("lol//cat").toString()).isEqualTo("lol//cat"); assertThat((Object) fs.getPath("lol//cat")).isEqualTo(fs.getPath("lol//cat")); } } @Test public void testCreate_preservesTrailingSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("lol/cat/").toString()).isEqualTo("lol/cat/"); assertThat((Object) fs.getPath("lol/cat/")).isEqualTo(fs.getPath("lol/cat/")); } } @Test public void testGetGcsFilename_empty_notAllowed() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); fs.getPath("").getBlobId(); } } @Test public void testGetGcsFilename_stripsPrefixSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi").getBlobId().getName()).isEqualTo("hi"); } } @Test public void testGetGcsFilename_overrideStripPrefixSlash_doesntStripPrefixSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", stripPrefixSlash(false))) { assertThat(fs.getPath("/hi").getBlobId().getName()).isEqualTo("/hi"); } } @Test public void testGetGcsFilename_extraSlashes_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); fs.getPath("a//b").getBlobId().getName(); } } @Test public void testGetGcsFilename_overridepermitEmptyPathComponents() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", permitEmptyPathComponents(true))) { assertThat(fs.getPath("a//b").getBlobId().getName()).isEqualTo("a//b"); } } @Test public void testGetGcsFilename_freaksOutOnExtraSlashesAndDotDirs() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); fs.getPath("a//b/..").getBlobId().getName(); } } @Test public void testNameCount() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("").getNameCount()).isEqualTo(1); assertThat(fs.getPath("/").getNameCount()).isEqualTo(0); assertThat(fs.getPath("/hi/").getNameCount()).isEqualTo(1); assertThat(fs.getPath("/hi/yo").getNameCount()).isEqualTo(2); assertThat(fs.getPath("hi/yo").getNameCount()).isEqualTo(2); } } @Test public void testGetName() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("").getName(0).toString()).isEqualTo(""); assertThat(fs.getPath("/hi").getName(0).toString()).isEqualTo("hi"); assertThat(fs.getPath("hi/there").getName(1).toString()).isEqualTo("there"); } } @Test public void testGetName_negative_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); fs.getPath("angel").getName(-1); } } @Test public void testGetName_overflow_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); fs.getPath("angel").getName(1); } } @Test public void testIterator() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(Iterables.get(fs.getPath("/dog/mog"), 0).toString()).isEqualTo("dog"); assertThat(Iterables.get(fs.getPath("/dog/mog"), 1).toString()).isEqualTo("mog"); assertThat(Iterables.size(fs.getPath("/"))).isEqualTo(0); assertThat(Iterables.size(fs.getPath(""))).isEqualTo(1); assertThat(Iterables.get(fs.getPath(""), 0).toString()).isEqualTo(""); } } @Test public void testNormalize() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/").normalize().toString()).isEqualTo("/"); assertThat(fs.getPath("a/x/../b/x/..").normalize().toString()).isEqualTo("a/b/"); assertThat(fs.getPath("/x/x/../../♡").normalize().toString()).isEqualTo("/♡"); assertThat(fs.getPath("/x/x/./.././.././♡").normalize().toString()).isEqualTo("/♡"); } } @Test public void testNormalize_dot_becomesBlank() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("").normalize().toString()).isEqualTo(""); assertThat(fs.getPath(".").normalize().toString()).isEqualTo(""); } } @Test public void testNormalize_trailingSlash_isPreserved() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("o/").normalize().toString()).isEqualTo("o/"); } } @Test public void testNormalize_doubleDot_becomesBlank() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("..").normalize().toString()).isEqualTo(""); assertThat(fs.getPath("../..").normalize().toString()).isEqualTo(""); } } @Test public void testNormalize_extraSlashes_getRemoved() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("//life///b/good//").normalize().toString()).isEqualTo("/life/b/good/"); } } @Test public void testToRealPath_hasDotDir_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { fs.getPath("a/hi./b").toRealPath(); fs.getPath("a/.hi/b").toRealPath(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("dot-dir"); fs.getPath("a/./b").toRealPath(); } } @Test public void testToRealPath_hasDotDotDir_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { fs.getPath("a/hi../b").toRealPath(); fs.getPath("a/..hi/b").toRealPath(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("dot-dir"); fs.getPath("a/../b").toRealPath(); } } @Test public void testToRealPath_extraSlashes_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("extra slashes"); fs.getPath("a//b").toRealPath(); } } @Test public void testToRealPath_overridePermitEmptyPathComponents_extraSlashes_slashesRemain() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", permitEmptyPathComponents(true))) { assertThat(fs.getPath("/life///b/./good/").toRealPath().toString()) .isEqualTo("life///b/./good/"); } } @Test public void testToRealPath_permitEmptyPathComponents_doesNotNormalize() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", permitEmptyPathComponents(true))) { assertThat(fs.getPath("a").toRealPath().toString()).isEqualTo("a"); assertThat(fs.getPath("a//b").toRealPath().toString()).isEqualTo("a//b"); assertThat(fs.getPath("a//./b//..").toRealPath().toString()).isEqualTo("a//./b//.."); } } @Test public void testToRealPath_withWorkingDirectory_makesAbsolute() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", workingDirectory("/lol"))) { assertThat(fs.getPath("a").toRealPath().toString()).isEqualTo("lol/a"); } } @Test public void testToRealPath_disableStripPrefixSlash_makesPathAbsolute() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", stripPrefixSlash(false))) { assertThat(fs.getPath("a").toRealPath().toString()).isEqualTo("/a"); assertThat(fs.getPath("/a").toRealPath().toString()).isEqualTo("/a"); } } @Test public void testToRealPath_trailingSlash_getsPreserved() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("a/b/").toRealPath().toString()).isEqualTo("a/b/"); } } @Test public void testNormalize_empty_returnsEmpty() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("").normalize().toString()).isEqualTo(""); } } @Test public void testNormalize_preserveTrailingSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("a/b/../c/").normalize().toString()).isEqualTo("a/c/"); assertThat(fs.getPath("a/b/./c/").normalize().toString()).isEqualTo("a/b/c/"); } } @Test public void testGetParent_preserveTrailingSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("a/b/c").getParent().toString()).isEqualTo("a/b/"); assertThat(fs.getPath("a/b/c/").getParent().toString()).isEqualTo("a/b/"); assertThat((Object) fs.getPath("").getParent()).isNull(); assertThat((Object) fs.getPath("/").getParent()).isNull(); assertThat((Object) fs.getPath("aaa").getParent()).isNull(); assertThat((Object) (fs.getPath("aaa/").getParent())).isNull(); } } @Test public void testGetRoot() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hello").getRoot().toString()).isEqualTo("/"); assertThat((Object) fs.getPath("hello").getRoot()).isNull(); } } @Test public void testRelativize() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat( fs.getPath("/foo/bar/lol/cat").relativize(fs.getPath("/foo/a/b/../../c")).toString()) .isEqualTo("../../../a/b/../../c"); } } @Test public void testRelativize_providerMismatch() throws IOException { try (CloudStorageFileSystem gcs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(ProviderMismatchException.class); gcs.getPath("/etc").relativize(FileSystems.getDefault().getPath("/dog")); } } @Test @SuppressWarnings("ReturnValueIgnored") // testing that an Exception is thrown public void testRelativize_providerMismatch2() throws IOException { try (CloudStorageFileSystem gcs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(ProviderMismatchException.class); gcs.getPath("/dog").relativize(FileSystems.getDefault().getPath("/etc")); } } @Test public void testResolve() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi").resolve("there").toString()).isEqualTo("/hi/there"); assertThat(fs.getPath("hi").resolve("there").toString()).isEqualTo("hi/there"); } } @Test public void testResolve_providerMismatch() throws IOException { try (CloudStorageFileSystem gcs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(ProviderMismatchException.class); gcs.getPath("etc").resolve(FileSystems.getDefault().getPath("/dog")); } } @Test public void testIsAbsolute() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi").isAbsolute()).isTrue(); assertThat(fs.getPath("hi").isAbsolute()).isFalse(); } } @Test public void testToAbsolutePath() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat((Object) fs.getPath("/hi").toAbsolutePath()).isEqualTo(fs.getPath("/hi")); assertThat((Object) fs.getPath("hi").toAbsolutePath()).isEqualTo(fs.getPath("/hi")); } } @Test public void testToAbsolutePath_withWorkingDirectory() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", workingDirectory("/lol"))) { assertThat(fs.getPath("a").toAbsolutePath().toString()).isEqualTo("/lol/a"); } } @Test public void testGetFileName() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi/there").getFileName().toString()).isEqualTo("there"); assertThat(fs.getPath("military/fashion/show").getFileName().toString()).isEqualTo("show"); } } @Test public void testCompareTo() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi/there").compareTo(fs.getPath("/hi/there"))).isEqualTo(0); assertThat(fs.getPath("/hi/there").compareTo(fs.getPath("/hi/therf"))).isEqualTo(-1); assertThat(fs.getPath("/hi/there").compareTo(fs.getPath("/hi/therd"))).isEqualTo(1); } } @Test public void testStartsWith() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi/there").startsWith(fs.getPath("/hi/there"))).isTrue(); assertThat(fs.getPath("/hi/there").startsWith(fs.getPath("/hi/therf"))).isFalse(); assertThat(fs.getPath("/hi/there").startsWith(fs.getPath("/hi"))).isTrue(); assertThat(fs.getPath("/hi/there").startsWith(fs.getPath("/hi/"))).isTrue(); assertThat(fs.getPath("/hi/there").startsWith(fs.getPath("hi"))).isFalse(); assertThat(fs.getPath("/hi/there").startsWith(fs.getPath("/"))).isTrue(); assertThat(fs.getPath("/hi/there").startsWith(fs.getPath(""))).isFalse(); } } @Test public void testEndsWith() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { assertThat(fs.getPath("/hi/there").endsWith(fs.getPath("there"))).isTrue(); assertThat(fs.getPath("/hi/there").endsWith(fs.getPath("therf"))).isFalse(); assertThat(fs.getPath("/hi/there").endsWith(fs.getPath("/blag/therf"))).isFalse(); assertThat(fs.getPath("/hi/there").endsWith(fs.getPath("/hi/there"))).isTrue(); assertThat(fs.getPath("/hi/there").endsWith(fs.getPath("/there"))).isFalse(); assertThat(fs.getPath("/human/that/you/cry").endsWith(fs.getPath("that/you/cry"))).isTrue(); assertThat(fs.getPath("/human/that/you/cry").endsWith(fs.getPath("that/you/cry/"))).isTrue(); assertThat(fs.getPath("/hi/there/").endsWith(fs.getPath("/"))).isFalse(); assertThat(fs.getPath("/hi/there").endsWith(fs.getPath(""))).isFalse(); assertThat(fs.getPath("").endsWith(fs.getPath(""))).isTrue(); } } @Test public void testResolve_willWorkWithRecursiveCopy() throws IOException { // See: http://stackoverflow.com/a/10068306 try (FileSystem fsSource = FileSystems.getFileSystem(URI.create("gs://hello")); FileSystem fsTarget = FileSystems.getFileSystem(URI.create("gs://cat"))) { Path targetPath = fsTarget.getPath("/some/folder/"); Path relSrcPath = fsSource.getPath("file.txt"); assertThat((Object) targetPath.resolve(relSrcPath)) .isEqualTo(fsTarget.getPath("/some/folder/file.txt")); } } @Test public void testRelativize_willWorkWithRecursiveCopy() throws IOException { // See: http://stackoverflow.com/a/10068306 try (FileSystem fsSource = FileSystems.getFileSystem(URI.create("gs://hello")); FileSystem fsTarget = FileSystems.getFileSystem(URI.create("gs://cat"))) { Path targetPath = fsTarget.getPath("/some/folder/"); Path sourcePath = fsSource.getPath("/sloth/"); Path file = fsSource.getPath("/sloth/file.txt"); assertThat((Object) targetPath.resolve(sourcePath.relativize(file))) .isEqualTo(fsTarget.getPath("/some/folder/file.txt")); } } @Test public void testToFile_unsupported() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { Path path = fs.getPath("/lol"); thrown.expect(UnsupportedOperationException.class); path.toFile(); } } @Test public void testEquals() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { new EqualsTester() // These are obviously equal. .addEqualityGroup(fs.getPath("/hello/cat"), fs.getPath("/hello/cat")) // These are equal because equals() runs things through toRealPath() .addEqualityGroup(fs.getPath("great/commandment"), fs.getPath("/great/commandment")) .addEqualityGroup(fs.getPath("great/commandment/"), fs.getPath("/great/commandment/")) // Equals shouldn't do error checking or normalization. .addEqualityGroup(fs.getPath("foo/../bar"), fs.getPath("foo/../bar")) .addEqualityGroup(fs.getPath("bar")) .testEquals(); } } @Test public void testEquals_currentDirectoryIsTakenIntoConsideration() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", workingDirectory("/hello"))) { new EqualsTester() .addEqualityGroup(fs.getPath("cat"), fs.getPath("/hello/cat")) .addEqualityGroup(fs.getPath(""), fs.getPath("/hello")) .testEquals(); } } @Test public void testNullness() throws IOException, NoSuchMethodException, SecurityException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { NullPointerTester tester = new NullPointerTester(); tester.ignore(CloudStoragePath.class.getMethod("equals", Object.class)); tester.setDefault(Path.class, fs.getPath("sup")); tester.testAllPublicStaticMethods(CloudStoragePath.class); tester.testAllPublicInstanceMethods(fs.getPath("sup")); } } @Test public void testSpaces() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { Path path = fs.getPath("/with/a space"); // we can also go via a URI. Decoding should give us the space back. String toUri = URLDecoder.decode(path.toUri().toString(), "UTF-8"); assertThat(toUri).isEqualTo("gs://doodle/with/a space"); Path path2 = fs.getPath("/with/a%20percent"); String toUri2 = URLDecoder.decode(path2.toUri().toString(), "UTF-8"); assertThat(toUri2).isEqualTo("gs://doodle/with/a%20percent"); } } private static CloudStorageConfiguration stripPrefixSlash(boolean value) { return CloudStorageConfiguration.builder().stripPrefixSlash(value).build(); } private static CloudStorageConfiguration permitEmptyPathComponents(boolean value) { return CloudStorageConfiguration.builder().permitEmptyPathComponents(value).build(); } private static CloudStorageConfiguration workingDirectory(String value) { return CloudStorageConfiguration.builder().workingDirectory(value).build(); } }
{ "content_hash": "e3bc2dd2228c9ea16ab1cad25318877c", "timestamp": "", "source": "github", "line_count": 500, "max_line_length": 115, "avg_line_length": 41.258, "alnum_prop": 0.6941684037035242, "repo_name": "rborer/google-cloud-java", "id": "8fd5ba626f170df1fff834520180190aba5f17e8", "size": "21254", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23036" }, { "name": "HTML", "bytes": "16224" }, { "name": "Java", "bytes": "7868843" }, { "name": "JavaScript", "bytes": "989" }, { "name": "Python", "bytes": "15024" }, { "name": "Shell", "bytes": "17167" } ], "symlink_target": "" }
<?php namespace yiiunit\framework\db\oci; use yiiunit\data\ar\DefaultPk; use yiiunit\data\ar\DefaultMultiplePk; use yiiunit\data\ar\Type; /** * @group db * @group oci */ class ActiveRecordTest extends \yiiunit\framework\db\ActiveRecordTest { protected $driverName = 'oci'; public function testCastValues() { // pass, because boolean casting is not available return; $model = new Type(); $model->int_col = 123; $model->int_col2 = 456; $model->smallint_col = 42; $model->char_col = '1337'; $model->char_col2 = 'test'; $model->char_col3 = 'test123'; $model->float_col = 3.742; $model->float_col2 = 42.1337; $model->bool_col = 1; $model->bool_col2 = 0; $model->save(false); /* @var $model Type */ $model = Type::find()->one(); $this->assertSame(123, $model->int_col); $this->assertSame(456, $model->int_col2); $this->assertSame(42, $model->smallint_col); $this->assertSame('1337', trim($model->char_col)); $this->assertSame('test', $model->char_col2); $this->assertSame('test123', $model->char_col3); // $this->assertSame(1337.42, $model->float_col); // $this->assertSame(42.1337, $model->float_col2); // $this->assertTrue($model->bool_col); // $this->assertFalse($model->bool_col2); } public function testDefaultValues() { $model = new Type(); $model->loadDefaultValues(); $this->assertEquals(1, $model->int_col2); $this->assertEquals('something', $model->char_col2); $this->assertEquals(1.23, $model->float_col2); $this->assertEquals(33.22, $model->numeric_col); $this->assertTrue($model->bool_col2); // not testing $model->time, because oci\Schema can't read default value $model = new Type(); $model->char_col2 = 'not something'; $model->loadDefaultValues(); $this->assertEquals('not something', $model->char_col2); $model = new Type(); $model->char_col2 = 'not something'; $model->loadDefaultValues(false); $this->assertEquals('something', $model->char_col2); } public function testFindAsArray() { /* @var $customerClass \yii\db\ActiveRecordInterface */ $customerClass = $this->getCustomerClass(); // asArray $customer = $customerClass::find()->where(['id' => 2])->asArray()->one(); $this->assertEquals([ 'id' => 2, 'email' => '[email protected]', 'name' => 'user2', 'address' => 'address2', 'status' => 1, 'profile_id' => null, 'bool_status' => true, ], $customer); // find all asArray $customers = $customerClass::find()->asArray()->all(); $this->assertCount(3, $customers); $this->assertArrayHasKey('id', $customers[0]); $this->assertArrayHasKey('name', $customers[0]); $this->assertArrayHasKey('email', $customers[0]); $this->assertArrayHasKey('address', $customers[0]); $this->assertArrayHasKey('status', $customers[0]); $this->assertArrayHasKey('bool_status', $customers[0]); $this->assertArrayHasKey('id', $customers[1]); $this->assertArrayHasKey('name', $customers[1]); $this->assertArrayHasKey('email', $customers[1]); $this->assertArrayHasKey('address', $customers[1]); $this->assertArrayHasKey('status', $customers[1]); $this->assertArrayHasKey('bool_status', $customers[1]); $this->assertArrayHasKey('id', $customers[2]); $this->assertArrayHasKey('name', $customers[2]); $this->assertArrayHasKey('email', $customers[2]); $this->assertArrayHasKey('address', $customers[2]); $this->assertArrayHasKey('status', $customers[2]); $this->assertArrayHasKey('bool_status', $customers[2]); } public function testPrimaryKeyAfterSave() { $record = new DefaultPk(); $record->type = 'type'; $record->save(false); $this->assertEquals(5, $record->primaryKey); } public function testMultiplePrimaryKeyAfterSave() { $record = new DefaultMultiplePk(); $record->id = 5; $record->second_key_column = 'secondKey'; $record->type = 'type'; $record->save(false); $this->assertEquals(5, $record->id); $this->assertEquals('secondKey', $record->second_key_column); } }
{ "content_hash": "69f781ff45882f00bcbbe7d79978c4f0", "timestamp": "", "source": "github", "line_count": 132, "max_line_length": 81, "avg_line_length": 34.53030303030303, "alnum_prop": 0.573716542343133, "repo_name": "vchenin/yii2", "id": "5935c8996445f1a6406b16e5a0e92fa5ae4b5755", "size": "4702", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/framework/db/oci/ActiveRecordTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "28" }, { "name": "Batchfile", "bytes": "1085" }, { "name": "JavaScript", "bytes": "70389" }, { "name": "PHP", "bytes": "4839361" }, { "name": "PLSQL", "bytes": "15246" }, { "name": "Ruby", "bytes": "207" }, { "name": "Shell", "bytes": "2978" } ], "symlink_target": "" }
/* * Auxiliary file for QualifiedThisAndSuper_1.java, et. al. */ package p1; public class BS { protected String u = "bsu"; protected String o() { return "bso"; } }
{ "content_hash": "06bd5845490cdbb74c1695739a9d94ad", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 59, "avg_line_length": 14.833333333333334, "alnum_prop": 0.6292134831460674, "repo_name": "rokn/Count_Words_2015", "id": "f6a44879aee37e5246c0577f55927f0692e2e355", "size": "1228", "binary": false, "copies": "94", "ref": "refs/heads/master", "path": "testing/openjdk2/langtools/test/tools/javac/p1/BS.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- DO NOT EDIT! Generated by `common/security-features/tools/generate.py --spec content-security-policy/` --> <html> <head> <meta charset="utf-8"> <meta name="timeout" content="long"> <meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-inline'"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/common/security-features/resources/common.sub.js"></script> <script src="../../../generic/test-case.sub.js"></script> </head> <body> <script> TestCase( [ { "expectation": "allowed", "origin": "cross-https", "redirection": "keep-origin", "source_context_list": [], "source_scheme": "https", "subresource": "worker-import", "subresource_policy_deliveries": [], "test_description": "Content Security Policy: Expects allowed for worker-import to cross-https origin and keep-origin redirection from https context." }, { "expectation": "allowed", "origin": "cross-https", "redirection": "no-redirect", "source_context_list": [], "source_scheme": "https", "subresource": "worker-import", "subresource_policy_deliveries": [], "test_description": "Content Security Policy: Expects allowed for worker-import to cross-https origin and no-redirect redirection from https context." }, { "expectation": "allowed", "origin": "cross-https", "redirection": "swap-origin", "source_context_list": [], "source_scheme": "https", "subresource": "worker-import", "subresource_policy_deliveries": [], "test_description": "Content Security Policy: Expects allowed for worker-import to cross-https origin and swap-origin redirection from https context." }, { "expectation": "allowed", "origin": "same-https", "redirection": "keep-origin", "source_context_list": [], "source_scheme": "https", "subresource": "worker-import", "subresource_policy_deliveries": [], "test_description": "Content Security Policy: Expects allowed for worker-import to same-https origin and keep-origin redirection from https context." }, { "expectation": "allowed", "origin": "same-https", "redirection": "no-redirect", "source_context_list": [], "source_scheme": "https", "subresource": "worker-import", "subresource_policy_deliveries": [], "test_description": "Content Security Policy: Expects allowed for worker-import to same-https origin and no-redirect redirection from https context." }, { "expectation": "allowed", "origin": "same-https", "redirection": "swap-origin", "source_context_list": [], "source_scheme": "https", "subresource": "worker-import", "subresource_policy_deliveries": [], "test_description": "Content Security Policy: Expects allowed for worker-import to same-https origin and swap-origin redirection from https context." } ], new SanityChecker() ).start(); </script> <div id="log"></div> </body> </html>
{ "content_hash": "48c32a965dcd28f9c99fdcc6d0a54153", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 162, "avg_line_length": 42.975903614457835, "alnum_prop": 0.5634987384356602, "repo_name": "nwjs/chromium.src", "id": "9f2b25ea2b5b56fdf69b08e81325bd9f3eea11d1", "size": "3567", "binary": false, "copies": "22", "ref": "refs/heads/nw70", "path": "third_party/blink/web_tests/external/wpt/content-security-policy/gen/top.meta/script-src-wildcard/worker-import.https.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.blm.orc; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpressionWriter; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpressionWriterFactory; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector; import org.apache.hadoop.io.ObjectWritable; import org.apache.hadoop.io.Writable; /** * A serde class for ORC. * It transparently passes the object to/from the ORC file reader/writer. */ public class VectorizedOrcSerde extends OrcSerde { private final OrcStruct [] orcStructArray = new OrcStruct [VectorizedRowBatch.DEFAULT_SIZE]; private final Writable [] orcRowArray = new Writable [VectorizedRowBatch.DEFAULT_SIZE]; private final ObjectWritable ow = new ObjectWritable(); private final ObjectInspector inspector = null; private final VectorExpressionWriter [] valueWriters; public VectorizedOrcSerde(ObjectInspector objInspector) { super(); for (int i = 0; i < orcStructArray.length; i++) { orcRowArray[i] = new OrcSerdeRow(); } try { valueWriters = VectorExpressionWriterFactory .getExpressionWriters((StructObjectInspector) objInspector); } catch (HiveException e) { throw new RuntimeException(e); } } @Override public Writable serialize(Object obj, ObjectInspector inspector) { VectorizedRowBatch batch = (VectorizedRowBatch) obj; try { for (int i = 0; i < batch.size; i++) { OrcStruct ost = orcStructArray[i]; if (ost == null) { ost = new OrcStruct(batch.numCols); orcStructArray[i] = ost; } int index = 0; if (batch.selectedInUse) { index = batch.selected[i]; } else { index = i; } for (int p = 0; p < batch.projectionSize; p++) { int k = batch.projectedColumns[p]; if (batch.cols[k].isRepeating) { valueWriters[p].setValue(ost, batch.cols[k], 0); } else { valueWriters[p].setValue(ost, batch.cols[k], index); } } OrcSerdeRow row = (OrcSerdeRow) orcRowArray[i]; row.realRow = ost; row.inspector = inspector; } } catch (HiveException ex) { throw new RuntimeException(ex); } ow.set(orcRowArray); return ow; } }
{ "content_hash": "68e8607f651d467cb4c97081b5c168e0", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 94, "avg_line_length": 34.69444444444444, "alnum_prop": 0.6717373899119295, "repo_name": "DamianZhou/ThingsOfHadoop", "id": "89a3ba65748bf99070956cde7b32167e869a7930", "size": "3304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Hadoop/OrcStructDemo/src/com/blm/orc/VectorizedOrcSerde.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groff", "bytes": "1048585" }, { "name": "Java", "bytes": "1277201" } ], "symlink_target": "" }
/** * Get a list of all `dt-tag tr` nodes in the table which are not currently * visible (useful for building forms). * * This function is marked as deprecated as using the `dt-api rows()` method in * DataTables 1.10+ is preferred to this approach. * * @name fnGetHiddenNodes * @summary Get the `dt-tag tr` elements which are not in the DOM * @author [Allan Jardine](http://sprymedia.co.uk) * @deprecated * * @example * var table = $('#example').dataTable(); * var nodes = table.fnGetHiddenNodes(); */ jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes = function (settings) { var nodes; var display = jQuery('tbody tr', settings.nTable); if (jQuery.fn.dataTable.versionCheck) { // DataTables 1.10 var api = new jQuery.fn.dataTable.Api(settings); nodes = api.rows().nodes().toArray(); } else { // 1.9- nodes = this.oApi._fnGetTrNodes(settings); } /* Remove nodes which are being displayed */ for (var i = 0; i < display.length; i++) { var iIndex = jQuery.inArray(display[i], nodes); if (iIndex != -1) { nodes.splice(iIndex, 1); } } return nodes; };
{ "content_hash": "ffdd15fab28cb20cac81641c9dd1218b", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 79, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6109243697478992, "repo_name": "jakub-tucek/simple-spring-borrow-system", "id": "661c4874e58a1201e41bbb2af6793d501c68f265", "size": "1190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/static/components/datatables-plugins/api/fnGetHiddenNodes.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "516240" }, { "name": "CoffeeScript", "bytes": "166382" }, { "name": "HTML", "bytes": "802048" }, { "name": "Java", "bytes": "33968" }, { "name": "JavaScript", "bytes": "4152381" }, { "name": "Makefile", "bytes": "570" }, { "name": "PowerShell", "bytes": "936" }, { "name": "Shell", "bytes": "12370" } ], "symlink_target": "" }
package org.esupportail.publisher.config.bean; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import lombok.Data; import org.springframework.validation.annotation.Validated; @Data @Validated public class ServiceProperties { @NotNull private ClassificationParams classificationParams = new ClassificationParams(); @Data @Validated public static class ClassificationParams{ @Min(600) private int defaultTTL = 3600; @Min(3000) private int defaultTimeout= 15000; @NotNull private HighlightClassification highlightClassification = new HighlightClassification(); @Data @Validated public static class HighlightClassification{ @NotBlank private String name; @NotBlank private String color; @NotBlank private String description; @Override public String toString() { return "{\n\"HighlightClassification\":{" + "\n \"name\":\"" + name + "\"" + ",\n \"color\":\"" + color + "\"" + ",\n \"description\":\"" + description + "\"" + "\n}\n}"; } } @Override public String toString() { return "{\n\"ClassificationParams\":{" + "\n \"defaultTTL\":\"" + defaultTTL + "\"" + ",\n \"defaultTimeout\":\"" + defaultTimeout + "\"" + ",\n \"highlightClassification\":" + highlightClassification + "\n}\n}"; } } @Override public String toString() { return "{\n\"ServiceProperties\":{" + "\n \"classificationParams\":" + classificationParams + "\n}\n}"; } }
{ "content_hash": "0f5a604b9ff3bd6f52b23d2292488158", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 96, "avg_line_length": 29.50769230769231, "alnum_prop": 0.5375391032325338, "repo_name": "EsupPortail/esup-publisher", "id": "30e83a0ef523d4bce7bed3846a50798cbfba35b6", "size": "2622", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/main/java/org/esupportail/publisher/config/bean/ServiceProperties.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18322" }, { "name": "HTML", "bytes": "23165" }, { "name": "Java", "bytes": "1970724" }, { "name": "JavaScript", "bytes": "196180" }, { "name": "SCSS", "bytes": "69100" }, { "name": "Shell", "bytes": "460" }, { "name": "Vue", "bytes": "592681" } ], "symlink_target": "" }
template< typename T, class TimeSource = GenericTimeSource< SimMSTimer > > class InterpolatedChangeProperty { public: enum { /// Default time (in milliseconds) to go from one value /// to a new one. DEFAULT_TRANSITION_TIME = 2000 }; typedef TimeSource TimeSourceType; typedef typename TimeSource::TickType TimeType; protected: /// The current value. mutable T mCurrentValue; /// @name Transitioning /// /// Transitioning allows to smoothly go from one value to /// a different one over a period of time. /// /// @{ /// TimeSourceType mTimeSource; /// Number of milliseconds it takes to go from one value /// to a different one. TimeType mBlendPhaseTime; /// Interpolation to use for going from source to target. EaseF mTransitionCurve; /// The time the transition started. If 0, no transition is in progress. mutable TimeType mTransitionStartTime; /// The value we are transitioning from. T mSourceValue; /// The value we are transitioning to. T mTargetValue; /// @} /// Update #mCurrentValue. void _update() const; public: /// InterpolatedChangeProperty( const T& initialValue = T() ) : mCurrentValue( initialValue ), mBlendPhaseTime( DEFAULT_TRANSITION_TIME ), mTargetValue( initialValue ), mTransitionStartTime( 0 ) { // By default, start time source right away. mTimeSource.start(); } /// Get the current value. If a transition is in progress, this will be /// an interpolation of the last value and the new one. const T& getCurrentValue() const { _update(); return mCurrentValue; } /// Set the interpolation to use for going from one ambient color to /// a different one. void setTransitionCurve( const EaseF& ease ) { mTransitionCurve = ease; } /// Set the amount of time it takes to go from one ambient color to /// a different one. void setTransitionTime( TimeType time ) { mBlendPhaseTime = time; } /// Set the desired value. If this differs from the current value, /// a smooth blend to the given color will be initiated. /// /// @param value Desired value. void setTargetValue( const T& value ); /// Return the time source to which interpolation synchronizes. const TimeSourceType& geTimeSource() const { return mTimeSource; } TimeSourceType& getTimeSource() { return mTimeSource; } }; //----------------------------------------------------------------------------- template< typename T, typename TimeSource > void InterpolatedChangeProperty< T, TimeSource >::setTargetValue( const T& value ) { if( mTargetValue == value ) return; if( mBlendPhaseTime == 0 ) { mTargetValue = value; mCurrentValue = value; } else { // Set the source value to the current value (which may be interpolated) // and then start a transition to the given target. mSourceValue = getCurrentValue(); mTargetValue = value; mTransitionStartTime = mTimeSource.getPosition(); } } //----------------------------------------------------------------------------- template< typename T, typename TimeSource > void InterpolatedChangeProperty< T, TimeSource >::_update() const { // Nothing to do if no transition in progress. if( !mTransitionStartTime ) return; // See if we have finished the transition. TimeType deltaTime = mTimeSource.getPosition() - mTransitionStartTime; if( deltaTime >= mBlendPhaseTime ) { // We're done. mCurrentValue = mTargetValue; mTransitionStartTime = 0; return; } // Determine the interpolated value. F32 blendFactor = F32( deltaTime ) / F32( mBlendPhaseTime ); blendFactor = mTransitionCurve.getUnitValue( blendFactor ); mCurrentValue.interpolate( mSourceValue, mTargetValue, blendFactor ); } #endif // !_INTERPOLATEDCHANGEPROPERTY_H_
{ "content_hash": "40d24d2c4fc481cc583799b45173f566", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 82, "avg_line_length": 28.156462585034014, "alnum_prop": 0.6151244261899009, "repo_name": "Bloodknight/Torque3D", "id": "120563c9e5f786b0a4ea6877d16b41b62fca9c8c", "size": "5911", "binary": false, "copies": "9", "ref": "refs/heads/Preview4_0", "path": "Engine/source/util/interpolatedChangeProperty.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "199191" }, { "name": "Awk", "bytes": "42982" }, { "name": "Batchfile", "bytes": "6272" }, { "name": "C", "bytes": "36261330" }, { "name": "C#", "bytes": "54021" }, { "name": "C++", "bytes": "59628094" }, { "name": "CMake", "bytes": "810787" }, { "name": "CSS", "bytes": "55472" }, { "name": "DIGITAL Command Language", "bytes": "11619" }, { "name": "Dockerfile", "bytes": "988" }, { "name": "GLSL", "bytes": "454161" }, { "name": "HLSL", "bytes": "485715" }, { "name": "HTML", "bytes": "1664814" }, { "name": "Java", "bytes": "192558" }, { "name": "JavaScript", "bytes": "73468" }, { "name": "Lex", "bytes": "18784" }, { "name": "Lua", "bytes": "1288" }, { "name": "M4", "bytes": "321055" }, { "name": "Makefile", "bytes": "253553" }, { "name": "Metal", "bytes": "3691" }, { "name": "Module Management System", "bytes": "15326" }, { "name": "NSIS", "bytes": "1193756" }, { "name": "Objective-C", "bytes": "685452" }, { "name": "Objective-C++", "bytes": "119397" }, { "name": "Pascal", "bytes": "48918" }, { "name": "Perl", "bytes": "84351" }, { "name": "PowerShell", "bytes": "12518" }, { "name": "Python", "bytes": "263449" }, { "name": "Rich Text Format", "bytes": "4380" }, { "name": "Roff", "bytes": "303500" }, { "name": "SAS", "bytes": "13756" }, { "name": "Shell", "bytes": "937082" }, { "name": "Smalltalk", "bytes": "6201" }, { "name": "StringTemplate", "bytes": "4329" }, { "name": "WebAssembly", "bytes": "13560" }, { "name": "Yacc", "bytes": "19731" } ], "symlink_target": "" }
namespace sync_preferences { class TestingPrefServiceSyncable; } #endif namespace content { class WebContents; } namespace payments { class ContentPaymentRequestDelegate; struct AppDescription { std::string label; std::string sublabel; std::string total; }; // Observe states or actions taken by the PaymentRequest in tests, supporting // both Android and desktop. class PaymentRequestTestObserver { public: virtual void OnCanMakePaymentCalled() {} virtual void OnCanMakePaymentReturned() {} virtual void OnHasEnrolledInstrumentCalled() {} virtual void OnHasEnrolledInstrumentReturned() {} virtual void OnAppListReady() {} virtual void OnErrorDisplayed() {} virtual void OnNotSupportedError() {} virtual void OnConnectionTerminated() {} virtual void OnAbortCalled() {} virtual void OnCompleteCalled() {} virtual void OnUIDisplayed() {} protected: virtual ~PaymentRequestTestObserver() = default; }; // A class to control creation and behaviour of PaymentRequests in a // cross-platform way for testing both Android and desktop. class PaymentRequestTestController { public: PaymentRequestTestController(); ~PaymentRequestTestController(); // To be called from an override of BrowserTestBase::SetUpOnMainThread(). void SetUpOnMainThread(); void SetObserver(PaymentRequestTestObserver* observer); // Sets values that will change the behaviour of PaymentRequests created in // the future. void SetOffTheRecord(bool is_off_the_record); void SetValidSsl(bool valid_ssl); void SetCanMakePaymentEnabledPref(bool can_make_payment_enabled); void SetTwaPackageName(const std::string& twa_package_name); void SetHasAuthenticator(bool has_authenticator); void SetTwaPaymentApp(const std::string& method_name, const std::string& response); // Gets the WebContents of the Payment Handler for testing purpose, or null if // nonexistent. To guarantee a non-null return, this function should be called // only if: 1) PaymentRequest UI is opening. 2) PaymentHandler is opening. content::WebContents* GetPaymentHandlerWebContents(); #if BUILDFLAG(IS_ANDROID) // Clicks the security icon on the Expandable Payment Handler toolbar for // testing purpose. Return whether it's succeeded. bool ClickPaymentHandlerSecurityIcon(); #endif // Clicks the close button on the Payment Handler toolbar for testing purpose. // Return whether it's succeeded. bool ClickPaymentHandlerCloseButton(); // Closes the dialog. bool CloseDialog(); // Confirms payment in a browser payment sheet, be it either PAYMENT_REQUEST // or SECURE_PAYMENT_CONFIRMATION type. Returns true if the dialog was // available. bool ConfirmPayment(); // Clicks opt-out on the dialog, if available. Returns true if the opt-out // link was available, false if not. bool ClickOptOut(); // Returns true when running on Android M or L. bool IsAndroidMarshmallowOrLollipop(); // Sets the list of apps available for the current payment request. void set_app_descriptions( const std::vector<AppDescription>& app_descriptions) { app_descriptions_ = app_descriptions; } // Returns the list of apps available for the current payment request. const std::vector<AppDescription>& app_descriptions() const { return app_descriptions_; } private: // Observers that forward through to the PaymentRequestTestObserver. void OnCanMakePaymentCalled(); void OnCanMakePaymentReturned(); void OnHasEnrolledInstrumentCalled(); void OnHasEnrolledInstrumentReturned(); void OnAppListReady(); void OnErrorDisplayed(); void OnNotSupportedError(); void OnConnectionTerminated(); void OnAbortCalled(); void OnCompleteCalled(); void OnUIDisplayed(); raw_ptr<PaymentRequestTestObserver> observer_ = nullptr; bool is_off_the_record_ = false; bool valid_ssl_ = true; bool can_make_payment_pref_ = true; std::string twa_package_name_; bool has_authenticator_ = false; std::string twa_payment_app_method_name_; std::string twa_payment_app_response_; std::vector<AppDescription> app_descriptions_; #if !BUILDFLAG(IS_ANDROID) void UpdateDelegateFactory(); std::unique_ptr<sync_preferences::TestingPrefServiceSyncable> prefs_; class ObserverConverter; std::unique_ptr<ObserverConverter> observer_converter_; base::WeakPtr<ContentPaymentRequestDelegate> delegate_; #endif }; } // namespace payments #endif // CHROME_TEST_PAYMENTS_PAYMENT_REQUEST_TEST_CONTROLLER_H_
{ "content_hash": "2bd3e402c246644553d694d9e20cfa1a", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 80, "avg_line_length": 31.661971830985916, "alnum_prop": 0.7548932384341637, "repo_name": "chromium/chromium", "id": "7b81c150522e5e877e42b260cacecee5c85f456d", "size": "4951", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "chrome/test/payments/payment_request_test_controller.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'time' require 'thread' require 'optparse' require 'rubygems' require 'aerospike' include Aerospike @options = { :port => 3000, :namespace => 'test', :set => 'benchmark', :key_count => 100000, :bin_def => 'I', :concurrency => 4, :workload_def => 'I:100', :throughput => 0, :timeout => 0, :max_retries => 2, :conn_queue_size => 64, :rand_bin_data => false, :debug_mode => false, :user => '', :password => '', } @mutex = Mutex.new @opt_parser = OptionParser.new do |opts| opts.banner = "Usage: benchmark [@options]" opts.on("-h", "--host HOST", "Aerospike server seed hostnames or IP addresses") do |v| @options[:host] = v end opts.on("-p", "--port PORT", "Aerospike server seed hostname or IP address port number.") do |v| @options[:port] = v.to_i end opts.on("-U", "--user USER", "Aerospike user name") do |v| @options[:user] = v end opts.on("-P", "--password PASSWORD", "Aerospike user password") do |v| @options[:password] = v end opts.on("-n", "--namespace NAMESPACE", "Aerospike namespace.") do |v| @options[:namespace] = v end opts.on("-s", "--set SET", "Aerospike set name.") do |v| @options[:set] = v end opts.on("-k", "--keys KEYS", "Key/record count or key/record range.") do |v| @options[:key_count] = v.to_i end opts.on("-o", "--object OBJECT", "Bin object specification.\n\t\t\t\t\tI\t: Read/write integer bin.\n\t\t\t\t\tB:200\t: Read/write byte array bin of length 200.\n\t\t\t\t\tS:50\t: Read/write string bin of length 50.") do |v| @options[:bin_def] = v end opts.on("-c", "--concurrency COUNT", "Number of threads to generate load.") do |v| @options[:concurrency] = v.to_i end opts.on("-w", "--workload TYPE", "Desired workload.\n\t\t\t\t\tI:60\t: Linear 'insert' workload initializing 60% of the keys.\n\t\t\t\t\tRU:80\t: Random read/update workload with 80% reads and 20% writes.") do |v| @options[:workload_def] = v end opts.on("-g", "--throttle VALUE", "Throttle transactions per second to a maximum value.\n\t\t\t\t\tIf tps is zero, do not throttle throughput.\n\t\t\t\t\tUsed in read/write mode only.") do |v| @options[:throughput] = v.to_i end opts.on("-t", "--timeout MILISECONDS", "Read/Write timeout in milliseconds.") do |v| @options[:timeout] = v.to_i / 1000.to_f end opts.on("-m", "--max-retries COUNT", "Maximum number of retries before aborting the current transaction.") do |v| @options[:max_retries] = v.to_i end opts.on("-q", "--queue-size SIZE", "Maximum number of connections to pool.") do |v| @options[:conn_queue_size] = v.to_i end opts.on("-R", "--random-bins", "Use dynamically generated random bin values instead of default static fixed bin values.") do |v| @options[:rand_bin_data] = v end opts.on("-d", "--debug", "Run benchmarks in debug mode.") do |v| @options[:debug_mode] = v end opts.on("-u", "--usage", "Show usage information.") do |v| puts opts exit end end # opt_parser def workloadToString case @workloadType when 'RU' "Read #{@workloadPercent}%, Write #{100-@workloadPercent}%" else "Initialize #{@workloadPercent}% of records" end end def throughputToString if @options[:throughput] <= 0 "unlimited" else "#{@options[:throughput]}" end end def printBenchmarkParams puts("hosts:\t\t#{@options[:host]}") puts("port:\t\t#{@options[:port]}") puts("namespace:\t#{@options[:namespace]}") puts("set:\t\t#{@options[:set]}") puts("keys/records:\t#{@options[:key_count]}") puts("object spec:\t#{@binDataType}, size: #{@binDataSize}") puts("random bins:\t#{@options[:rand_bin_data]}") puts("workload:\t#{workloadToString}") puts("concurrency:\t#{@options[:concurrency]}") puts("max throughput:\t#{throughputToString}") puts("timeout:\t#{@options[:timeout] > 0 ? (@options[:timeout] * 1000).to_i : '-'} ms") puts("max retries:\t#{@options[:max_retries]}") puts("debug:\t\t#{@options[:debug_mode]}") puts end # parses an string of (key:value) type def parseValuedParam(param) re = /(?<type>\w+)([:,](?<value>\d+))?/ values = re.match(param) if values [values[:type], values[:value].to_i] else [nil, nil] end end # reads input flags and interprets the complex ones def readFlags @opt_parser.parse! Aerospike.logger.level = Logger::ERROR if @options[:debug_mode] Aerospike.logger.level = Logger::INFO end @binDataType, binDataSz = parseValuedParam(@options[:bin_def]) if binDataSz @binDataSize = @options[:binDataSz] else case @binDataType when 'B' @binDataSize = 200 when 'S' @binDataSize = 50 end end @workloadType, workloadPct = parseValuedParam(@options[:workload_def]) if workloadPct @workloadPercent = workloadPct.to_i else case @workloadType when 'I' @workloadPercent = 100 when 'RU' @workloadPercent = 50 end end end # new random bin generator based on benchmark specs def getBin case @binDataType when 'B' bin = Bin.new('information', BytesValue.new(randString(@binDataSize))) when 'S' bin = Bin.new('information', StringValue.new(randString(@binDataSize))) else bin = Bin.new('information', IntegerValue.new(2**63)) end bin end # generates a random strings of specified length @RAND_CHARS = ('a'..'z').to_a.concat(('A'..'Z').to_a).concat(('0'..'9').to_a) def randString(size) @RAND_CHARS.shuffle[0,size].join end @totalWCount, @totalRCount = 0, 0 @totalWErrCount, @totalRErrCount = 0, 0 @totalTOCount, @totalWTOCount, @totalRTOCount = 0, 0, 0 @terminate = false Signal.trap("INT") do @terminate = true end def run_bench(client, ident, times) writepolicy = WritePolicy.new client.default_write_policy.timeout = @options[:timeout] client.default_write_policy.max_retries = @options[:max_retries] client.default_write_policy = writepolicy defaultBin = getBin t = Time.now w_count, r_count = 0, 0 write_err, read_err = 0, 0 write_to_err, read_to_err = 0, 0 bin = defaultBin namespace = @options[:namespace] set = @options[:set] randbins = @options[:rand_bin_data] iters = 1 while (@workloadType == 'RU' || iters <= times) && !@terminate # if randomBin data has been requested bin = getBin if randbins key = Key.new(namespace, set, ident*times+(iters%times)) if (@workloadType == 'I') || (rand(100) >= @workloadPercent) begin client.put(key, bin) w_count+=1 rescue Exception => err if err.is_a?(Aerospike::Exceptions::Timeout) write_to_err+=1 else write_err +=1 end end else begin client.get(key, [bin.name]) r_count+=1 rescue Exception => err if err.is_a?(Aerospike::Exceptions::Timeout) read_to_err +=1 else read_err +=1 end end end if Time.now - t >= 0.3 @mutex.synchronize do @totalWCount += w_count @totalRCount += r_count @totalWErrCount += write_err @totalRErrCount += read_err @totalWTOCount += write_to_err @totalRTOCount += read_to_err end w_count, r_count = 0, 0 write_err, read_err = 0, 0 write_to_err, read_to_err = 0, 0 t = Time.now end iters += 1 end end def log_stats(timeElapsed:, reads: 0, readTimeouts: 0, readErrors: 0, writes: 0, writeTimeouts: 0, writeErrors: 0) readTPS = reads / timeElapsed writeTPS = writes / timeElapsed total = reads + writes totalTPS = total / timeElapsed totalTimeouts = readTimeouts + writeTimeouts totalErrors = readErrors = writeErrors if @workloadType == 'RU' str = "write(tps=#{writeTPS.round} timeouts=#{writeTimeouts} errors=#{writeErrors})" str << " read(tps=#{readTPS.round} timeouts=#{readTimeouts} errors=#{readErrors})" str << " total(tps=#{totalTPS.round} timeouts=#{totalTimeouts} errors=#{totalErrors}, count=#{total})" @logger.info str else @logger.info "write(tps=#{writeTPS.round} timeouts=#{writeTimeouts} errors=#{writeErrors} totalCount=#{writes})" end end def log_final(timeElapsed) @logger.info "Totals: (run time #{timeElapsed} sec)" log_stats(timeElapsed: timeElapsed, reads: @totalRCount, readTimeouts: @totalRTOCount, readErrors: @totalRErrCount, writes: @totalWCount, writeTimeouts: @totalWTOCount, writeErrors: @totalWErrCount ) end def reporter last_totalWCount = 0 last_totalRCount = 0 last_totalWErrCount = 0 last_totalRErrCount = 0 last_totalWTOCount = 0 last_totalRTOCount = 0 t = Time.now while true timeElapsed = Time.now - t if timeElapsed >= 1 @mutex.synchronize do log_stats(timeElapsed: timeElapsed, reads: @totalRCount - last_totalRCount, readTimeouts: @totalRTOCount - last_totalRTOCount, readErrors: @totalRErrCount - last_totalRErrCount, writes: @totalWCount - last_totalWCount, writeTimeouts: @totalWTOCount - last_totalWTOCount, writeErrors: @totalWErrCount - last_totalWErrCount ) last_totalWCount = @totalWCount last_totalRCount = @totalRCount last_totalWErrCount = @totalWErrCount last_totalRErrCount = @totalRErrCount last_totalWTOCount = @totalWTOCount last_totalRTOCount = @totalRTOCount end t = Time.now end sleep(0.1) end end @logger = Logger.new(STDOUT) @logger.level = Logger::INFO readFlags printBenchmarkParams begin host = Host.new(@options[:host], @options[:port]) policy = { user: @options[:user], password: @options[:password] } client = @options[:host] ? Client.new(host, policy: policy) : Client.new(policy: policy) rescue => e abort(e.to_s) end r_thread = Thread.new do reporter end start = Time.now threads = [] for i in (1..@options[:concurrency]) do threads << Thread.new {run_bench(client, i - 1, @options[:key_count] / @options[:concurrency]) } end threads.each(&:join) @total_time = Time.now - start r_thread.kill log_final(@total_time)
{ "content_hash": "4c26c9ddca8c27c25d24e8c7620ddb3f", "timestamp": "", "source": "github", "line_count": 375, "max_line_length": 226, "avg_line_length": 27.208, "alnum_prop": 0.6333431343722434, "repo_name": "aerospike/aerospike-client-ruby", "id": "338dbdcbe90e5dff9a267f05f771d66d58120671", "size": "10224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tools/benchmark/benchmark.rb", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "812121" }, { "name": "Shell", "bytes": "1054" } ], "symlink_target": "" }
// Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "source/opt/scalar_replacement_pass.h" #include <algorithm> #include <queue> #include <tuple> #include <utility> #include "source/enum_string_mapping.h" #include "source/extensions.h" #include "source/opt/reflect.h" #include "source/opt/types.h" #include "source/util/make_unique.h" static const uint32_t kDebugValueOperandValueIndex = 5; static const uint32_t kDebugValueOperandExpressionIndex = 6; namespace spvtools { namespace opt { Pass::Status ScalarReplacementPass::Process() { Status status = Status::SuccessWithoutChange; for (auto& f : *get_module()) { Status functionStatus = ProcessFunction(&f); if (functionStatus == Status::Failure) return functionStatus; else if (functionStatus == Status::SuccessWithChange) status = functionStatus; } return status; } Pass::Status ScalarReplacementPass::ProcessFunction(Function* function) { std::queue<Instruction*> worklist; BasicBlock& entry = *function->begin(); for (auto iter = entry.begin(); iter != entry.end(); ++iter) { // Function storage class OpVariables must appear as the first instructions // of the entry block. if (iter->opcode() != SpvOpVariable) break; Instruction* varInst = &*iter; if (CanReplaceVariable(varInst)) { worklist.push(varInst); } } Status status = Status::SuccessWithoutChange; while (!worklist.empty()) { Instruction* varInst = worklist.front(); worklist.pop(); Status var_status = ReplaceVariable(varInst, &worklist); if (var_status == Status::Failure) return var_status; else if (var_status == Status::SuccessWithChange) status = var_status; } return status; } Pass::Status ScalarReplacementPass::ReplaceVariable( Instruction* inst, std::queue<Instruction*>* worklist) { std::vector<Instruction*> replacements; if (!CreateReplacementVariables(inst, &replacements)) { return Status::Failure; } std::vector<Instruction*> dead; bool replaced_all_uses = get_def_use_mgr()->WhileEachUser( inst, [this, &replacements, &dead](Instruction* user) { if (user->GetCommonDebugOpcode() == CommonDebugInfoDebugDeclare) { if (ReplaceWholeDebugDeclare(user, replacements)) { dead.push_back(user); return true; } return false; } if (user->GetCommonDebugOpcode() == CommonDebugInfoDebugValue) { if (ReplaceWholeDebugValue(user, replacements)) { dead.push_back(user); return true; } return false; } if (!IsAnnotationInst(user->opcode())) { switch (user->opcode()) { case SpvOpLoad: if (ReplaceWholeLoad(user, replacements)) { dead.push_back(user); } else { return false; } break; case SpvOpStore: if (ReplaceWholeStore(user, replacements)) { dead.push_back(user); } else { return false; } break; case SpvOpAccessChain: case SpvOpInBoundsAccessChain: if (ReplaceAccessChain(user, replacements)) dead.push_back(user); else return false; break; case SpvOpName: case SpvOpMemberName: break; default: assert(false && "Unexpected opcode"); break; } } return true; }); if (replaced_all_uses) { dead.push_back(inst); } else { return Status::Failure; } // If there are no dead instructions to clean up, return with no changes. if (dead.empty()) return Status::SuccessWithoutChange; // Clean up some dead code. while (!dead.empty()) { Instruction* toKill = dead.back(); dead.pop_back(); context()->KillInst(toKill); } // Attempt to further scalarize. for (auto var : replacements) { if (var->opcode() == SpvOpVariable) { if (get_def_use_mgr()->NumUsers(var) == 0) { context()->KillInst(var); } else if (CanReplaceVariable(var)) { worklist->push(var); } } } return Status::SuccessWithChange; } bool ScalarReplacementPass::ReplaceWholeDebugDeclare( Instruction* dbg_decl, const std::vector<Instruction*>& replacements) { // Insert Deref operation to the front of the operation list of |dbg_decl|. Instruction* dbg_expr = context()->get_def_use_mgr()->GetDef( dbg_decl->GetSingleWordOperand(kDebugValueOperandExpressionIndex)); auto* deref_expr = context()->get_debug_info_mgr()->DerefDebugExpression(dbg_expr); // Add DebugValue instruction with Indexes operand and Deref operation. int32_t idx = 0; for (const auto* var : replacements) { Instruction* added_dbg_value = context()->get_debug_info_mgr()->AddDebugValueForDecl( dbg_decl, /*value_id=*/var->result_id(), /*insert_before=*/var->NextNode(), /*scope_and_line=*/dbg_decl); if (added_dbg_value == nullptr) return false; added_dbg_value->AddOperand( {SPV_OPERAND_TYPE_ID, {context()->get_constant_mgr()->GetSIntConst(idx)}}); added_dbg_value->SetOperand(kDebugValueOperandExpressionIndex, {deref_expr->result_id()}); if (context()->AreAnalysesValid(IRContext::Analysis::kAnalysisDefUse)) { context()->get_def_use_mgr()->AnalyzeInstUse(added_dbg_value); } ++idx; } return true; } bool ScalarReplacementPass::ReplaceWholeDebugValue( Instruction* dbg_value, const std::vector<Instruction*>& replacements) { int32_t idx = 0; BasicBlock* block = context()->get_instr_block(dbg_value); for (auto var : replacements) { // Clone the DebugValue. std::unique_ptr<Instruction> new_dbg_value(dbg_value->Clone(context())); uint32_t new_id = TakeNextId(); if (new_id == 0) return false; new_dbg_value->SetResultId(new_id); // Update 'Value' operand to the |replacements|. new_dbg_value->SetOperand(kDebugValueOperandValueIndex, {var->result_id()}); // Append 'Indexes' operand. new_dbg_value->AddOperand( {SPV_OPERAND_TYPE_ID, {context()->get_constant_mgr()->GetSIntConst(idx)}}); // Insert the new DebugValue to the basic block. auto* added_instr = dbg_value->InsertBefore(std::move(new_dbg_value)); get_def_use_mgr()->AnalyzeInstDefUse(added_instr); context()->set_instr_block(added_instr, block); ++idx; } return true; } bool ScalarReplacementPass::ReplaceWholeLoad( Instruction* load, const std::vector<Instruction*>& replacements) { // Replaces the load of the entire composite with a load from each replacement // variable followed by a composite construction. BasicBlock* block = context()->get_instr_block(load); std::vector<Instruction*> loads; loads.reserve(replacements.size()); BasicBlock::iterator where(load); for (auto var : replacements) { // Create a load of each replacement variable. if (var->opcode() != SpvOpVariable) { loads.push_back(var); continue; } Instruction* type = GetStorageType(var); uint32_t loadId = TakeNextId(); if (loadId == 0) { return false; } std::unique_ptr<Instruction> newLoad( new Instruction(context(), SpvOpLoad, type->result_id(), loadId, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_ID, {var->result_id()}}})); // Copy memory access attributes which start at index 1. Index 0 is the // pointer to load. for (uint32_t i = 1; i < load->NumInOperands(); ++i) { Operand copy(load->GetInOperand(i)); newLoad->AddOperand(std::move(copy)); } where = where.InsertBefore(std::move(newLoad)); get_def_use_mgr()->AnalyzeInstDefUse(&*where); context()->set_instr_block(&*where, block); where->UpdateDebugInfoFrom(load); loads.push_back(&*where); } // Construct a new composite. uint32_t compositeId = TakeNextId(); if (compositeId == 0) { return false; } where = load; std::unique_ptr<Instruction> compositeConstruct(new Instruction( context(), SpvOpCompositeConstruct, load->type_id(), compositeId, {})); for (auto l : loads) { Operand op(SPV_OPERAND_TYPE_ID, std::initializer_list<uint32_t>{l->result_id()}); compositeConstruct->AddOperand(std::move(op)); } where = where.InsertBefore(std::move(compositeConstruct)); get_def_use_mgr()->AnalyzeInstDefUse(&*where); where->UpdateDebugInfoFrom(load); context()->set_instr_block(&*where, block); context()->ReplaceAllUsesWith(load->result_id(), compositeId); return true; } bool ScalarReplacementPass::ReplaceWholeStore( Instruction* store, const std::vector<Instruction*>& replacements) { // Replaces a store to the whole composite with a series of extract and stores // to each element. uint32_t storeInput = store->GetSingleWordInOperand(1u); BasicBlock* block = context()->get_instr_block(store); BasicBlock::iterator where(store); uint32_t elementIndex = 0; for (auto var : replacements) { // Create the extract. if (var->opcode() != SpvOpVariable) { elementIndex++; continue; } Instruction* type = GetStorageType(var); uint32_t extractId = TakeNextId(); if (extractId == 0) { return false; } std::unique_ptr<Instruction> extract(new Instruction( context(), SpvOpCompositeExtract, type->result_id(), extractId, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_ID, {storeInput}}, {SPV_OPERAND_TYPE_LITERAL_INTEGER, {elementIndex++}}})); auto iter = where.InsertBefore(std::move(extract)); iter->UpdateDebugInfoFrom(store); get_def_use_mgr()->AnalyzeInstDefUse(&*iter); context()->set_instr_block(&*iter, block); // Create the store. std::unique_ptr<Instruction> newStore( new Instruction(context(), SpvOpStore, 0, 0, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_ID, {var->result_id()}}, {SPV_OPERAND_TYPE_ID, {extractId}}})); // Copy memory access attributes which start at index 2. Index 0 is the // pointer and index 1 is the data. for (uint32_t i = 2; i < store->NumInOperands(); ++i) { Operand copy(store->GetInOperand(i)); newStore->AddOperand(std::move(copy)); } iter = where.InsertBefore(std::move(newStore)); iter->UpdateDebugInfoFrom(store); get_def_use_mgr()->AnalyzeInstDefUse(&*iter); context()->set_instr_block(&*iter, block); } return true; } bool ScalarReplacementPass::ReplaceAccessChain( Instruction* chain, const std::vector<Instruction*>& replacements) { // Replaces the access chain with either another access chain (with one fewer // indexes) or a direct use of the replacement variable. uint32_t indexId = chain->GetSingleWordInOperand(1u); const Instruction* index = get_def_use_mgr()->GetDef(indexId); int64_t indexValue = context() ->get_constant_mgr() ->GetConstantFromInst(index) ->GetSignExtendedValue(); if (indexValue < 0 || indexValue >= static_cast<int64_t>(replacements.size())) { // Out of bounds access, this is illegal IR. Notice that OpAccessChain // indexing is 0-based, so we should also reject index == size-of-array. return false; } else { const Instruction* var = replacements[static_cast<size_t>(indexValue)]; if (chain->NumInOperands() > 2) { // Replace input access chain with another access chain. BasicBlock::iterator chainIter(chain); uint32_t replacementId = TakeNextId(); if (replacementId == 0) { return false; } std::unique_ptr<Instruction> replacementChain(new Instruction( context(), chain->opcode(), chain->type_id(), replacementId, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_ID, {var->result_id()}}})); // Add the remaining indexes. for (uint32_t i = 2; i < chain->NumInOperands(); ++i) { Operand copy(chain->GetInOperand(i)); replacementChain->AddOperand(std::move(copy)); } replacementChain->UpdateDebugInfoFrom(chain); auto iter = chainIter.InsertBefore(std::move(replacementChain)); get_def_use_mgr()->AnalyzeInstDefUse(&*iter); context()->set_instr_block(&*iter, context()->get_instr_block(chain)); context()->ReplaceAllUsesWith(chain->result_id(), replacementId); } else { // Replace with a use of the variable. context()->ReplaceAllUsesWith(chain->result_id(), var->result_id()); } } return true; } bool ScalarReplacementPass::CreateReplacementVariables( Instruction* inst, std::vector<Instruction*>* replacements) { Instruction* type = GetStorageType(inst); std::unique_ptr<std::unordered_set<int64_t>> components_used = GetUsedComponents(inst); uint32_t elem = 0; switch (type->opcode()) { case SpvOpTypeStruct: type->ForEachInOperand( [this, inst, &elem, replacements, &components_used](uint32_t* id) { if (!components_used || components_used->count(elem)) { CreateVariable(*id, inst, elem, replacements); } else { replacements->push_back(CreateNullConstant(*id)); } elem++; }); break; case SpvOpTypeArray: for (uint32_t i = 0; i != GetArrayLength(type); ++i) { if (!components_used || components_used->count(i)) { CreateVariable(type->GetSingleWordInOperand(0u), inst, i, replacements); } else { replacements->push_back( CreateNullConstant(type->GetSingleWordInOperand(0u))); } } break; case SpvOpTypeMatrix: case SpvOpTypeVector: for (uint32_t i = 0; i != GetNumElements(type); ++i) { CreateVariable(type->GetSingleWordInOperand(0u), inst, i, replacements); } break; default: assert(false && "Unexpected type."); break; } TransferAnnotations(inst, replacements); return std::find(replacements->begin(), replacements->end(), nullptr) == replacements->end(); } void ScalarReplacementPass::TransferAnnotations( const Instruction* source, std::vector<Instruction*>* replacements) { // Only transfer invariant and restrict decorations on the variable. There are // no type or member decorations that are necessary to transfer. for (auto inst : get_decoration_mgr()->GetDecorationsFor(source->result_id(), false)) { assert(inst->opcode() == SpvOpDecorate); uint32_t decoration = inst->GetSingleWordInOperand(1u); if (decoration == SpvDecorationInvariant || decoration == SpvDecorationRestrict) { for (auto var : *replacements) { if (var == nullptr) { continue; } std::unique_ptr<Instruction> annotation( new Instruction(context(), SpvOpDecorate, 0, 0, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_ID, {var->result_id()}}, {SPV_OPERAND_TYPE_DECORATION, {decoration}}})); for (uint32_t i = 2; i < inst->NumInOperands(); ++i) { Operand copy(inst->GetInOperand(i)); annotation->AddOperand(std::move(copy)); } context()->AddAnnotationInst(std::move(annotation)); get_def_use_mgr()->AnalyzeInstUse(&*--context()->annotation_end()); } } } } void ScalarReplacementPass::CreateVariable( uint32_t typeId, Instruction* varInst, uint32_t index, std::vector<Instruction*>* replacements) { uint32_t ptrId = GetOrCreatePointerType(typeId); uint32_t id = TakeNextId(); if (id == 0) { replacements->push_back(nullptr); } std::unique_ptr<Instruction> variable(new Instruction( context(), SpvOpVariable, ptrId, id, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_STORAGE_CLASS, {SpvStorageClassFunction}}})); BasicBlock* block = context()->get_instr_block(varInst); block->begin().InsertBefore(std::move(variable)); Instruction* inst = &*block->begin(); // If varInst was initialized, make sure to initialize its replacement. GetOrCreateInitialValue(varInst, index, inst); get_def_use_mgr()->AnalyzeInstDefUse(inst); context()->set_instr_block(inst, block); // Copy decorations from the member to the new variable. Instruction* typeInst = GetStorageType(varInst); for (auto dec_inst : get_decoration_mgr()->GetDecorationsFor(typeInst->result_id(), false)) { uint32_t decoration; if (dec_inst->opcode() != SpvOpMemberDecorate) { continue; } if (dec_inst->GetSingleWordInOperand(1) != index) { continue; } decoration = dec_inst->GetSingleWordInOperand(2u); switch (decoration) { case SpvDecorationRelaxedPrecision: { std::unique_ptr<Instruction> new_dec_inst( new Instruction(context(), SpvOpDecorate, 0, 0, {})); new_dec_inst->AddOperand(Operand(SPV_OPERAND_TYPE_ID, {id})); for (uint32_t i = 2; i < dec_inst->NumInOperandWords(); ++i) { new_dec_inst->AddOperand(Operand(dec_inst->GetInOperand(i))); } context()->AddAnnotationInst(std::move(new_dec_inst)); } break; default: break; } } // Update the DebugInfo debug information. inst->UpdateDebugInfoFrom(varInst); replacements->push_back(inst); } uint32_t ScalarReplacementPass::GetOrCreatePointerType(uint32_t id) { auto iter = pointee_to_pointer_.find(id); if (iter != pointee_to_pointer_.end()) return iter->second; analysis::Type* pointeeTy; std::unique_ptr<analysis::Pointer> pointerTy; std::tie(pointeeTy, pointerTy) = context()->get_type_mgr()->GetTypeAndPointerType(id, SpvStorageClassFunction); uint32_t ptrId = 0; if (pointeeTy->IsUniqueType()) { // Non-ambiguous type, just ask the type manager for an id. ptrId = context()->get_type_mgr()->GetTypeInstruction(pointerTy.get()); pointee_to_pointer_[id] = ptrId; return ptrId; } // Ambiguous type. We must perform a linear search to try and find the right // type. for (auto global : context()->types_values()) { if (global.opcode() == SpvOpTypePointer && global.GetSingleWordInOperand(0u) == SpvStorageClassFunction && global.GetSingleWordInOperand(1u) == id) { if (get_decoration_mgr()->GetDecorationsFor(id, false).empty()) { // Only reuse a decoration-less pointer of the correct type. ptrId = global.result_id(); break; } } } if (ptrId != 0) { pointee_to_pointer_[id] = ptrId; return ptrId; } ptrId = TakeNextId(); context()->AddType(MakeUnique<Instruction>( context(), SpvOpTypePointer, 0, ptrId, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_STORAGE_CLASS, {SpvStorageClassFunction}}, {SPV_OPERAND_TYPE_ID, {id}}})); Instruction* ptr = &*--context()->types_values_end(); get_def_use_mgr()->AnalyzeInstDefUse(ptr); pointee_to_pointer_[id] = ptrId; // Register with the type manager if necessary. context()->get_type_mgr()->RegisterType(ptrId, *pointerTy); return ptrId; } void ScalarReplacementPass::GetOrCreateInitialValue(Instruction* source, uint32_t index, Instruction* newVar) { assert(source->opcode() == SpvOpVariable); if (source->NumInOperands() < 2) return; uint32_t initId = source->GetSingleWordInOperand(1u); uint32_t storageId = GetStorageType(newVar)->result_id(); Instruction* init = get_def_use_mgr()->GetDef(initId); uint32_t newInitId = 0; // TODO(dnovillo): Refactor this with constant propagation. if (init->opcode() == SpvOpConstantNull) { // Initialize to appropriate NULL. auto iter = type_to_null_.find(storageId); if (iter == type_to_null_.end()) { newInitId = TakeNextId(); type_to_null_[storageId] = newInitId; context()->AddGlobalValue( MakeUnique<Instruction>(context(), SpvOpConstantNull, storageId, newInitId, std::initializer_list<Operand>{})); Instruction* newNull = &*--context()->types_values_end(); get_def_use_mgr()->AnalyzeInstDefUse(newNull); } else { newInitId = iter->second; } } else if (IsSpecConstantInst(init->opcode())) { // Create a new constant extract. newInitId = TakeNextId(); context()->AddGlobalValue(MakeUnique<Instruction>( context(), SpvOpSpecConstantOp, storageId, newInitId, std::initializer_list<Operand>{ {SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER, {SpvOpCompositeExtract}}, {SPV_OPERAND_TYPE_ID, {init->result_id()}}, {SPV_OPERAND_TYPE_LITERAL_INTEGER, {index}}})); Instruction* newSpecConst = &*--context()->types_values_end(); get_def_use_mgr()->AnalyzeInstDefUse(newSpecConst); } else if (init->opcode() == SpvOpConstantComposite) { // Get the appropriate index constant. newInitId = init->GetSingleWordInOperand(index); Instruction* element = get_def_use_mgr()->GetDef(newInitId); if (element->opcode() == SpvOpUndef) { // Undef is not a valid initializer for a variable. newInitId = 0; } } else { assert(false); } if (newInitId != 0) { newVar->AddOperand({SPV_OPERAND_TYPE_ID, {newInitId}}); } } uint64_t ScalarReplacementPass::GetArrayLength( const Instruction* arrayType) const { assert(arrayType->opcode() == SpvOpTypeArray); const Instruction* length = get_def_use_mgr()->GetDef(arrayType->GetSingleWordInOperand(1u)); return context() ->get_constant_mgr() ->GetConstantFromInst(length) ->GetZeroExtendedValue(); } uint64_t ScalarReplacementPass::GetNumElements(const Instruction* type) const { assert(type->opcode() == SpvOpTypeVector || type->opcode() == SpvOpTypeMatrix); const Operand& op = type->GetInOperand(1u); assert(op.words.size() <= 2); uint64_t len = 0; for (size_t i = 0; i != op.words.size(); ++i) { len |= (static_cast<uint64_t>(op.words[i]) << (32ull * i)); } return len; } bool ScalarReplacementPass::IsSpecConstant(uint32_t id) const { const Instruction* inst = get_def_use_mgr()->GetDef(id); assert(inst); return spvOpcodeIsSpecConstant(inst->opcode()); } Instruction* ScalarReplacementPass::GetStorageType( const Instruction* inst) const { assert(inst->opcode() == SpvOpVariable); uint32_t ptrTypeId = inst->type_id(); uint32_t typeId = get_def_use_mgr()->GetDef(ptrTypeId)->GetSingleWordInOperand(1u); return get_def_use_mgr()->GetDef(typeId); } bool ScalarReplacementPass::CanReplaceVariable( const Instruction* varInst) const { assert(varInst->opcode() == SpvOpVariable); // Can only replace function scope variables. if (varInst->GetSingleWordInOperand(0u) != SpvStorageClassFunction) { return false; } if (!CheckTypeAnnotations(get_def_use_mgr()->GetDef(varInst->type_id()))) { return false; } const Instruction* typeInst = GetStorageType(varInst); if (!CheckType(typeInst)) { return false; } if (!CheckAnnotations(varInst)) { return false; } if (!CheckUses(varInst)) { return false; } return true; } bool ScalarReplacementPass::CheckType(const Instruction* typeInst) const { if (!CheckTypeAnnotations(typeInst)) { return false; } switch (typeInst->opcode()) { case SpvOpTypeStruct: // Don't bother with empty structs or very large structs. if (typeInst->NumInOperands() == 0 || IsLargerThanSizeLimit(typeInst->NumInOperands())) { return false; } return true; case SpvOpTypeArray: if (IsSpecConstant(typeInst->GetSingleWordInOperand(1u))) { return false; } if (IsLargerThanSizeLimit(GetArrayLength(typeInst))) { return false; } return true; // TODO(alanbaker): Develop some heuristics for when this should be // re-enabled. //// Specifically including matrix and vector in an attempt to reduce the //// number of vector registers required. // case SpvOpTypeMatrix: // case SpvOpTypeVector: // if (IsLargerThanSizeLimit(GetNumElements(typeInst))) return false; // return true; case SpvOpTypeRuntimeArray: default: return false; } } bool ScalarReplacementPass::CheckTypeAnnotations( const Instruction* typeInst) const { for (auto inst : get_decoration_mgr()->GetDecorationsFor(typeInst->result_id(), false)) { uint32_t decoration; if (inst->opcode() == SpvOpDecorate) { decoration = inst->GetSingleWordInOperand(1u); } else { assert(inst->opcode() == SpvOpMemberDecorate); decoration = inst->GetSingleWordInOperand(2u); } switch (decoration) { case SpvDecorationRowMajor: case SpvDecorationColMajor: case SpvDecorationArrayStride: case SpvDecorationMatrixStride: case SpvDecorationCPacked: case SpvDecorationInvariant: case SpvDecorationRestrict: case SpvDecorationOffset: case SpvDecorationAlignment: case SpvDecorationAlignmentId: case SpvDecorationMaxByteOffset: case SpvDecorationRelaxedPrecision: break; default: return false; } } return true; } bool ScalarReplacementPass::CheckAnnotations(const Instruction* varInst) const { for (auto inst : get_decoration_mgr()->GetDecorationsFor(varInst->result_id(), false)) { assert(inst->opcode() == SpvOpDecorate); uint32_t decoration = inst->GetSingleWordInOperand(1u); switch (decoration) { case SpvDecorationInvariant: case SpvDecorationRestrict: case SpvDecorationAlignment: case SpvDecorationAlignmentId: case SpvDecorationMaxByteOffset: break; default: return false; } } return true; } bool ScalarReplacementPass::CheckUses(const Instruction* inst) const { VariableStats stats = {0, 0}; bool ok = CheckUses(inst, &stats); // TODO(alanbaker/greg-lunarg): Add some meaningful heuristics about when // SRoA is costly, such as when the structure has many (unaccessed?) // members. return ok; } bool ScalarReplacementPass::CheckUses(const Instruction* inst, VariableStats* stats) const { uint64_t max_legal_index = GetMaxLegalIndex(inst); bool ok = true; get_def_use_mgr()->ForEachUse(inst, [this, max_legal_index, stats, &ok]( const Instruction* user, uint32_t index) { if (user->GetCommonDebugOpcode() == CommonDebugInfoDebugDeclare || user->GetCommonDebugOpcode() == CommonDebugInfoDebugValue) { // TODO: include num_partial_accesses if it uses Fragment operation or // DebugValue has Indexes operand. stats->num_full_accesses++; return; } // Annotations are check as a group separately. if (!IsAnnotationInst(user->opcode())) { switch (user->opcode()) { case SpvOpAccessChain: case SpvOpInBoundsAccessChain: if (index == 2u && user->NumInOperands() > 1) { uint32_t id = user->GetSingleWordInOperand(1u); const Instruction* opInst = get_def_use_mgr()->GetDef(id); const auto* constant = context()->get_constant_mgr()->GetConstantFromInst(opInst); if (!constant) { ok = false; } else if (constant->GetZeroExtendedValue() >= max_legal_index) { ok = false; } else { if (!CheckUsesRelaxed(user)) ok = false; } stats->num_partial_accesses++; } else { ok = false; } break; case SpvOpLoad: if (!CheckLoad(user, index)) ok = false; stats->num_full_accesses++; break; case SpvOpStore: if (!CheckStore(user, index)) ok = false; stats->num_full_accesses++; break; case SpvOpName: case SpvOpMemberName: break; default: ok = false; break; } } }); return ok; } bool ScalarReplacementPass::CheckUsesRelaxed(const Instruction* inst) const { bool ok = true; get_def_use_mgr()->ForEachUse( inst, [this, &ok](const Instruction* user, uint32_t index) { switch (user->opcode()) { case SpvOpAccessChain: case SpvOpInBoundsAccessChain: if (index != 2u) { ok = false; } else { if (!CheckUsesRelaxed(user)) ok = false; } break; case SpvOpLoad: if (!CheckLoad(user, index)) ok = false; break; case SpvOpStore: if (!CheckStore(user, index)) ok = false; break; case SpvOpImageTexelPointer: if (!CheckImageTexelPointer(index)) ok = false; break; default: ok = false; break; } }); return ok; } bool ScalarReplacementPass::CheckImageTexelPointer(uint32_t index) const { return index == 2u; } bool ScalarReplacementPass::CheckLoad(const Instruction* inst, uint32_t index) const { if (index != 2u) return false; if (inst->NumInOperands() >= 2 && inst->GetSingleWordInOperand(1u) & SpvMemoryAccessVolatileMask) return false; return true; } bool ScalarReplacementPass::CheckStore(const Instruction* inst, uint32_t index) const { if (index != 0u) return false; if (inst->NumInOperands() >= 3 && inst->GetSingleWordInOperand(2u) & SpvMemoryAccessVolatileMask) return false; return true; } bool ScalarReplacementPass::IsLargerThanSizeLimit(uint64_t length) const { if (max_num_elements_ == 0) { return false; } return length > max_num_elements_; } std::unique_ptr<std::unordered_set<int64_t>> ScalarReplacementPass::GetUsedComponents(Instruction* inst) { std::unique_ptr<std::unordered_set<int64_t>> result( new std::unordered_set<int64_t>()); analysis::DefUseManager* def_use_mgr = context()->get_def_use_mgr(); def_use_mgr->WhileEachUser(inst, [&result, def_use_mgr, this](Instruction* use) { switch (use->opcode()) { case SpvOpLoad: { // Look for extract from the load. std::vector<uint32_t> t; if (def_use_mgr->WhileEachUser(use, [&t](Instruction* use2) { if (use2->opcode() != SpvOpCompositeExtract || use2->NumInOperands() <= 1) { return false; } t.push_back(use2->GetSingleWordInOperand(1)); return true; })) { result->insert(t.begin(), t.end()); return true; } else { result.reset(nullptr); return false; } } case SpvOpName: case SpvOpMemberName: case SpvOpStore: // No components are used. return true; case SpvOpAccessChain: case SpvOpInBoundsAccessChain: { // Add the first index it if is a constant. // TODO: Could be improved by checking if the address is used in a load. analysis::ConstantManager* const_mgr = context()->get_constant_mgr(); uint32_t index_id = use->GetSingleWordInOperand(1); const analysis::Constant* index_const = const_mgr->FindDeclaredConstant(index_id); if (index_const) { result->insert(index_const->GetSignExtendedValue()); return true; } else { // Could be any element. Assuming all are used. result.reset(nullptr); return false; } } default: // We do not know what is happening. Have to assume the worst. result.reset(nullptr); return false; } }); return result; } Instruction* ScalarReplacementPass::CreateNullConstant(uint32_t type_id) { analysis::TypeManager* type_mgr = context()->get_type_mgr(); analysis::ConstantManager* const_mgr = context()->get_constant_mgr(); const analysis::Type* type = type_mgr->GetType(type_id); const analysis::Constant* null_const = const_mgr->GetConstant(type, {}); Instruction* null_inst = const_mgr->GetDefiningInstruction(null_const, type_id); if (null_inst != nullptr) { context()->UpdateDefUse(null_inst); } return null_inst; } uint64_t ScalarReplacementPass::GetMaxLegalIndex( const Instruction* var_inst) const { assert(var_inst->opcode() == SpvOpVariable && "|var_inst| must be a variable instruction."); Instruction* type = GetStorageType(var_inst); switch (type->opcode()) { case SpvOpTypeStruct: return type->NumInOperands(); case SpvOpTypeArray: return GetArrayLength(type); case SpvOpTypeMatrix: case SpvOpTypeVector: return GetNumElements(type); default: return 0; } return 0; } } // namespace opt } // namespace spvtools
{ "content_hash": "7fa6d8feec2045dad239d87459c8ff36", "timestamp": "", "source": "github", "line_count": 998, "max_line_length": 80, "avg_line_length": 34.14829659318637, "alnum_prop": 0.6274354460093897, "repo_name": "emoon/bgfx", "id": "8adca7b9aeae5346b4ed89b787ba3ffb91b3305c", "size": "34080", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "3rdparty/spirv-tools/source/opt/scalar_replacement_pass.cpp", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "439062" }, { "name": "C++", "bytes": "3620364" }, { "name": "Lua", "bytes": "17299" }, { "name": "Makefile", "bytes": "29122" }, { "name": "Objective-C++", "bytes": "32724" }, { "name": "Scala", "bytes": "12411" }, { "name": "Shell", "bytes": "49221" }, { "name": "SuperCollider", "bytes": "102766" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="/assets/jquery/jquery-1.11.2.js"></script> <script src="/assets/jquery/jquery.slicknav.min.js"></script> <script src="/assets/jquery/jquery.watermark.min.js"></script> <script src="/assets/js/jekyll-search.js"></script> <title>Buckwheat and Shiitake Mushroom Salad with Gouda</title> <meta name="description" content="Cooking and Code: simple, healthy, easy, delicious recipes curated by me, Lucy Wyman"> <meta name="keywords" content="Buckwheat and Shiitake Mushroom Salad with Gouda, , recipes, easy, healthy, jekyll, ruby, cooking, code"> <meta name="robots" content="index, follow"> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Cooking and Code | Buckwheat and Shiitake Mushroom Salad with Gouda" /> <meta property="og:url" content="http://recipes.lucywyman.me" /> <meta property="og:site_name" content="Cooking and Code" /> <link rel="stylesheet" href="/assets/css/slicknav.min.css"> <link rel="stylesheet" href="/assets/css/main.css"> <link rel="canonical" href="/buckwheat-mushroom-salad.html"> <link rel="alternate" type="application/rss+xml" title="Recipes" href="/feed.xml" /> <link rel="icon" type="image/png" href="/assets/img/favicon.png" /> </head> <body> <div class='sidebar' id='sidebar'> <input type="text" id='search-input' class="search-field" placeholder="Search" autocomplete=true> <ul> <li><a href="/about">about me</a></li> <li><a href="/all">all recipes</a></li> <li class='expanded'><a class='on'>bread <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/pumpkin-challah.html">Pumpkin Challah</a></li> <li><a href="/apple-muffins.html">Brown Butter Apple Muffins</a></li> <li><a href="/brown-butter-banana-bread.html">Brown Butter Banana Bread</a></li> <li><a href='/bread'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>breakfast <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/pumpkin-spiced-pancakes.html">Pumpkin Spiced Pancakes</a></li> <li><a href="/tomato-turmeric-omelet.html">Tomato Turmeric Omelet</a></li> <li><a href="/kale-sweet-potato-egg-bake.html">Kale and Sweet Potato Egg Bake</a></li> <li><a href='/breakfast'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>desserts <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/miso-peanut-butter-cookies.html">Miso Peanut Butter Cookies</a></li> <li><a href="/matcha-cookies.html">Matcha Cookies</a></li> <li><a href="/elvis-piesley.html">Elvis Piesley</a></li> <li><a href='/desserts'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>drinks <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/pumpkin-spice-latte.html">Pumpkin Spice Latte</a></li> <li><a href="/chai-apple-cider.html">Chai Apple Cider</a></li> <li><a href="/turmeric-latte.html">Turmeric Ginger Latte</a></li> <li><a href='/drinks'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>mains <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/pumpkin-pasta.html">Pumpkin Pasta</a></li> <li><a href="/veggie-meatballs.html">Mushroom Meatballs</a></li> <li><a href="/sauteed-shrimp-with-tomato-onion-sauce.html">Sauteed Shrimp with Tomato and Onion</a></li> <li><a href='/mains'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>salads <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/simple-kale-salad.html">Kale Salad with Pecorino and Lemon</a></li> <li><a href="/farmers-market-salad.html">Farmers Market Salad</a></li> <li><a href="/spring-strawberry.html">Spring Strawberry Salad</a></li> <li><a href='/salads'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>sides <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/creamy-mashed-cauliflower.html">Creamy Mashed Cauliflower</a></li> <li><a href="/pumpkin-butter.html">Pumpkin Butter</a></li> <li><a href="/guacamole.html">Guacamole</a></li> <li><a href='/sides'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>snacks <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/cheez-its.html">Homemade Cheez-Its</a></li> <li><a href='/snacks'>more...</a></li> </ul> </li> <li class='expanded'><a class='on'>soups <span style='font-size: 10px; vertical-align: middle;'>&#9660;</span></a> <ul class='submenu'> <li><a href=""></a></li> <li><a href="/chickpea-vegetable-soup.html">Instant Pot Chickpea Vegetable Soup with Parmesan</a></li> <li><a href="/cioppino.html">Instant Pot Cioppino</a></li> <li><a href="/carrot-soup.html">Carrot Curry Soup</a></li> <li><a href='/soups'>more...</a></li> </ul> </li> </ul> </div> <main> <div class='recipe print'> <h2 class='title'>Buckwheat and Shiitake Mushroom Salad with Gouda</h2><br> <hr><br> <center> <h5>From: <a href='https://www.bonappetit.com/recipe/buckwheat-and-shiitake-mushroom-salad-with-gouda'>Bon Appetit</a> • <a href='#' onclick="print()">Print this Recipe</a></h5></center> <h4 id='results'>Search Results</h4> <ul class='results' id='results-container'></ul> <h5 id="ingredients">Ingredients:</h5> <ul> <li>2 tablespoons olive oil, plus more for drizzling</li> <li>1½ cups buckwheat groats</li> <li>8 ounces shiitake mushrooms, thinly sliced</li> <li>3 cups parsley leaves with tender stems (about 1 large bunch)</li> <li>4 ounces goat’s- or cow’s-milk Gouda, shaved, divided</li> <li>Kosher salt, freshly ground pepper</li> </ul> <p><br /></p> <h5 id="directions">Directions:</h5> <ol> <li>Heat oil in a large skillet over medium-high.</li> <li>Cook buckwheat, stirring often, until slightly darkened in color and fragrant, about 5 minutes; transfer buckwheat and oil to a large bowl.</li> <li>Add mushrooms, parsley, and half of Gouda and season with salt and pepper; toss to combine. Top with remaining Gouda and drizzle with oil. Grind a little more pepper on top.</li> </ol> </div> </main> <footer class='footer'> <p>This site is made by me, <a href='http://lucywyman.me'>Lucy Wyman</a>, and is powered by <a href='http://jekyllrb.com/'>Jekyll</a> and <a href='https://pages.github.com/'>Github Pages</a></p> </footer> <!-- All the yavascripts --> <!-- Slicknav --> <script> $(document).ready(function(){ $('#sidebar').slicknav({ label:'' }); }); </script> <!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-48093989-4', 'auto'); ga('send', 'pageview'); </script> <!-- Custom JS --> <script> $(document).ready(function(){ // Expanding navigation bar js $('ul li.expanded > a') .attr('data-active','0') .click(function(event){ $('.submuneu').hide(); if($(this).attr('data-active')==0){ $(this).parent().find('ul').slideToggle('slow'); $(this).attr('data-active','1'); } else{ $(this).parent().find('ul').slideToggle('slow'); $(this).attr('data-active','0');} $('a.on').removeClass("active"); $(this).addClass("active"); }); SimpleJekyllSearch({ searchInput: document.getElementById('search-input'), resultsContainer: document.getElementById('results-container'), json: "/search.json", searchResultsTemplate:'<li><a href="{url}">{title}</a></li>', fuzzy: true }) $("#search-input").keyup(function(){ if($("#search-input").val() != ""){ $("#results").css("display", "block"); } else { $("#results").css("display", "none"); } }); }); </script> </body> </html>
{ "content_hash": "609ef444ad9b428ce72b08cb34bdb422", "timestamp": "", "source": "github", "line_count": 330, "max_line_length": 198, "avg_line_length": 27.76060606060606, "alnum_prop": 0.6079030673507259, "repo_name": "lucywyman/recipes-website", "id": "05cf57fa2aa10662f71b6af8166cc1564a57a87e", "size": "9168", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "site/buckwheat-mushroom-salad.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "575242" }, { "name": "HTML", "bytes": "1428265" }, { "name": "Ruby", "bytes": "186" }, { "name": "Shell", "bytes": "862" } ], "symlink_target": "" }
import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import org.glassfish.jaxb.runtime.CycleRecoverable; public class Main { public static void main(String[] args) throws JAXBException { // let's create an obvious cycle Person p = new Person(); p.id = 5; p.name = "Joe Chin"; p.parent = p; JAXBContext context = JAXBContext.newInstance(Person.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); m.marshal(p,System.out); } }
{ "content_hash": "6a4d6f9fbe58b3c860f0d1ee6b2a01df", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 68, "avg_line_length": 28.227272727272727, "alnum_prop": 0.6682769726247987, "repo_name": "eclipse-ee4j/jaxb-ri", "id": "e2bcb1b2dbc10e898d5bba9477df25697fabbd85", "size": "957", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jaxb-ri/samples/src/main/samples/cycle-recovery/src/Main.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3049" }, { "name": "CSS", "bytes": "6843" }, { "name": "HTML", "bytes": "14919" }, { "name": "Java", "bytes": "5454681" }, { "name": "Shell", "bytes": "11506" }, { "name": "XSLT", "bytes": "10643" } ], "symlink_target": "" }
module Trax module Core module Definitions def self.extended(base) base.extend(Trax::Core::Fields) end def enum(klass_name, **options, &block) attribute_klass = if options.key?(:extends) _klass_prototype = options[:extends].constantize.clone ::Trax::Core::NamedClass.new("#{self.name}::#{klass_name}", _klass_prototype, :parent_definition => self, &block) else ::Trax::Core::NamedClass.new("#{self.name}::#{klass_name}", ::Trax::Core::Types::Enum, :parent_definition => self, &block) end attribute_klass end def struct(klass_name, **options, &block) attribute_klass = if options.key?(:extends) _klass_prototype = options[:extends].constantize.clone ::Trax::Core::NamedClass.new("#{self.name}::#{klass_name}", _klass_prototype, :parent_definition => self, &block) else ::Trax::Core::NamedClass.new("#{self.name}::#{klass_name}", ::Trax::Core::Types::Struct, :parent_definition => self, &block) end attribute_klass end end end end
{ "content_hash": "92d6c1780d28e07164b2cb66d01ac168", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 134, "avg_line_length": 35.903225806451616, "alnum_prop": 0.6001796945193172, "repo_name": "vyrak/trax_core", "id": "4f7069817279d113e3018dfab1565ccc8a365934", "size": "1113", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/trax/core/definitions.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "135774" } ], "symlink_target": "" }
var Board = require("../lib/board.js"), events = require("events"), util = require("util"), Sensor = require("../lib/sensor.js"); var priv = new Map(); var Devices = { NONDIRECTIONAL: { pins: { get: function() { return { pwm: this.opts.pin }; } }, dir: { value: function() { console.log("Non-directional motor type"); return this; } }, brake: { value: function() { this.speed({speed: 0, saveState: false}); this.emit("brake", null, new Date()); } }, release: { value: function() { this.start(); this.emit("release", null, new Date()); } } }, DIRECTIONAL: { pins: { get: function() { if (Array.isArray(this.opts.pins)) { return { pwm: this.opts.pins[0], dir: this.opts.pins[1] }; } else { return this.opts.pins; } } }, dir: { value: function(motor, speed, dir) { speed = speed || this.speed(); this.stop(); this.io.digitalWrite(this.pins.dir, dir.value); this.direction = dir.value; this.start(speed); this.emit(dir.name, null, new Date()); return this; } }, brake: { value: function(duration) { if (typeof this.pins.brake === "undefined") { this.stop(); return this; } this.io.digitalWrite(this.pins.brake, 1); this.io.digitalWrite(this.pins.dir, 1); this.speed({speed: 255, saveState: false}); this.emit("brake", null, new Date()); if (duration) { var motor = this; this.board.wait(duration, function() { motor.stop(); }); } return this; } }, release: { value: function() { if (this.pins.brake) { this.io.digitalWrite(this.pins.brake, 0); this.io.digitalWrite(this.pins.dir, this.direction); var speed = this.speed(); this.speed(speed); this.emit("release", null, new Date()); } return this; } } }, CDIR: { pins: { get: function() { if (Array.isArray(this.opts.pins)) { return { pwm: this.opts.pins[0], dir: this.opts.pins[1], cdir: this.opts.pins[2] }; } else { return this.opts.pins; } } }, dir: { value: function(motor, speed, dir) { speed = speed || this.speed(); this.stop(); this.direction = dir.value; this.io.digitalWrite(this.pins.cdir, 1 ^ dir.value); this.io.digitalWrite(this.pins.dir, dir.value); this.start(speed); this.emit(dir.name, null, new Date()); return this; } }, brake: { value: function(duration) { this.speed({speed:255, saveState: false}); this.io.digitalWrite(this.pins.dir, 1); this.io.digitalWrite(this.pins.cdir, 1); this.emit("brake", null, new Date()); if (duration) { var motor = this; this.board.wait(duration, function() { motor.stop(); }); } return this; } }, release: { value: function() { var speed = this.speed(); this.speed(speed); this.io.digitalWrite(this.pins.dir, this.direction); this.io.digitalWrite(this.pins.cdir, 1 ^ this.direction); this.emit("release", null, new Date()); return this; } } } }; /** * Motor * @constructor * * @param {Object} opts Options: pin|pins{pwm, dir[, cdir]}, device, interface, current * @param {Number} pin A single pin for basic * @param {Array} pins A two or three digit array of pins [pwm, dir]|[pwm, dir, cdir] * * * Initializing "Hobby Motors" * * new five.Motor(9); * * ...is the same as... * * new five.Motor({ * pin: 9 * }); * * * Initializing 2 pin, Bi-Directional DC Motors: * * new five.Motor([ 3, 12 ]); * * ...is the same as... * * new five.Motor({ * pins: [ 3, 12 ] * }); * * ...is the same as... * * new five.Motor({ * pins: { * pwm: 3, * dir: 12 * } * }); * * * Initializing 3 pin, Bi-Directional DC Motors: * * new five.Motor([ 3, 12, 11 ]); * * ...is the same as... * * new five.Motor({ * pins: [ 3, 12, 11 ] * }); * * ...is the same as... * * new five.Motor({ * pins: { * pwm: 3, * dir: 12, * cdir: 11 * } * }); * * * Initializing Bi-Directional DC Motors with brake: * * new five.Motor({ * pins: { * pwm: 3, * dir: 12, * brake: 11 * } * }); * * * Initializing Bi-Directional DC Motors with current sensing pins: * See Sensor.js for details on options * * new five.Motor({ * pins: [3, 12], * current: { * pin: "A0", * freq: 250, * range: [0, 2000] * } * }); * * * Initializing Bi-Directional DC Motors with inverted speed for reverse: * Most likely used for non-commercial H-Bridge controllers * * new five.Motor({ * pins: [3, 12], * invertPWM: true * }); * */ function Motor(opts) { if (!(this instanceof Motor)) { return new Motor(opts); } // Initialize a Device instance on a Board Board.Device.call( this, this.opts = Board.Options(opts) ); /* Note: Interface overrides device * To the user we present both "device" and "interface" * params to map logically to real-world things. * "Devices" are motors and "interfaces" are controllers. * Here in the the library we are not concerned with * this distinction. */ if (this.opts.interface) { this.opts.device = this.opts.interface; } // Derive device based on pins passed if (typeof this.opts.device === "undefined") { this.opts.device = typeof this.opts.pins === "undefined" ? "NONDIRECTIONAL" : "DIRECTIONAL"; if (this.opts.pins && (this.opts.pins.cdir || this.opts.pins.length > 2)) { this.opts.device = "CDIR"; } } // Allow users to pass in custom device types var device = typeof this.opts.device === "string" ? Devices[this.opts.device] : this.opts.device; this.threshold = typeof this.opts.threshold !== "undefined" ? this.opts.threshold : 30; this.invertPWM = typeof this.opts.invertPWM !== "undefined" ? this.opts.invertPWM : false; // We need to store the state of the dir pin for release() this.direction = 0; Object.defineProperties(this, device); // Set the PWM pin to PWM mode this.io.pinMode(this.pins.pwm, this.io.MODES.PWM); ["dir", "cdir", "brake"].forEach(function(pin) { if (this.pins[pin]) { this.io.pinMode(this.pins[pin], this.io.MODES.OUTPUT); } }, this); // current just wraps a Sensor if (this.opts.current) { this.opts.current.board = this.board; this.current = new Sensor(this.opts.current); } Object.defineProperties(this, { // Calculated, read-only motor on/off state // true|false isOn: { get: function() { return priv.get(this).isOn; } }, currentSpeed: { get: function() { return priv.get(this).currentSpeed; } } }); // Create a "state" entry for privately // storing the state of the motor priv.set(this, { isOn: false, currentSpeed: typeof this.opts.speed !== "undefined" ? this.opts.speed : 128 }); } util.inherits(Motor, events.EventEmitter); Motor.prototype.speed = function(opts) { if (typeof opts === 'undefined') { return this.currentSpeed; } else { if (typeof opts === 'number') { opts = { speed: opts }; } opts.speed = Board.constrain(opts.speed, 0, 255); opts.saveState = typeof opts.saveState !== "undefined" ? opts.saveState : true; if (opts.speed < this.threshold) { opts.speed = 0; } if (opts.saveState) { // Update stored values priv.set(this, { isOn: opts.speed === 0 ? false : true, currentSpeed: opts.speed }); } if (this.invertPWM && this.direction === 1) { opts.speed ^= 0xff; } this.io.analogWrite(this.pins.pwm, opts.speed); return this; } }; // start a motor - essentially just switch it on like a normal motor Motor.prototype.start = function(speed) { // Send a signal to turn on the motor and run at given speed in whatever // direction is currently set. if (this.pins.brake) { this.io.digitalWrite(this.pins.brake, 0); } // get current speed if nothing provided. speed = typeof speed !== 'undefined' ? speed : this.speed(); this.speed(speed); // "start" event is fired when the motor is started if (speed > 0) { this.emit("start", null, new Date()); } return this; }; Motor.prototype.stop = function() { this.speed(0); this.release(); // "stop" event is fired when the motor is stopped this.emit("stop", null, new Date()); return this; }; [ /** * forward Turn the Motor in its forward direction * fwd Turn the Motor in its forward direction * * @param {Number} 0-255, 0 is stopped, 255 is fastest * @return {Object} this */ { name: "forward", abbr: "fwd", value: 1 }, /** * reverse Turn the Motor in its reverse direction * rev Turn the Motor in its reverse direction * * @param {Number} 0-255, 0 is stopped, 255 is fastest * @return {Object} this */ { name: "reverse", abbr: "rev", value: 0 } ].forEach(function(dir) { var method = function(speed) { this.dir(this, speed, dir); return this; }; Motor.prototype[dir.name] = Motor.prototype[dir.abbr] = method; }); module.exports = Motor; // References // http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM
{ "content_hash": "df877cbc391e9f5912447ed33d61a84a", "timestamp": "", "source": "github", "line_count": 475, "max_line_length": 87, "avg_line_length": 21.073684210526316, "alnum_prop": 0.5451548451548451, "repo_name": "rbrazileiro/tamarino", "id": "0cbc92a0246138cefb28251857e2dc75e90d9fe2", "size": "10010", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/sys/node_modules/johnny-five/lib/motor.js", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3723173" }, { "name": "C++", "bytes": "270377" }, { "name": "CSS", "bytes": "50858" }, { "name": "Erlang", "bytes": "10" }, { "name": "Java", "bytes": "47626" }, { "name": "JavaScript", "bytes": "374272" }, { "name": "Objective-C", "bytes": "11781" }, { "name": "PHP", "bytes": "25856" }, { "name": "Perl", "bytes": "4637" }, { "name": "Ruby", "bytes": "23049" }, { "name": "Shell", "bytes": "32784" } ], "symlink_target": "" }
package gang.com.screencontrol; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
{ "content_hash": "bdb53016e75c50e17e71bb9a3495a11e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 81, "avg_line_length": 23.529411764705884, "alnum_prop": 0.6925, "repo_name": "xiaoganggang/ScreenControl", "id": "b6f896c3e844c84c299214f6902ca49b08f06091", "size": "400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/test/java/gang/com/screencontrol/ExampleUnitTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "492142" } ], "symlink_target": "" }
package containerd import ( "context" "fmt" "io" "net/http" "runtime" "strconv" "time" containersapi "github.com/containerd/containerd/api/services/containers/v1" contentapi "github.com/containerd/containerd/api/services/content/v1" diffapi "github.com/containerd/containerd/api/services/diff/v1" eventsapi "github.com/containerd/containerd/api/services/events/v1" imagesapi "github.com/containerd/containerd/api/services/images/v1" introspectionapi "github.com/containerd/containerd/api/services/introspection/v1" namespacesapi "github.com/containerd/containerd/api/services/namespaces/v1" snapshotsapi "github.com/containerd/containerd/api/services/snapshots/v1" "github.com/containerd/containerd/api/services/tasks/v1" versionservice "github.com/containerd/containerd/api/services/version/v1" "github.com/containerd/containerd/containers" "github.com/containerd/containerd/content" "github.com/containerd/containerd/dialer" "github.com/containerd/containerd/errdefs" "github.com/containerd/containerd/images" "github.com/containerd/containerd/namespaces" "github.com/containerd/containerd/platforms" "github.com/containerd/containerd/plugin" "github.com/containerd/containerd/remotes" "github.com/containerd/containerd/remotes/docker" "github.com/containerd/containerd/remotes/docker/schema1" "github.com/containerd/containerd/snapshots" "github.com/containerd/typeurl" ptypes "github.com/gogo/protobuf/types" ocispec "github.com/opencontainers/image-spec/specs-go/v1" specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "google.golang.org/grpc" "google.golang.org/grpc/health/grpc_health_v1" ) func init() { const prefix = "types.containerd.io" // register TypeUrls for commonly marshaled external types major := strconv.Itoa(specs.VersionMajor) typeurl.Register(&specs.Spec{}, prefix, "opencontainers/runtime-spec", major, "Spec") typeurl.Register(&specs.Process{}, prefix, "opencontainers/runtime-spec", major, "Process") typeurl.Register(&specs.LinuxResources{}, prefix, "opencontainers/runtime-spec", major, "LinuxResources") typeurl.Register(&specs.WindowsResources{}, prefix, "opencontainers/runtime-spec", major, "WindowsResources") } // New returns a new containerd client that is connected to the containerd // instance provided by address func New(address string, opts ...ClientOpt) (*Client, error) { var copts clientOpts for _, o := range opts { if err := o(&copts); err != nil { return nil, err } } gopts := []grpc.DialOption{ grpc.WithBlock(), grpc.WithInsecure(), grpc.WithTimeout(60 * time.Second), grpc.FailOnNonTempDialError(true), grpc.WithBackoffMaxDelay(3 * time.Second), grpc.WithDialer(dialer.Dialer), } if len(copts.dialOptions) > 0 { gopts = copts.dialOptions } if copts.defaultns != "" { unary, stream := newNSInterceptors(copts.defaultns) gopts = append(gopts, grpc.WithUnaryInterceptor(unary), grpc.WithStreamInterceptor(stream), ) } connector := func() (*grpc.ClientConn, error) { conn, err := grpc.Dial(dialer.DialAddress(address), gopts...) if err != nil { return nil, errors.Wrapf(err, "failed to dial %q", address) } return conn, nil } conn, err := connector() if err != nil { return nil, err } return &Client{ conn: conn, connector: connector, runtime: fmt.Sprintf("%s.%s", plugin.RuntimePlugin, runtime.GOOS), }, nil } // NewWithConn returns a new containerd client that is connected to the containerd // instance provided by the connection func NewWithConn(conn *grpc.ClientConn, opts ...ClientOpt) (*Client, error) { return &Client{ conn: conn, runtime: fmt.Sprintf("%s.%s", plugin.RuntimePlugin, runtime.GOOS), }, nil } // Client is the client to interact with containerd and its various services // using a uniform interface type Client struct { conn *grpc.ClientConn runtime string connector func() (*grpc.ClientConn, error) } // Reconnect re-establishes the GRPC connection to the containerd daemon func (c *Client) Reconnect() error { if c.connector == nil { return errors.New("unable to reconnect to containerd, no connector available") } c.conn.Close() conn, err := c.connector() if err != nil { return err } c.conn = conn return nil } // IsServing returns true if the client can successfully connect to the // containerd daemon and the healthcheck service returns the SERVING // response. // This call will block if a transient error is encountered during // connection. A timeout can be set in the context to ensure it returns // early. func (c *Client) IsServing(ctx context.Context) (bool, error) { r, err := c.HealthService().Check(ctx, &grpc_health_v1.HealthCheckRequest{}, grpc.FailFast(false)) if err != nil { return false, err } return r.Status == grpc_health_v1.HealthCheckResponse_SERVING, nil } // Containers returns all containers created in containerd func (c *Client) Containers(ctx context.Context, filters ...string) ([]Container, error) { r, err := c.ContainerService().List(ctx, filters...) if err != nil { return nil, err } var out []Container for _, container := range r { out = append(out, containerFromRecord(c, container)) } return out, nil } // NewContainer will create a new container in container with the provided id // the id must be unique within the namespace func (c *Client) NewContainer(ctx context.Context, id string, opts ...NewContainerOpts) (Container, error) { ctx, done, err := c.WithLease(ctx) if err != nil { return nil, err } defer done() container := containers.Container{ ID: id, Runtime: containers.RuntimeInfo{ Name: c.runtime, }, } for _, o := range opts { if err := o(ctx, c, &container); err != nil { return nil, err } } r, err := c.ContainerService().Create(ctx, container) if err != nil { return nil, err } return containerFromRecord(c, r), nil } // LoadContainer loads an existing container from metadata func (c *Client) LoadContainer(ctx context.Context, id string) (Container, error) { r, err := c.ContainerService().Get(ctx, id) if err != nil { return nil, err } return containerFromRecord(c, r), nil } // RemoteContext is used to configure object resolutions and transfers with // remote content stores and image providers. type RemoteContext struct { // Resolver is used to resolve names to objects, fetchers, and pushers. // If no resolver is provided, defaults to Docker registry resolver. Resolver remotes.Resolver // Unpack is done after an image is pulled to extract into a snapshotter. // If an image is not unpacked on pull, it can be unpacked any time // afterwards. Unpacking is required to run an image. Unpack bool // Snapshotter used for unpacking Snapshotter string // Labels to be applied to the created image Labels map[string]string // BaseHandlers are a set of handlers which get are called on dispatch. // These handlers always get called before any operation specific // handlers. BaseHandlers []images.Handler // ConvertSchema1 is whether to convert Docker registry schema 1 // manifests. If this option is false then any image which resolves // to schema 1 will return an error since schema 1 is not supported. ConvertSchema1 bool } func defaultRemoteContext() *RemoteContext { return &RemoteContext{ Resolver: docker.NewResolver(docker.ResolverOptions{ Client: http.DefaultClient, }), Snapshotter: DefaultSnapshotter, } } // Pull downloads the provided content into containerd's content store func (c *Client) Pull(ctx context.Context, ref string, opts ...RemoteOpt) (Image, error) { pullCtx := defaultRemoteContext() for _, o := range opts { if err := o(c, pullCtx); err != nil { return nil, err } } store := c.ContentStore() ctx, done, err := c.WithLease(ctx) if err != nil { return nil, err } defer done() name, desc, err := pullCtx.Resolver.Resolve(ctx, ref) if err != nil { return nil, errors.Wrapf(err, "failed to resolve reference %q", ref) } fetcher, err := pullCtx.Resolver.Fetcher(ctx, name) if err != nil { return nil, errors.Wrapf(err, "failed to get fetcher for %q", name) } var ( schema1Converter *schema1.Converter handler images.Handler ) if desc.MediaType == images.MediaTypeDockerSchema1Manifest && pullCtx.ConvertSchema1 { schema1Converter = schema1.NewConverter(store, fetcher) handler = images.Handlers(append(pullCtx.BaseHandlers, schema1Converter)...) } else { // Get all the children for a descriptor childrenHandler := images.ChildrenHandler(store) // Set any children labels for that content childrenHandler = images.SetChildrenLabels(store, childrenHandler) // Filter the childen by the platform childrenHandler = images.FilterPlatform(platforms.Default(), childrenHandler) handler = images.Handlers(append(pullCtx.BaseHandlers, remotes.FetchHandler(store, fetcher), childrenHandler, )...) } if err := images.Dispatch(ctx, handler, desc); err != nil { return nil, err } if schema1Converter != nil { desc, err = schema1Converter.Convert(ctx) if err != nil { return nil, err } } imgrec := images.Image{ Name: name, Target: desc, Labels: pullCtx.Labels, } is := c.ImageService() if created, err := is.Create(ctx, imgrec); err != nil { if !errdefs.IsAlreadyExists(err) { return nil, err } updated, err := is.Update(ctx, imgrec) if err != nil { return nil, err } imgrec = updated } else { imgrec = created } img := &image{ client: c, i: imgrec, } if pullCtx.Unpack { if err := img.Unpack(ctx, pullCtx.Snapshotter); err != nil { errors.Wrapf(err, "failed to unpack image on snapshotter %s", pullCtx.Snapshotter) } } return img, nil } // Push uploads the provided content to a remote resource func (c *Client) Push(ctx context.Context, ref string, desc ocispec.Descriptor, opts ...RemoteOpt) error { pushCtx := defaultRemoteContext() for _, o := range opts { if err := o(c, pushCtx); err != nil { return err } } pusher, err := pushCtx.Resolver.Pusher(ctx, ref) if err != nil { return err } return remotes.PushContent(ctx, pusher, desc, c.ContentStore(), pushCtx.BaseHandlers...) } // GetImage returns an existing image func (c *Client) GetImage(ctx context.Context, ref string) (Image, error) { i, err := c.ImageService().Get(ctx, ref) if err != nil { return nil, err } return &image{ client: c, i: i, }, nil } // ListImages returns all existing images func (c *Client) ListImages(ctx context.Context, filters ...string) ([]Image, error) { imgs, err := c.ImageService().List(ctx, filters...) if err != nil { return nil, err } images := make([]Image, len(imgs)) for i, img := range imgs { images[i] = &image{ client: c, i: img, } } return images, nil } // Subscribe to events that match one or more of the provided filters. // // Callers should listen on both the envelope and errs channels. If the errs // channel returns nil or an error, the subscriber should terminate. // // The subscriber can stop receiving events by canceling the provided context. // The errs channel will be closed and return a nil error. func (c *Client) Subscribe(ctx context.Context, filters ...string) (ch <-chan *eventsapi.Envelope, errs <-chan error) { var ( evq = make(chan *eventsapi.Envelope) errq = make(chan error, 1) ) errs = errq ch = evq session, err := c.EventService().Subscribe(ctx, &eventsapi.SubscribeRequest{ Filters: filters, }) if err != nil { errq <- err close(errq) return } go func() { defer close(errq) for { ev, err := session.Recv() if err != nil { errq <- err return } select { case evq <- ev: case <-ctx.Done(): return } } }() return ch, errs } // Close closes the clients connection to containerd func (c *Client) Close() error { return c.conn.Close() } // NamespaceService returns the underlying Namespaces Store func (c *Client) NamespaceService() namespaces.Store { return NewNamespaceStoreFromClient(namespacesapi.NewNamespacesClient(c.conn)) } // ContainerService returns the underlying container Store func (c *Client) ContainerService() containers.Store { return NewRemoteContainerStore(containersapi.NewContainersClient(c.conn)) } // ContentStore returns the underlying content Store func (c *Client) ContentStore() content.Store { return NewContentStoreFromClient(contentapi.NewContentClient(c.conn)) } // SnapshotService returns the underlying snapshotter for the provided snapshotter name func (c *Client) SnapshotService(snapshotterName string) snapshots.Snapshotter { return NewSnapshotterFromClient(snapshotsapi.NewSnapshotsClient(c.conn), snapshotterName) } // TaskService returns the underlying TasksClient func (c *Client) TaskService() tasks.TasksClient { return tasks.NewTasksClient(c.conn) } // ImageService returns the underlying image Store func (c *Client) ImageService() images.Store { return NewImageStoreFromClient(imagesapi.NewImagesClient(c.conn)) } // DiffService returns the underlying Differ func (c *Client) DiffService() DiffService { return NewDiffServiceFromClient(diffapi.NewDiffClient(c.conn)) } // IntrospectionService returns the underlying Introspection Client func (c *Client) IntrospectionService() introspectionapi.IntrospectionClient { return introspectionapi.NewIntrospectionClient(c.conn) } // HealthService returns the underlying GRPC HealthClient func (c *Client) HealthService() grpc_health_v1.HealthClient { return grpc_health_v1.NewHealthClient(c.conn) } // EventService returns the underlying EventsClient func (c *Client) EventService() eventsapi.EventsClient { return eventsapi.NewEventsClient(c.conn) } // VersionService returns the underlying VersionClient func (c *Client) VersionService() versionservice.VersionClient { return versionservice.NewVersionClient(c.conn) } // Version of containerd type Version struct { // Version number Version string // Revision from git that was built Revision string } // Version returns the version of containerd that the client is connected to func (c *Client) Version(ctx context.Context) (Version, error) { response, err := c.VersionService().Version(ctx, &ptypes.Empty{}) if err != nil { return Version{}, err } return Version{ Version: response.Version, Revision: response.Revision, }, nil } type importOpts struct { } // ImportOpt allows the caller to specify import specific options type ImportOpt func(c *importOpts) error func resolveImportOpt(opts ...ImportOpt) (importOpts, error) { var iopts importOpts for _, o := range opts { if err := o(&iopts); err != nil { return iopts, err } } return iopts, nil } // Import imports an image from a Tar stream using reader. // Caller needs to specify importer. Future version may use oci.v1 as the default. // Note that unreferrenced blobs may be imported to the content store as well. func (c *Client) Import(ctx context.Context, importer images.Importer, reader io.Reader, opts ...ImportOpt) ([]Image, error) { _, err := resolveImportOpt(opts...) // unused now if err != nil { return nil, err } ctx, done, err := c.WithLease(ctx) if err != nil { return nil, err } defer done() imgrecs, err := importer.Import(ctx, c.ContentStore(), reader) if err != nil { // is.Update() is not called on error return nil, err } is := c.ImageService() var images []Image for _, imgrec := range imgrecs { if updated, err := is.Update(ctx, imgrec, "target"); err != nil { if !errdefs.IsNotFound(err) { return nil, err } created, err := is.Create(ctx, imgrec) if err != nil { return nil, err } imgrec = created } else { imgrec = updated } images = append(images, &image{ client: c, i: imgrec, }) } return images, nil } type exportOpts struct { } // ExportOpt allows the caller to specify export-specific options type ExportOpt func(c *exportOpts) error func resolveExportOpt(opts ...ExportOpt) (exportOpts, error) { var eopts exportOpts for _, o := range opts { if err := o(&eopts); err != nil { return eopts, err } } return eopts, nil } // Export exports an image to a Tar stream. // OCI format is used by default. // It is up to caller to put "org.opencontainers.image.ref.name" annotation to desc. // TODO(AkihiroSuda): support exporting multiple descriptors at once to a single archive stream. func (c *Client) Export(ctx context.Context, exporter images.Exporter, desc ocispec.Descriptor, opts ...ExportOpt) (io.ReadCloser, error) { _, err := resolveExportOpt(opts...) // unused now if err != nil { return nil, err } pr, pw := io.Pipe() go func() { pw.CloseWithError(exporter.Export(ctx, c.ContentStore(), desc, pw)) }() return pr, nil }
{ "content_hash": "9db49e03a8fcea52e603fc53928c036f", "timestamp": "", "source": "github", "line_count": 586, "max_line_length": 139, "avg_line_length": 28.585324232081913, "alnum_prop": 0.7179272879231091, "repo_name": "tophj-ibm/docker", "id": "2ac256dd9d6f226841ac73a226758c5d08162ff6", "size": "17345", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "vendor/github.com/containerd/containerd/client.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "81" }, { "name": "C", "bytes": "5027" }, { "name": "Go", "bytes": "7372490" }, { "name": "Makefile", "bytes": "12708" }, { "name": "PowerShell", "bytes": "23242" }, { "name": "Protocol Buffer", "bytes": "119" }, { "name": "Shell", "bytes": "507851" }, { "name": "Vim script", "bytes": "1350" } ], "symlink_target": "" }
On device unit tests ==================== This test app runs a set of unit tests, to help confirm that the python-for-android build is actually working properly. Also it's dynamic, because it will run one app or another depending on the supplied recipes at build time. It currently supports three app `modes`: - `kivy app` (with sdl2 bootstrap): if kivy in recipes - `flask app` (with webview bootstrap): if flask in recipes - `no gui`: if neither of above cases is taken The main tests are for the recipes built in the apk. Each module (or other tool) is at least imported and subject to some basic check. This test app can be build via `setup.py` or via buildozer. In both cases it will build a basic kivy app with a set of tests defined via the `requirements` keyword (specified at build time). In case that you build the `test app with no-gui`, the unittests results must be checked via command `adb logcat` or some logging apk (you may need root permissions in your device to use such app). Building the app with python-for-android ======================================== You can use the provided file `setup.py`. Check our `Makefile <https://github.com/kivy/python-for-android/blob/develop/Makefile>`__ to guess how to build the test app, or also you can look at `testing pull requests documentation <https://github.com/kivy/python-for-android/blob/develop/doc/source/testing_pull_requests.rst>`__, which describes some of the methods that you can use to build the test app. Building the app with buildozer =============================== This app can be built using buildozer, which it also serves as a test for:: $ buildozer android debug Install on an Android device:: $ adb install -r adb install -r bin/p4aunittests-0.1-debug.apk # or $ buildozer android deploy Run the app and check in logcat that all the tests pass:: $ adb logcat | grep python # or look up the adb syntax for this
{ "content_hash": "8921b1452e2dad75130af0f576988a6f", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 98, "avg_line_length": 37.84313725490196, "alnum_prop": 0.7196891191709844, "repo_name": "rnixx/python-for-android", "id": "6c0eb9626eeb033495124df872f41dbdc5751419", "size": "1930", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "testapps/on_device_unit_tests/README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "70942" }, { "name": "C++", "bytes": "491" }, { "name": "CMake", "bytes": "250" }, { "name": "CSS", "bytes": "3487" }, { "name": "Dockerfile", "bytes": "4440" }, { "name": "HTML", "bytes": "11631" }, { "name": "Java", "bytes": "517112" }, { "name": "Makefile", "bytes": "27307" }, { "name": "Python", "bytes": "1359684" }, { "name": "Shell", "bytes": "5340" } ], "symlink_target": "" }
class User { name: string = "Bob"; sayHello(): void { //console.log("Hello, " + this.name); } } class RegisteredUser extends User { name: string = "Frank"; constructor() { super(); // super call in a constructor super.sayHello(); // super call in a lambda in a constructor var x = () => super.sayHello(); } sayHello(): void { // super call in a method super.sayHello(); // super call in a lambda in a method var x = () => super.sayHello(); } } class RegisteredUser2 extends User { name: string = "Joe"; constructor() { super(); // super call in a nested lambda in a constructor var x = () => () => () => super.sayHello(); } sayHello(): void { // super call in a nested lambda in a method var x = () => () => () => super.sayHello(); } } class RegisteredUser3 extends User { name: string = "Sam"; constructor() { super(); // super property in a nested lambda in a constructor var superName = () => () => () => super.name; } sayHello(): void { // super property in a nested lambda in a method var superName = () => () => () => super.name; } } class RegisteredUser4 extends User { name: string = "Mark"; constructor() { super(); // super in a nested lambda in a constructor var x = () => () => super; } sayHello(): void { // super in a nested lambda in a method var x = () => () => super; } } //// [superInLambdas.js] var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var User = (function () { function User() { this.name = "Bob"; } User.prototype.sayHello = function () { //console.log("Hello, " + this.name); }; return User; }()); var RegisteredUser = (function (_super) { __extends(RegisteredUser, _super); function RegisteredUser() { var _this = _super.call(this) || this; _this.name = "Frank"; // super call in a constructor _super.prototype.sayHello.call(_this); // super call in a lambda in a constructor var x = function () { return _super.prototype.sayHello.call(_this); }; return _this; } RegisteredUser.prototype.sayHello = function () { var _this = this; // super call in a method _super.prototype.sayHello.call(this); // super call in a lambda in a method var x = function () { return _super.prototype.sayHello.call(_this); }; }; return RegisteredUser; }(User)); var RegisteredUser2 = (function (_super) { __extends(RegisteredUser2, _super); function RegisteredUser2() { var _this = _super.call(this) || this; _this.name = "Joe"; // super call in a nested lambda in a constructor var x = function () { return function () { return function () { return _super.prototype.sayHello.call(_this); }; }; }; return _this; } RegisteredUser2.prototype.sayHello = function () { var _this = this; // super call in a nested lambda in a method var x = function () { return function () { return function () { return _super.prototype.sayHello.call(_this); }; }; }; }; return RegisteredUser2; }(User)); var RegisteredUser3 = (function (_super) { __extends(RegisteredUser3, _super); function RegisteredUser3() { var _this = _super.call(this) || this; _this.name = "Sam"; // super property in a nested lambda in a constructor var superName = function () { return function () { return function () { return _super.prototype.name; }; }; }; return _this; } RegisteredUser3.prototype.sayHello = function () { var _this = this; // super property in a nested lambda in a method var superName = function () { return function () { return function () { return _super.prototype.name; }; }; }; }; return RegisteredUser3; }(User)); var RegisteredUser4 = (function (_super) { __extends(RegisteredUser4, _super); function RegisteredUser4() { var _this = _super.call(this) || this; _this.name = "Mark"; // super in a nested lambda in a constructor var x = function () { return function () { return _super.prototype.; }; }; return _this; } RegisteredUser4.prototype.sayHello = function () { var _this = this; // super in a nested lambda in a method var x = function () { return function () { return _super.prototype.; }; }; }; return RegisteredUser4; }(User));
{ "content_hash": "29900c646a5d602af38f736daba75e2b", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 126, "avg_line_length": 32.81456953642384, "alnum_prop": 0.551765893037336, "repo_name": "jeremyepling/TypeScript", "id": "73ca53c3b5cb9eb9c6df03e9bc38df725257bdd3", "size": "4981", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tests/baselines/reference/superInLambdas.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "945" }, { "name": "HTML", "bytes": "4843" }, { "name": "JavaScript", "bytes": "85" }, { "name": "PowerShell", "bytes": "2855" }, { "name": "TypeScript", "bytes": "23854064" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.storage.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.Get; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.Put; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.resourcemanager.storage.fluent.QueueServicesClient; import com.azure.resourcemanager.storage.fluent.models.ListQueueServicesInner; import com.azure.resourcemanager.storage.fluent.models.QueueServicePropertiesInner; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in QueueServicesClient. */ public final class QueueServicesClientImpl implements QueueServicesClient { /** The proxy service used to perform REST calls. */ private final QueueServicesService service; /** The service client containing this operation class. */ private final StorageManagementClientImpl client; /** * Initializes an instance of QueueServicesClientImpl. * * @param client the instance of the service client containing this operation class. */ QueueServicesClientImpl(StorageManagementClientImpl client) { this.service = RestProxy.create(QueueServicesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for StorageManagementClientQueueServices to be used by the proxy service * to perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "StorageManagementCli") private interface QueueServicesService { @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage" + "/storageAccounts/{accountName}/queueServices") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<ListQueueServicesInner>> list( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Put( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage" + "/storageAccounts/{accountName}/queueServices/{queueServiceName}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<QueueServicePropertiesInner>> setServiceProperties( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("queueServiceName") String queueServiceName, @BodyParam("application/json") QueueServicePropertiesInner parameters, @HeaderParam("Accept") String accept, Context context); @Headers({"Content-Type: application/json"}) @Get( "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage" + "/storageAccounts/{accountName}/queueServices/{queueServiceName}") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<QueueServicePropertiesInner>> getServiceProperties( @HostParam("$host") String endpoint, @PathParam("resourceGroupName") String resourceGroupName, @PathParam("accountName") String accountName, @QueryParam("api-version") String apiVersion, @PathParam("subscriptionId") String subscriptionId, @PathParam("queueServiceName") String queueServiceName, @HeaderParam("Accept") String accept, Context context); } /** * List all queue services for the storage account. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response body along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ListQueueServicesInner>> listWithResponseAsync(String resourceGroupName, String accountName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (accountName == null) { return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .list( this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * List all queue services for the storage account. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response body along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<ListQueueServicesInner>> listWithResponseAsync( String resourceGroupName, String accountName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (accountName == null) { return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .list( this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), this.client.getSubscriptionId(), accept, context); } /** * List all queue services for the storage account. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response body on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ListQueueServicesInner> listAsync(String resourceGroupName, String accountName) { return listWithResponseAsync(resourceGroupName, accountName).flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** * List all queue services for the storage account. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response. */ @ServiceMethod(returns = ReturnType.SINGLE) public ListQueueServicesInner list(String resourceGroupName, String accountName) { return listAsync(resourceGroupName, accountName).block(); } /** * List all queue services for the storage account. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the response body along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<ListQueueServicesInner> listWithResponse( String resourceGroupName, String accountName, Context context) { return listWithResponseAsync(resourceGroupName, accountName, context).block(); } /** * Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param parameters The properties of a storage account’s Queue service, only properties for Storage Analytics and * CORS (Cross-Origin Resource Sharing) rules can be specified. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service along with {@link Response} on successful completion * of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueServicePropertiesInner>> setServicePropertiesWithResponseAsync( String resourceGroupName, String accountName, QueueServicePropertiesInner parameters) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (accountName == null) { return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (parameters == null) { return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); } else { parameters.validate(); } final String queueServiceName = "default"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .setServiceProperties( this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), this.client.getSubscriptionId(), queueServiceName, parameters, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param parameters The properties of a storage account’s Queue service, only properties for Storage Analytics and * CORS (Cross-Origin Resource Sharing) rules can be specified. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service along with {@link Response} on successful completion * of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<QueueServicePropertiesInner>> setServicePropertiesWithResponseAsync( String resourceGroupName, String accountName, QueueServicePropertiesInner parameters, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (accountName == null) { return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (parameters == null) { return Mono.error(new IllegalArgumentException("Parameter parameters is required and cannot be null.")); } else { parameters.validate(); } final String queueServiceName = "default"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .setServiceProperties( this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), this.client.getSubscriptionId(), queueServiceName, parameters, accept, context); } /** * Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param parameters The properties of a storage account’s Queue service, only properties for Storage Analytics and * CORS (Cross-Origin Resource Sharing) rules can be specified. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueServicePropertiesInner> setServicePropertiesAsync( String resourceGroupName, String accountName, QueueServicePropertiesInner parameters) { return setServicePropertiesWithResponseAsync(resourceGroupName, accountName, parameters) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** * Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param parameters The properties of a storage account’s Queue service, only properties for Storage Analytics and * CORS (Cross-Origin Resource Sharing) rules can be specified. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service. */ @ServiceMethod(returns = ReturnType.SINGLE) public QueueServicePropertiesInner setServiceProperties( String resourceGroupName, String accountName, QueueServicePropertiesInner parameters) { return setServicePropertiesAsync(resourceGroupName, accountName, parameters).block(); } /** * Sets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param parameters The properties of a storage account’s Queue service, only properties for Storage Analytics and * CORS (Cross-Origin Resource Sharing) rules can be specified. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<QueueServicePropertiesInner> setServicePropertiesWithResponse( String resourceGroupName, String accountName, QueueServicePropertiesInner parameters, Context context) { return setServicePropertiesWithResponseAsync(resourceGroupName, accountName, parameters, context).block(); } /** * Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<QueueServicePropertiesInner>> getServicePropertiesWithResponseAsync( String resourceGroupName, String accountName) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (accountName == null) { return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String queueServiceName = "default"; final String accept = "application/json"; return FluxUtil .withContext( context -> service .getServiceProperties( this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), this.client.getSubscriptionId(), queueServiceName, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<QueueServicePropertiesInner>> getServicePropertiesWithResponseAsync( String resourceGroupName, String accountName, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (resourceGroupName == null) { return Mono .error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.")); } if (accountName == null) { return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } final String queueServiceName = "default"; final String accept = "application/json"; context = this.client.mergeContext(context); return service .getServiceProperties( this.client.getEndpoint(), resourceGroupName, accountName, this.client.getApiVersion(), this.client.getSubscriptionId(), queueServiceName, accept, context); } /** * Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<QueueServicePropertiesInner> getServicePropertiesAsync(String resourceGroupName, String accountName) { return getServicePropertiesWithResponseAsync(resourceGroupName, accountName) .flatMap(res -> Mono.justOrEmpty(res.getValue())); } /** * Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. */ @ServiceMethod(returns = ReturnType.SINGLE) public QueueServicePropertiesInner getServiceProperties(String resourceGroupName, String accountName) { return getServicePropertiesAsync(resourceGroupName, accountName).block(); } /** * Gets the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules. * * @param resourceGroupName The name of the resource group within the user's subscription. The name is case * insensitive. * @param accountName The name of the storage account within the specified resource group. Storage account names * must be between 3 and 24 characters in length and use numbers and lower-case letters only. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the properties of a storage account’s Queue service, including properties for Storage Analytics and CORS * (Cross-Origin Resource Sharing) rules along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<QueueServicePropertiesInner> getServicePropertiesWithResponse( String resourceGroupName, String accountName, Context context) { return getServicePropertiesWithResponseAsync(resourceGroupName, accountName, context).block(); } }
{ "content_hash": "ef967dc76c1b07403a16850e71360d62", "timestamp": "", "source": "github", "line_count": 608, "max_line_length": 119, "avg_line_length": 54.72861842105263, "alnum_prop": 0.67618332081142, "repo_name": "Azure/azure-sdk-for-java", "id": "759b710f9a57be54b168eadad3c4de4234c284bd", "size": "33325", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/resourcemanager/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/implementation/QueueServicesClientImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "8762" }, { "name": "Bicep", "bytes": "15055" }, { "name": "CSS", "bytes": "7676" }, { "name": "Dockerfile", "bytes": "2028" }, { "name": "Groovy", "bytes": "3237482" }, { "name": "HTML", "bytes": "42090" }, { "name": "Java", "bytes": "432409546" }, { "name": "JavaScript", "bytes": "36557" }, { "name": "Jupyter Notebook", "bytes": "95868" }, { "name": "PowerShell", "bytes": "737517" }, { "name": "Python", "bytes": "240542" }, { "name": "Scala", "bytes": "1143898" }, { "name": "Shell", "bytes": "18488" }, { "name": "XSLT", "bytes": "755" } ], "symlink_target": "" }
/** The modal for selecting an avatar @class AvatarSelectorController @extends Discourse.Controller @namespace Discourse @uses Discourse.ModalFunctionality @module Discourse **/ Discourse.AvatarSelectorController = Discourse.Controller.extend(Discourse.ModalFunctionality, { actions: { useUploadedAvatar: function() { this.set("use_uploaded_avatar", true); }, useGravatar: function() { this.set("use_uploaded_avatar", false); } }, avatarTemplate: function() { return this.get("use_uploaded_avatar") ? this.get("uploaded_avatar_template") : this.get("gravatar_template"); }.property("use_uploaded_avatar", "uploaded_avatar_template", "gravatar_template") });
{ "content_hash": "987909a7d4bb2bf5ae535b1cc78fa02e", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 114, "avg_line_length": 33.04761904761905, "alnum_prop": 0.7305475504322767, "repo_name": "tadp/learnswift", "id": "6c3d6d9ab65c08bacf1db5d4b3ae3effdd6cdb08", "size": "694", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "app/assets/javascripts/discourse/controllers/avatar_selector_controller.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "214967" }, { "name": "JavaScript", "bytes": "1096013" }, { "name": "Ruby", "bytes": "2151629" }, { "name": "Shell", "bytes": "2368" } ], "symlink_target": "" }
using System; using System.Globalization; using System.Windows.Data; namespace Ropufu.LeytePond.Converters { public class EqualityConverter : IValueConverter, IMultiValueConverter { /// <summary> /// Checks if <paramref name="value"/> equals <paramref name="parameter"/>. /// </summary> public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) { if (value.IsNull()) throw new ArgumentNullException(nameof(value)); if (parameter.IsNull()) throw new ArgumentNullException(nameof(parameter)); return value.Equals(parameter); } /// <summary> /// Checks if all passed <paramref name="values"/> are equal. /// </summary> public Object Convert(Object[] values, Type targetType, Object parameter, CultureInfo culture) { if (values.IsNull()) throw new ArgumentNullException(nameof(values)); foreach (var item in values) if (item.IsNull()) return false; var previous = values[0]; for (var i = 1; i < values.Length; ++i) { var next = values[i]; if (!next.Equals(previous)) return false; previous = next; } return true; } public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) => throw new NotSupportedException(); public Object[] ConvertBack(Object value, Type[] targetTypes, Object parameter, CultureInfo culture) => throw new NotSupportedException(); } }
{ "content_hash": "11f4f9286aaded6dbe0ec03bacd6c04c", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 146, "avg_line_length": 38.595238095238095, "alnum_prop": 0.6169031462060457, "repo_name": "ropufu/settlers_online", "id": "f39b74878daf8ca46fec9ac9f5cbf4a6ed7ed30e", "size": "1623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/LeytePond/Converters/EqualityConverter.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "684" }, { "name": "C#", "bytes": "284336" }, { "name": "C++", "bytes": "437094" }, { "name": "Makefile", "bytes": "801" } ], "symlink_target": "" }
(function (global, factory) { if (typeof define === "function" && define.amd) { define(['exports', './betamax-utils', './media-apis/html-video-api', './media-apis/html-video-hls-api', './media-apis/html-audio-api'], factory); } else if (typeof exports !== "undefined") { factory(exports, require('./betamax-utils'), require('./media-apis/html-video-api'), require('./media-apis/html-video-hls-api'), require('./media-apis/html-audio-api')); } else { var mod = { exports: {} }; factory(mod.exports, global.betamaxUtils, global.htmlVideoApi, global.htmlVideoHlsApi, global.htmlAudioApi); global.betamaxMediaApi = mod.exports; } })(this, function (exports, _betamaxUtils, _htmlVideoApi, _htmlVideoHlsApi, _htmlAudioApi) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BetaMaxMediaAPIFactory = exports.default = undefined; var _betamaxUtils2 = _interopRequireDefault(_betamaxUtils); var _htmlVideoApi2 = _interopRequireDefault(_htmlVideoApi); var _htmlVideoHlsApi2 = _interopRequireDefault(_htmlVideoHlsApi); var _htmlAudioApi2 = _interopRequireDefault(_htmlAudioApi); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var BetaMaxMediaAPIFactory = function BetaMaxMediaAPIFactory(_ref) { var $mediaObj = _ref.$mediaObj; var events = _ref.events; var mediaApi = void 0; var type = void 0; switch ($mediaObj.tagName.toLowerCase()) { case 'audio': type = 'audio'; break; default: type = 'video'; } if (_betamaxUtils2.default.isHlsSupported() && /\.m3u8$/.test($mediaObj.currentSrc)) { type = 'hls'; } switch (type) { case 'video': mediaApi = new _htmlVideoApi2.default({ $mediaObj: $mediaObj, events: events }); break; case 'audio': mediaApi = new _htmlAudioApi2.default({ $mediaObj: $mediaObj, events: events }); break; case 'hls': mediaApi = new _htmlVideoHlsApi2.default({ $mediaObj: $mediaObj, events: events, currentSrc: $mediaObj.currentSrc }); break; default: throw new Error("You must specify a type."); } return mediaApi; }; exports.default = BetaMaxMediaAPIFactory; exports.BetaMaxMediaAPIFactory = BetaMaxMediaAPIFactory; });
{ "content_hash": "cd39c07d378ca7adc9a9b20fa9ea94db", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 173, "avg_line_length": 32.56164383561644, "alnum_prop": 0.6495582667227597, "repo_name": "antoinegrant/betamax-core", "id": "47a134b51acbaf594a6ec41b6bdbe76e56b5f35f", "size": "2377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/betamax-media-api.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1086" }, { "name": "JavaScript", "bytes": "39897" } ], "symlink_target": "" }
module.exports = juice; /** * Module dependencies. */ var utils = require('./utils') , Selector = require('./selector') , Property = require('./property') , packageJson = require('../package') , fs = require('fs') , Batch = require('batch') , url = require('url') , superagent = require('superagent') , path = require('path') , assert = require('assert') , os = require('os') , styleSelector = new Selector('<style attribute>', [1, 0, 0, 0]) , importantSelector = new Selector('<!important>', [2, 0, 0, 0]) /** * Package version */ juice.version = packageJson.version; /** * Export Selector. */ juice.Selector = Selector; /** * Export Property. */ juice.Property = Property; /** * Export utils. */ juice.utils = require('./utils'); juice.ignoredPseudos = ['hover', 'active', 'focus', 'visited', 'link']; juice.juiceDocument = juiceDocument; juice.juiceContent = juiceContent; juice.juiceFile = juiceFile; juice.inlineDocument = inlineDocument; juice.inlineContent = inlineContent; function inlineDocument(document, css) { var rules = utils.parseCSS(css) , editedElements = [] rules.forEach(handleRule); editedElements.forEach(setStyleAttrs); function handleRule(rule) { var sel = rule[0] , style = rule[1] , selector = new Selector(sel) // skip rule if the selector has any pseudos which are ignored var parsedSelector = selector.parsed(); for (var i = 0; i < parsedSelector.length; ++i) { var subSel = parsedSelector[i]; if (subSel.pseudos) { for (var j = 0; j < subSel.pseudos.length; ++j) { var subSelPseudo = subSel.pseudos[j]; if (juice.ignoredPseudos.indexOf(subSelPseudo.name) >= 0) return; } } } var els; try { els = document.querySelectorAll(sel); } catch (err) { // skip invalid selector return; } utils.toArray(els).forEach(function (el) { if (!el.styleProps) { el.styleProps = {} // if the element has inline styles, fake selector with topmost specificity if (el.getAttribute('style')) { var cssText = '* { ' + el.getAttribute('style') + ' } ' addProps(utils.parseCSS(cssText)[0][1], styleSelector); } // store reference to an element we need to compile style="" attr for editedElements.push(el); } // go through the properties function addProps (style, selector) { for (var i = 0, l = style.length; i < l; i++) { var name = style[i] , value = style[name] , sel = style._importants[name] ? importantSelector : selector , prop = new Property(name, value, sel) , existing = el.styleProps[name] if (existing) { var winner = existing.compare(prop) , loser = prop === winner ? existing : prop if (winner === prop) el.styleProps[name] = prop; } else { el.styleProps[name] = prop; } } } addProps(style, selector); }); } function setStyleAttrs(el) { var style = ''; for (var i in el.styleProps) { style += el.styleProps[i].toString() + ' '; } el.setAttribute('style', style.trim()); } } function juiceDocument(document, options, callback) { assert.ok(options.url, "options.url is required"); options = getDefaultOptions(options); extractCssFromDocument(document, options, function(err, css) { if (err) { return callback(err); } css += "\n" + options.extraCss; inlineDocumentWithCb(document, css, callback); }); } function juiceContent(html, options, callback) { assert.ok(options.url, "options.url is required"); options = getDefaultOptions(options); // hack to force jsdom to see this argument as html content, not a url // or a filename. https://github.com/tmpvar/jsdom/issues/554 html += "\n"; var document = utils.jsdom(html); juiceDocument(document, options, function(err) { if (err) { // free the associated memory // with lazily created parentWindow try { document.parentWindow.close(); } catch (cleanupErr) {} callback(err); } else { var inner = document.innerHTML; // free the associated memory // with lazily created parentWindow try { document.parentWindow.close(); } catch (cleanupErr) {} callback(null, inner); } }); } function getDefaultOptions(options) { return utils.extend({ extraCss: "", applyStyleTags: true, removeStyleTags: true, applyLinkTags: true, removeLinkTags: true, }, options); } function juiceFile(filePath, options, callback) { // set default options fs.readFile(filePath, 'utf8', function(err, content) { if (err) return callback(err); options = getDefaultOptions(options); // so we can mutate options without guilt var slashes = os.platform() === 'win32' ? '\\\\' : '//'; options.url = options.url || ("file:" + slashes + path.resolve(process.cwd(), filePath)); juiceContent(content, options, callback); }); } function inlineContent(html, css) { var document = utils.jsdom(html); inlineDocument(document, css); var inner = document.innerHTML; // free the associated memory // with lazily created parentWindow try { document.parentWindow.close(); } catch (cleanupErr) {} return inner; } /** * Inlines the CSS specified by `css` into the `html` * * @param {String} html * @param {String} css * @api public */ function juice (arg1, arg2, arg3) { // legacy behavior if (typeof arg2 === 'string') return inlineContent(arg1, arg2); var options = arg3 ? arg2 : {}; var callback = arg3 ? arg3 : arg2; juiceFile(arg1, options, callback); } function inlineDocumentWithCb(document, css, callback) { try { inlineDocument(document, css); callback(); } catch (err) { callback(err); } } function getStylesData(document, options, callback) { var results = []; var stylesList = document.getElementsByTagName("style"); var i, styleDataList, styleData, styleElement; for (i = 0; i < stylesList.length; ++i) { styleElement = stylesList[i]; styleDataList = styleElement.childNodes; if (styleDataList.length !== 1) { callback(new Error("empty style element")); return; } styleData = styleDataList[0].data; if (options.applyStyleTags) results.push(styleData); if (options.removeStyleTags) styleElement.parentNode.removeChild(styleElement); } callback(null, results); } function getHrefContent(destHref, sourceHref, callback) { var resolvedUrl = url.resolve(sourceHref, destHref); var parsedUrl = url.parse(resolvedUrl); if (parsedUrl.protocol === 'file:') { fs.readFile(parsedUrl.pathname, 'utf8', callback); } else { getRemoteContent(resolvedUrl, callback); } } function getRemoteContent(remoteUrl, callback) { superagent.get(remoteUrl).buffer().end(function(err, resp) { if (err) { callback(err); } else if (resp.ok) { callback(null, resp.text); } else { callback(new Error("GET " + remoteUrl + " " + resp.status)); } }); } function getStylesheetList(document, options) { var results = []; var linkList = document.getElementsByTagName("link"); var link, i, j, attr, attrs; for (i = 0; i < linkList.length; ++i) { link = linkList[i]; attrs = {}; for (j = 0; j < link.attributes.length; ++j) { attr = link.attributes[j]; attrs[attr.name.toLowerCase()] = attr.value; } if (attrs.rel && attrs.rel.toLowerCase() === 'stylesheet') { if (options.applyLinkTags) results.push(attrs.href); if (options.removeLinkTags) link.parentNode.removeChild(link); } } return results; } function extractCssFromDocument(document, options, callback) { var batch = new Batch(); batch.push(function(callback) { getStylesData(document, options, callback); }); getStylesheetList(document, options).forEach(function(stylesheetHref) { batch.push(function(callback) { getHrefContent(stylesheetHref, options.url, callback); }); }); batch.end(function(err, results) { if (err) return callback(err); var stylesData = results.shift(); results.forEach(function(content) { stylesData.push(content); }); var css = stylesData.join("\n"); callback(null, css); }); }
{ "content_hash": "5cd4881bf14e62087cf27f0ada03ad60", "timestamp": "", "source": "github", "line_count": 310, "max_line_length": 93, "avg_line_length": 27.096774193548388, "alnum_prop": 0.6305952380952381, "repo_name": "Code4Maine/modeify", "id": "c879d0f4b5cc89b86b43cbed1452d4f35e70c8c4", "size": "8485", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/juice/lib/juice.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace DaoUtilsCore.log { public class LogManager { private static ILogManager _logManager; public static void RegisterLogManagerAdaptor(ILogManager logManager) { _logManager = logManager; } private static ILogManager ActiveLogManager() { return _logManager = _logManager ?? reflection.LogManagerFactory.GetLogManager() ?? console.LogManager.Instance; } public static ILog GetLogger(string name) { return ActiveLogManager().GetLogger(name); } public static ILog GetLogger(Type type) { return ActiveLogManager().GetLogger(type); } } }
{ "content_hash": "f1b31f064abf7475a4867679617e2894", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 124, "avg_line_length": 25.774193548387096, "alnum_prop": 0.6345431789737171, "repo_name": "KenMiles/DaoUtils", "id": "bcc791926489dcd14717904ea8279891d679440d", "size": "801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DaoUtils/DaoUtilsCore/log/LogManager.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "740954" } ], "symlink_target": "" }
package com.alibaba.jstorm.task.master.ctrlevent; import java.util.Map; import backtype.storm.task.TopologyContext; import com.alibaba.jstorm.client.ConfigExtension; import com.alibaba.jstorm.cluster.StormClusterState; import com.alibaba.jstorm.task.error.ErrorConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.jstorm.task.master.TMHandler; import com.alibaba.jstorm.task.master.TopologyMasterContext; import com.alibaba.jstorm.transactional.state.SnapshotStateMaster; import com.alibaba.jstorm.utils.JStormUtils; import backtype.storm.tuple.Tuple; public class CtrlEventDispatcher implements TMHandler { private static final Logger LOG = LoggerFactory.getLogger(CtrlEventDispatcher.class); private SnapshotStateMaster snapshotStateMaster; private TopologyMasterContext tmContext; private StormClusterState zkCluster; private TopologyContext context; @Override public void init(TopologyMasterContext tmContext) { this.tmContext = tmContext; this.zkCluster = tmContext.getZkCluster(); this.context = tmContext.getContext(); boolean isTransaction = JStormUtils.parseBoolean(tmContext.getConf().get(ConfigExtension.TRANSACTION_TOPOLOGY), false); if (isTransaction) this.snapshotStateMaster = new SnapshotStateMaster(tmContext.getContext(), tmContext.getCollector()); } @Override public void process(Object event) throws Exception { if (event instanceof UpdateConfigEvent) { update(((UpdateConfigEvent) event).getConf()); return; } Tuple input = (Tuple) event; TopoMasterCtrlEvent ctlEvent = (TopoMasterCtrlEvent) input.getValues().get(0); if (ctlEvent != null) { if (ctlEvent.isTransactionEvent()) { snapshotStateMaster.process(input); } else { String errorInfo = "Received unexpected control event, {}" + event.toString(); LOG.warn(errorInfo); zkCluster.report_task_error(context.getTopologyId(), context.getThisTaskId(), errorInfo, ErrorConstants.WARN, ErrorConstants.CODE_USER); } } } public void update(Map conf) { LOG.info("Topology master received new conf:" + conf); tmContext.getConf().putAll(conf); } @Override public void cleanup() { if (snapshotStateMaster != null) snapshotStateMaster.close(); } }
{ "content_hash": "7842f47d1a3423dac78c844e5753415b", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 127, "avg_line_length": 34.81944444444444, "alnum_prop": 0.6940566414040686, "repo_name": "alibaba/jstorm", "id": "a5712873a3a514ffc43f18a0751453fef8bb0949", "size": "3309", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "jstorm-core/src/main/java/com/alibaba/jstorm/task/master/ctrlevent/CtrlEventDispatcher.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "16192" }, { "name": "Java", "bytes": "10749345" }, { "name": "JavaScript", "bytes": "29378" }, { "name": "Python", "bytes": "75887" }, { "name": "Shell", "bytes": "11354" }, { "name": "Thrift", "bytes": "16663" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</Pattern> </layout> </appender> <logger name="io.redbarn" level="info" additivity="false"> <appender-ref ref="STDOUT" /> </logger> <root level="error"> <appender-ref ref="STDOUT" /> </root> </configuration>
{ "content_hash": "4dbcca988035a469d0dec005ccb8f07d", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 87, "avg_line_length": 30.647058823529413, "alnum_prop": 0.6065259117082533, "repo_name": "redbarn-io/redbarn", "id": "3464b94b0575236023db0060997a942649e60c96", "size": "521", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/resources/logback.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "258914" }, { "name": "Java", "bytes": "29129" }, { "name": "JavaScript", "bytes": "617497" } ], "symlink_target": "" }
It's important to inform the contest role-takers and contestants about the rules of the contest so that a speech contest can be effectively and professionally conducted. The contest briefing is booked for this purpose and usually is held half a week before the actual contest. Contest chair is the responsible person to give the briefing. #### Contestant * Arrive 10 minutes before contest starts to submit contestant form and draw sequence * The formality of the table topic contest (one by one, first one draw the topic) * Secure qualification criteria: timing, originality, eligibility * Know judging criteria -> provide the judging criteria printing for early reading / study * Useful to ask feedbacks / bring manual to fill a project #### Contest Timer * Two timers working together, sitting in the center of the 1st row * Hold the card until the next card is coming * No "Ding" or additional reminder for the time-up * Help to control the time of silence * Record the timing result into the timer's sheet #### Ballot Counter * Two ballot counter working together, sitting close to the judges area * In the end of each contest, collect the ballots from voting judges * Calculate the ranking during the break and interview time (in the quiet room) * Do the caculation and record the result into the counter's tally sheet #### SAA * Collect all the needed material from contest chair and put them to the room * Meeting room preparation and member check-in * Put the big white board in the center of the room and prepare mark pens * Pickup the external judges * Prepare, print and distribute the feedback forms to judges and audiences * One of the SAAs sits close to the door. Secure the door and no one is allowed to go in / out when contestant is giving the speech * Accompany guests to go out during the break * Accompany table topic contestants to wait outside and keep their mobile-phone until they are invited
{ "content_hash": "6cd2a00633a066d95ea9a01a24628f25", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 338, "avg_line_length": 62, "alnum_prop": 0.7861602497398543, "repo_name": "eshtmc/eshtmc", "id": "d8da71813bb65caccce801485bb30fefe8f115ac", "size": "1942", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/leadership/experience/speech contest/spring/briefing.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "12352" }, { "name": "HTML", "bytes": "1903517" }, { "name": "PHP", "bytes": "132678" } ], "symlink_target": "" }
/* * 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 io.prestosql.plugin.mysql; import io.prestosql.testing.QueryRunner; import static io.prestosql.plugin.mysql.MySqlQueryRunner.createMySqlQueryRunner; import static io.prestosql.tpch.TpchTable.CUSTOMER; import static io.prestosql.tpch.TpchTable.NATION; import static io.prestosql.tpch.TpchTable.ORDERS; import static io.prestosql.tpch.TpchTable.REGION; public class TestGlobalTransactionMySqlIntegrationSmokeTest extends BaseMySqlIntegrationSmokeTest { @Override protected QueryRunner createQueryRunner() throws Exception { mysqlServer = new TestingMySqlServer(true); return createMySqlQueryRunner(mysqlServer, CUSTOMER, NATION, ORDERS, REGION); } }
{ "content_hash": "5ef9b30acc7ddfa3f665be63cc7d257c", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 85, "avg_line_length": 37.44117647058823, "alnum_prop": 0.7666928515318147, "repo_name": "treasure-data/presto", "id": "4ea05e14f9437a266c09bdb8028f351124f0ec9f", "size": "1273", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "presto-mysql/src/test/java/io/prestosql/plugin/mysql/TestGlobalTransactionMySqlIntegrationSmokeTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "30916" }, { "name": "CSS", "bytes": "17830" }, { "name": "Dockerfile", "bytes": "1490" }, { "name": "Groovy", "bytes": "1547" }, { "name": "HTML", "bytes": "24210" }, { "name": "Java", "bytes": "42427369" }, { "name": "JavaScript", "bytes": "219883" }, { "name": "PLSQL", "bytes": "85" }, { "name": "Python", "bytes": "9315" }, { "name": "Ruby", "bytes": "4592" }, { "name": "Shell", "bytes": "33906" }, { "name": "Thrift", "bytes": "12598" } ], "symlink_target": "" }
"""Support for ANEL PwrCtrl switches.""" from datetime import timedelta import logging from anel_pwrctrl import DeviceMaster import voluptuous as vol from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchEntity from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) CONF_PORT_RECV = "port_recv" CONF_PORT_SEND = "port_send" MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_PORT_RECV): cv.port, vol.Required(CONF_PORT_SEND): cv.port, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_HOST): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up PwrCtrl devices/switches.""" host = config.get(CONF_HOST) username = config[CONF_USERNAME] password = config[CONF_PASSWORD] port_recv = config[CONF_PORT_RECV] port_send = config[CONF_PORT_SEND] try: master = DeviceMaster( username=username, password=password, read_port=port_send, write_port=port_recv, ) master.query(ip_addr=host) except OSError as ex: _LOGGER.error("Unable to discover PwrCtrl device: %s", str(ex)) return False devices = [] for device in master.devices.values(): parent_device = PwrCtrlDevice(device) devices.extend( PwrCtrlSwitch(switch, parent_device) for switch in device.switches.values() ) add_entities(devices) class PwrCtrlSwitch(SwitchEntity): """Representation of a PwrCtrl switch.""" def __init__(self, port, parent_device): """Initialize the PwrCtrl switch.""" self._port = port self._parent_device = parent_device @property def unique_id(self): """Return the unique ID of the device.""" return f"{self._port.device.host}-{self._port.get_index()}" @property def name(self): """Return the name of the device.""" return self._port.label @property def is_on(self): """Return true if the device is on.""" return self._port.get_state() def update(self): """Trigger update for all switches on the parent device.""" self._parent_device.update() def turn_on(self, **kwargs): """Turn the switch on.""" self._port.on() def turn_off(self, **kwargs): """Turn the switch off.""" self._port.off() class PwrCtrlDevice: """Device representation for per device throttling.""" def __init__(self, device): """Initialize the PwrCtrl device.""" self._device = device @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update the device and all its switches.""" self._device.update()
{ "content_hash": "a020d6178cee7095be6eb956aa482a71", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 87, "avg_line_length": 28.08411214953271, "alnum_prop": 0.6369384359400998, "repo_name": "sdague/home-assistant", "id": "0669a3bb6c6a4fa79dfa225f47b60cd25a68711c", "size": "3005", "binary": false, "copies": "10", "ref": "refs/heads/dev", "path": "homeassistant/components/anel_pwrctrl/switch.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1488" }, { "name": "Python", "bytes": "27869189" }, { "name": "Shell", "bytes": "4528" } ], "symlink_target": "" }
// Version: $Id$ // // // Commentary: // // // Change Log: // // // Code: #include "dtkAbstractTrimLoopData.h" #include "dtkContinuousGeometry.h" /*! \class dtkAbstractTrimLoopData \inmodule dtkContinuousGeometry \brief dtkAbstractTrimLoopData is the data container for trim loop It cannot be instanciated on its own. It is to be inherited from the classes acting as plugins. For more information : dtkPluginsContinuousGeometry. In pratice, the client code will instanciate \l dtkTrimLoop. Check \l dtkTrimLoop for more information. */ /*! \fn dtkAbstractTrimLoopData::type(void) const Returns the type of the trim loop, it can either be dtkContinuousGeometryEnums::TrimLoopType::outer, dtkContinuousGeometryEnums::TrimLoopType::inner or dtkContinuousGeometryEnums::TrimLoopType::unknown. */ /*! \fn dtkAbstractTrimLoopData::setType(dtkContinuousGeometryEnums::TrimLoopType p_type) const Sets the type of the trim loop. \a p_type : type of the trim loop, it can be dtkContinuousGeometryEnums::TrimLoopType::outer, dtkContinuousGeometryEnums::TrimLoopType::inner or dtkContinuousGeometryEnums::TrimLoopType::unknown */ /*! \fn dtkAbstractTrimLoopData::isPointCulled(dtkContinuousGeometryPrimitives::Point_2 p_point) const Returns true if \a p_point is culled by the trim loop. \a p_point : point to check if culled or not */ /*! \fn dtkAbstractTrimLoopData::toPolyline(std::list< dtkContinuousGeometryPrimitives::Point_2 >& r_polyline, double p_discretisation_length) const Stores in \a r_polyline a polyline representation of the trim loop with regard to the length of discretisation (\a p_discretisation_length), returns true if successfull, else returns false. \a r_polyline : list in which the dtkContinuousGeometryPrimitives::Point_2 will be added as polyline representation of the curve \a p_discretisation_length : length in parameter space between two samples */ /*! \fn dtkAbstractTrimLoopData::toPolylineApprox(std::list< dtkContinuousGeometryPrimitives::Point_2 >& r_polyline, double p_approximation) const Stores in \a r_polyline a polyline representation of the trim loop with regard to an approximation distance to the curve(\a p_approximation), returns true if successfull, else returns false. \a r_polyline : list in which the dtkContinuousGeometryPrimitives::Point_2 will be added as polyline representation of the curve \a p_approximation : maximal tolerated distance from the polygonalization to the trim loop */ /*! \fn dtkAbstractTrimLoopData::isValid(void) const Returns true if the all the trims of the trim loop are connected, else returns false. */ /*! \fn dtkAbstractTrimLoopData::aabb(double* r_aabb) const Writes in \a r_aabb the [xmin, ymin, zmin, xmax, ymax, zmax] coordinates. \a r_aabb : array of size 6 to store the limits coordinates */ /*! \fn dtkAbstractTrimLoopData::clone(void) const Clone */ // ///////////////////////////////////////////////////////////////// // Register to dtkContinuousGeometry layer // ///////////////////////////////////////////////////////////////// namespace dtkContinuousGeometry { DTK_DEFINE_CONCEPT(dtkAbstractTrimLoopData, abstractTrimLoopData, dtkContinuousGeometry); } // // dtkAbstractTrimLoopData.cpp ends here
{ "content_hash": "ada52704f4dce6ee17d53c8d68b630ab", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 204, "avg_line_length": 38.27058823529412, "alnum_prop": 0.7433138641254227, "repo_name": "d-tk/dtk-continuous-geometry", "id": "97e11e59e3862659acc9fa23a8947470dfb55b58", "size": "3253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/dtkContinuousGeometryCore/dtkAbstractTrimLoopData.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "392112" }, { "name": "CMake", "bytes": "27479" } ], "symlink_target": "" }
@implementation UAEC2GetConsoleOutputResponse @synthesize instanceID=_instanceID, timestamp=_timestamp, output=_output; - (id)init { if (self = [super init]) { [self UA_addDecodeBase64AdditionalAccessorForSelector:@selector(decodedOutput) propertyName:@"output"]; [self UA_addEncodeBase64AdditionalAccessorForSelector:@selector(setDecodedOutput:) propertyName:@"output"]; } return self; } + (NSString *)XPathPrefix { return @"./ec2:GetConsoleOutputResponse/"; } + (NSDictionary *)XMLKeyPathsByPropertyKey { // Start with super's key paths (if there are any) NSMutableDictionary *keyPaths = [[UAEC2Response XMLKeyPathsByPropertyKey] mutableCopy]; [keyPaths addEntriesFromDictionary: @{ @"instanceID": @"ec2:instanceId", @"timestamp": @"ec2:timestamp", @"output": @"ec2:output", @"decodedOutput": [NSNull null] }]; return [keyPaths copy]; } @end #pragma clang diagnostic pop
{ "content_hash": "ffcd022f5c2ba3b1ff6fdf798c5c7344", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 109, "avg_line_length": 24.435897435897434, "alnum_prop": 0.7061909758656874, "repo_name": "unsignedapps/ua-aws-sdk-ios", "id": "31c2a1c07c1eee0a05524301d881ded578d3d13b", "size": "1272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AWS iOS SDK/EC2/Responses/UAEC2GetConsoleOutputResponse.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "42359" }, { "name": "Objective-C", "bytes": "4812683" }, { "name": "Ruby", "bytes": "1520" } ], "symlink_target": "" }
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.win; import com.intellij.ide.RecentProjectListActionProvider; import com.intellij.ide.ReopenProjectAction; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.Strings; import com.intellij.openapi.wm.impl.SystemDock; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.SystemDependent; import org.jetbrains.annotations.SystemIndependent; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * @author Denis Fokin * @author Nikita Provotorov */ public final class WinDockDelegate implements SystemDock.Delegate { public static @Nullable WinDockDelegate getInstance() { return instance; } @Override public void updateRecentProjectsMenu() { final var stackTraceHolder = new Throwable("Asynchronously launched from here"); ForkJoinPool.commonPool().execute(() -> { try { final var wsi = wsiFuture.get(30, TimeUnit.SECONDS); if (wsi == null) { return; } final List<AnAction> recentProjectActions = RecentProjectListActionProvider.getInstance().getActions(false); final @NotNull JumpTask @NotNull [] jumpTasks = convertToJumpTasks(recentProjectActions); wsi.postShellTask((final @NotNull WinShellIntegration.ShellContext ctx) -> { ctx.clearRecentTasksList(); ctx.setRecentTasksList(jumpTasks); }).get(); } catch (final InterruptedException e) { e.addSuppressed(stackTraceHolder); LOG.warn(e); } catch (final Throwable e) { e.addSuppressed(stackTraceHolder); LOG.error(e); } }); } private WinDockDelegate(final @NotNull Future<@Nullable WinShellIntegration> wsiFuture) { this.wsiFuture = wsiFuture; } private static @NotNull JumpTask @NotNull [] convertToJumpTasks(final @NotNull List<AnAction> actions) { final String launcherFileName = ApplicationNamesInfo.getInstance().getScriptName() + "64.exe"; final String launcherPath = Paths.get(PathManager.getBinPath(), launcherFileName).toString(); final @NotNull JumpTask @NotNull [] result = new JumpTask[actions.size()]; int i = 0; for (final var action : actions) { if (!(action instanceof ReopenProjectAction)) { LOG.debug("Failed to convert an action \"" + action + "\" to Jump Task: the action is not ReopenProjectAction"); continue; } final ReopenProjectAction reopenProjectAction = (ReopenProjectAction)action; final @SystemIndependent String projectPath = reopenProjectAction.getProjectPath(); final @SystemDependent String projectPathSystem = PathUtil.toSystemDependentName(projectPath); if (Strings.isEmptyOrSpaces(projectPathSystem)) { LOG.debug("Failed to convert a ReopenProjectAction \"" + reopenProjectAction + "\" to Jump Task: path to the project is empty (\"" + projectPathSystem + "\")"); continue; } final @NotNull String taskTitle; final @NotNull String taskTooltip; { final @Nullable String presentationText; final @Nullable String projectName; if (!Strings.isEmptyOrSpaces(presentationText = reopenProjectAction.getTemplatePresentation().getText())) { taskTitle = presentationText; taskTooltip = presentationText + " (" + projectPathSystem + ")"; } else if (!Strings.isEmptyOrSpaces(projectName = reopenProjectAction.getProjectNameToDisplay())) { taskTitle = projectName; taskTooltip = projectName + " (" + projectPathSystem + ")"; } else { taskTitle = projectPathSystem; taskTooltip = projectPathSystem; } } final String taskArgs = "\"" + projectPathSystem + "\""; result[i++] = new JumpTask(taskTitle, launcherPath, taskArgs, taskTooltip); } if (i < result.length) { return Arrays.copyOf(result, i); } return result; } private final @NotNull Future<@Nullable WinShellIntegration> wsiFuture; private static final Logger LOG = Logger.getInstance(WinDockDelegate.class); private static final @Nullable WinDockDelegate instance; static { final var stackTraceHolder = new Throwable("Asynchronously launched from here"); // Not AppExecutorUtil.getAppExecutorService() for class loading optimization final @NotNull Future<@Nullable WinShellIntegration> wsiFuture = ForkJoinPool.commonPool().submit(() -> { try { if (!Registry.is("windows.jumplist")) { return null; } return WinShellIntegration.getInstance(); } catch (final Throwable err) { err.addSuppressed(stackTraceHolder); LOG.error("Failed to initialize com.intellij.ui.win.WinShellIntegration instance", err); return null; } }); instance = new WinDockDelegate(wsiFuture); } }
{ "content_hash": "1b7e029076e0cb6c28a96f035e7624a5", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 158, "avg_line_length": 35.62820512820513, "alnum_prop": 0.6928751349406261, "repo_name": "GunoH/intellij-community", "id": "17f0d612673abd0ee72d4f8f26017bda1c851453", "size": "5558", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "platform/platform-impl/src/com/intellij/ui/win/WinDockDelegate.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.hadoop.mapreduce.lib.map; import org.apache.hadoop.util.ReflectionUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.MapContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.StatusReporter; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.task.MapContextImpl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Multithreaded implementation for @link org.apache.hadoop.mapreduce.Mapper. * <p> * It can be used instead of the default implementation, * @link org.apache.hadoop.mapred.MapRunner, when the Map operation is not CPU * bound in order to improve throughput. * <p> * Mapper implementations using this MapRunnable must be thread-safe. * <p> * The Map-Reduce job has to be configured with the mapper to use via * {@link #setMapperClass(Configuration, Class)} and * the number of thread the thread-pool can use with the * {@link #getNumberOfThreads(Configuration) method. The default * value is 10 threads. * <p> */ public class MultithreadedMapper<K1, V1, K2, V2> extends Mapper<K1, V1, K2, V2> { private static final Log LOG = LogFactory.getLog(MultithreadedMapper.class); private Class<? extends Mapper<K1,V1,K2,V2>> mapClass; private Context outer; private List<MapRunner> runners; /** * The number of threads in the thread pool that will run the map function. * @param job the job * @return the number of threads */ public static int getNumberOfThreads(JobContext job) { return job.getConfiguration(). getInt("mapred.map.multithreadedrunner.threads", 10); } /** * Set the number of threads in the pool for running maps. * @param job the job to modify * @param threads the new number of threads */ public static void setNumberOfThreads(Job job, int threads) { job.getConfiguration().setInt("mapred.map.multithreadedrunner.threads", threads); } /** * Get the application's mapper class. * @param <K1> the map's input key type * @param <V1> the map's input value type * @param <K2> the map's output key type * @param <V2> the map's output value type * @param job the job * @return the mapper class to run */ @SuppressWarnings("unchecked") public static <K1,V1,K2,V2> Class<Mapper<K1,V1,K2,V2>> getMapperClass(JobContext job) { return (Class<Mapper<K1,V1,K2,V2>>) job.getConfiguration().getClass("mapred.map.multithreadedrunner.class", Mapper.class); } /** * Set the application's mapper class. * @param <K1> the map input key type * @param <V1> the map input value type * @param <K2> the map output key type * @param <V2> the map output value type * @param job the job to modify * @param cls the class to use as the mapper */ public static <K1,V1,K2,V2> void setMapperClass(Job job, Class<? extends Mapper<K1,V1,K2,V2>> cls) { if (MultithreadedMapper.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("Can't have recursive " + "MultithreadedMapper instances."); } job.getConfiguration().setClass("mapred.map.multithreadedrunner.class", cls, Mapper.class); } /** * Run the application's maps using a thread pool. */ @Override public void run(Context context) throws IOException, InterruptedException { outer = context; int numberOfThreads = getNumberOfThreads(context); mapClass = getMapperClass(context); if (LOG.isDebugEnabled()) { LOG.debug("Configuring multithread runner to use " + numberOfThreads + " threads"); } runners = new ArrayList<MapRunner>(numberOfThreads); for(int i=0; i < numberOfThreads; ++i) { MapRunner thread = new MapRunner(context); thread.start(); runners.add(i, thread); } for(int i=0; i < numberOfThreads; ++i) { MapRunner thread = runners.get(i); thread.join(); Throwable th = thread.throwable; if (th != null) { if (th instanceof IOException) { throw (IOException) th; } else if (th instanceof InterruptedException) { throw (InterruptedException) th; } else { throw new RuntimeException(th); } } } } private class SubMapRecordReader extends RecordReader<K1,V1> { private K1 key; private V1 value; private Configuration conf; @Override public void close() throws IOException { } @Override public float getProgress() throws IOException, InterruptedException { return 0; } @Override public void initialize(InputSplit split, TaskAttemptContext context ) throws IOException, InterruptedException { conf = context.getConfiguration(); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { synchronized (outer) { if (!outer.nextKeyValue()) { return false; } key = ReflectionUtils.copy(outer.getConfiguration(), outer.getCurrentKey(), key); value = ReflectionUtils.copy(conf, outer.getCurrentValue(), value); return true; } } public K1 getCurrentKey() { return key; } @Override public V1 getCurrentValue() { return value; } } private class SubMapRecordWriter extends RecordWriter<K2,V2> { @Override public void close(TaskAttemptContext context) throws IOException, InterruptedException { } @Override public void write(K2 key, V2 value) throws IOException, InterruptedException { synchronized (outer) { outer.write(key, value); } } } private class SubMapStatusReporter extends StatusReporter { @Override public Counter getCounter(Enum<?> name) { return outer.getCounter(name); } @Override public Counter getCounter(String group, String name) { return outer.getCounter(group, name); } @Override public void progress() { outer.progress(); } @Override public void setStatus(String status) { outer.setStatus(status); } } private class MapRunner extends Thread { private Mapper<K1,V1,K2,V2> mapper; private Context subcontext; private Throwable throwable; MapRunner(Context context) throws IOException, InterruptedException { mapper = ReflectionUtils.newInstance(mapClass, context.getConfiguration()); MapContext<K1, V1, K2, V2> mapContext = new MapContextImpl<K1, V1, K2, V2>(outer.getConfiguration(), outer.getTaskAttemptID(), new SubMapRecordReader(), new SubMapRecordWriter(), context.getOutputCommitter(), new SubMapStatusReporter(), outer.getInputSplit()); subcontext = new WrappedMapper<K1, V1, K2, V2>().getMapContext(mapContext); } public Throwable getThrowable() { return throwable; } @Override public void run() { try { mapper.run(subcontext); } catch (Throwable ie) { throwable = ie; } } } }
{ "content_hash": "8360267389e08c7852b2bd1493cbca1a", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 81, "avg_line_length": 31.212355212355213, "alnum_prop": 0.6275358733300347, "repo_name": "baishuo/hadoop-2.6.0-cdh5.4.7_baishuo", "id": "47f138e2578162d9fca5b88591c9bcc20ccb1121", "size": "8890", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "hadoop-mapreduce1-project/src/mapred/org/apache/hadoop/mapreduce/lib/map/MultithreadedMapper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "95943" }, { "name": "Batchfile", "bytes": "61977" }, { "name": "C", "bytes": "1726589" }, { "name": "C++", "bytes": "2124581" }, { "name": "CMake", "bytes": "55490" }, { "name": "CSS", "bytes": "52527" }, { "name": "HTML", "bytes": "2441733" }, { "name": "Java", "bytes": "58166152" }, { "name": "JavaScript", "bytes": "45743" }, { "name": "Makefile", "bytes": "7278" }, { "name": "Objective-C", "bytes": "118273" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "159384" }, { "name": "Protocol Buffer", "bytes": "218840" }, { "name": "Python", "bytes": "723512" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "443121" }, { "name": "Smalltalk", "bytes": "56562" }, { "name": "TeX", "bytes": "45082" }, { "name": "Thrift", "bytes": "3965" }, { "name": "XSLT", "bytes": "41310" } ], "symlink_target": "" }
To enable strict mode, simply pass in `strict: true` when creating a Vuex store: ``` js const store = new Vuex.Store({ // ... strict: true }) ``` In strict mode, whenever Vuex state is mutated outside of mutation handlers, an error will be thrown. This ensures that all state mutations can be explicitly tracked by debugging tools. ### Development vs. Production **Do not enable strict mode when deploying for production!** Strict mode runs a synchronous deep watcher on the state tree for detecting inappropriate mutations, and it can be quite expensive when you make large amount of mutations to the state. Make sure to turn it off in production to avoid the performance cost. Similar to plugins, we can let the build tools handle that: ``` js const store = new Vuex.Store({ // ... strict: process.env.NODE_ENV !== 'production' }) ```
{ "content_hash": "2e4922a6631edcde5801891f6aba4822", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 315, "avg_line_length": 37, "alnum_prop": 0.7403055229142186, "repo_name": "feng00001/teamProject", "id": "f75fb6decab1ad18d2bd1c52805ba3a8f2e89ac7", "size": "866", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "docs/en/strict.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9136" }, { "name": "HTML", "bytes": "30995" }, { "name": "JavaScript", "bytes": "141000" }, { "name": "Shell", "bytes": "489" }, { "name": "TypeScript", "bytes": "6407" }, { "name": "Vue", "bytes": "178896" } ], "symlink_target": "" }
package openblocks.common.item; import javax.annotation.Nullable; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.IItemPropertyGetter; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import openblocks.common.entity.EntityLuggage; import openmods.infobook.BookDocumentation; import openmods.inventory.GenericInventory; import openmods.utils.ItemUtils; @BookDocumentation(hasVideo = true) public class ItemLuggage extends Item { public ItemLuggage() { setMaxStackSize(1); addPropertyOverride(new ResourceLocation("inventory"), new IItemPropertyGetter() { @Override public float apply(ItemStack stack, @Nullable World worldIn, @Nullable EntityLivingBase entityIn) { return getInventorySize(stack); } }); } @Override public boolean hasEffect(ItemStack stack) { return getInventorySize(stack) > EntityLuggage.SIZE_NORMAL; } @Override public ActionResult<ItemStack> onItemRightClick(ItemStack itemStack, World world, EntityPlayer player, EnumHand hand) { if (!world.isRemote) { Vec3d vec3 = new Vec3d(player.posX, player.posY, player.posZ); Vec3d vec31 = player.getLook(1.0f); Vec3d vec32 = vec3.addVector(vec31.xCoord * 2.0f, vec31.yCoord * 2.0f, vec31.zCoord * 2.0f); EntityLuggage luggage = new EntityLuggage(world); luggage.setPositionAndRotation(0.5 + vec32.xCoord, vec3.yCoord, 0.5 + vec32.zCoord, 0, 0); luggage.setOwnerId(player.getGameProfile().getId()); luggage.restoreFromStack(itemStack); world.spawnEntityInWorld(luggage); itemStack.stackSize--; } return ActionResult.newResult(EnumActionResult.SUCCESS, itemStack); } private static int getInventorySize(ItemStack stack) { return ItemUtils.getItemTag(stack).getInteger(GenericInventory.TAG_SIZE); } }
{ "content_hash": "7ba84fbdf7af319fbd5df58503974d97", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 120, "avg_line_length": 33.83606557377049, "alnum_prop": 0.7834302325581395, "repo_name": "TheSilkMiner/OpenBlocks", "id": "b50131d3f8028e64c82b3bd4c458c3b93e0cd33a", "size": "2064", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/openblocks/common/item/ItemLuggage.java", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "1414" }, { "name": "Java", "bytes": "1212967" } ], "symlink_target": "" }
import IronCheckedElementBehavior from './iron-checked-element-behavior'; import layout from '../templates/components/paper-toggle-button'; export default IronCheckedElementBehavior.extend({ layout, tagName: 'paper-toggle-button' });
{ "content_hash": "992d4ce3ffa19615cd55eedb6500e78e", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 73, "avg_line_length": 34.142857142857146, "alnum_prop": 0.7907949790794979, "repo_name": "dunnkers/ember-polymer-paper", "id": "d67b9afad51afbd71730804d0edd0d1f35189552", "size": "239", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addon/components/paper-toggle-button.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1772" }, { "name": "HTML", "bytes": "11873" }, { "name": "JavaScript", "bytes": "25334" } ], "symlink_target": "" }
#import "EC2GroupIdentifier.h" @implementation EC2GroupIdentifier @synthesize groupName; @synthesize groupId; -(id)init { if (self = [super init]) { groupName = nil; groupId = nil; } return self; } -(NSString *)description { NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256]; [buffer appendString:@"{"]; [buffer appendString:[[[NSString alloc] initWithFormat:@"GroupName: %@,", groupName] autorelease]]; [buffer appendString:[[[NSString alloc] initWithFormat:@"GroupId: %@,", groupId] autorelease]]; [buffer appendString:[super description]]; [buffer appendString:@"}"]; return [buffer autorelease]; } -(void)dealloc { [groupName release]; [groupId release]; [super dealloc]; } @end
{ "content_hash": "06d768e77b2d1cfd7f6cc021cac740d8", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 103, "avg_line_length": 16.5625, "alnum_prop": 0.6515723270440251, "repo_name": "wallisch/aws-sdk-ios-v1", "id": "eabb62f1283851655d6b0602405540feb4708478", "size": "1379", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Amazon.EC2/Model/EC2GroupIdentifier.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "15339" }, { "name": "Objective-C", "bytes": "7696659" }, { "name": "Shell", "bytes": "3903" } ], "symlink_target": "" }
 #include <aws/directconnect/model/LoaContentType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace DirectConnect { namespace Model { namespace LoaContentTypeMapper { static const int application_pdf_HASH = HashingUtils::HashString("application/pdf"); LoaContentType GetLoaContentTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == application_pdf_HASH) { return LoaContentType::application_pdf; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<LoaContentType>(hashCode); } return LoaContentType::NOT_SET; } Aws::String GetNameForLoaContentType(LoaContentType enumValue) { switch(enumValue) { case LoaContentType::application_pdf: return "application/pdf"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace LoaContentTypeMapper } // namespace Model } // namespace DirectConnect } // namespace Aws
{ "content_hash": "462ae53c7525c05920ad1437cf64d4b2", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 92, "avg_line_length": 27.949152542372882, "alnum_prop": 0.6228016979987872, "repo_name": "ambasta/aws-sdk-cpp", "id": "1f125e6727fa55e407628e161b90d507f5533a41", "size": "2222", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-directconnect/source/model/LoaContentType.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2305" }, { "name": "C++", "bytes": "74273816" }, { "name": "CMake", "bytes": "412257" }, { "name": "Java", "bytes": "229873" }, { "name": "Python", "bytes": "62933" } ], "symlink_target": "" }
using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace Trippit.Controls { public sealed partial class MovableAppBarToggleButton : AppBarToggleButton, ISortableAppBarButton { public static readonly DependencyProperty PositionProperty = DependencyProperty.Register("Position", typeof(int), typeof(MovableAppBarToggleButton), new PropertyMetadata(0)); public int Position { get { return (int)GetValue(PositionProperty); } set { SetValue(PositionProperty, value); } } public static readonly DependencyProperty IsSecondaryCommandProperty = DependencyProperty.Register("IsSecondaryCommand", typeof(bool), typeof(MovableAppBarToggleButton), new PropertyMetadata(false, new PropertyChangedCallback(IsSecondaryCommandChanged))); private static void IsSecondaryCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MovableAppBarToggleButton _this = d as MovableAppBarToggleButton; if (_this == null) { return; } bool newIsSecondary = (bool)e.NewValue; if (newIsSecondary) { _this.Width = double.NaN; _this.HorizontalAlignment = HorizontalAlignment.Stretch; } else { _this.Width = 68; _this.HorizontalAlignment = HorizontalAlignment.Left; /* HACK: Force a binding update in case the button should NOT be enabled. * Reason: If a button is a SecondaryCommand, its IsEnabled is forcibly set * to false whenever the overflow panel is hidden. If we just move the button * from SecondaryCommands to PrimaryCommands, whatever voodoo magic the * CommandBar uses to set IsEnabled correctly never gets cast. So set it to IsEnabled, * refresh the DataContext, and hope that nobody has manually set IsEnabled=false.*/ _this.IsEnabled = true; var savedDataContext = _this.DataContext; _this.DataContext = null; _this.DataContext = savedDataContext; } } public bool IsSecondaryCommand { get { return (bool)GetValue(IsSecondaryCommandProperty); } set { SetValue(IsSecondaryCommandProperty, value); } } public MovableAppBarToggleButton() { this.InitializeComponent(); } public int CompareTo(ISortableAppBarButton other) { return this.Position.CompareTo(other.Position); } } }
{ "content_hash": "955639aac892eb82e7d1e9955f6d389e", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 138, "avg_line_length": 41.529411764705884, "alnum_prop": 0.6218130311614731, "repo_name": "pingzing/digi-transit-10", "id": "89020721210d67fe2330260bb49ac5554ca982b0", "size": "2826", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Trippit/Controls/MovableAppBarToggleButton.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "671016" } ], "symlink_target": "" }
import { CanActivate, ChangeDetectionStrategy, Component } from "../core"; @Component({ template: require("./search-parameters-list.component.html"), styles: [require("./search-parameters-list.component.css")], selector: "search-parameters-list", inputs: ['entities','edit','remove'], changeDetection: ChangeDetectionStrategy.OnPush }) export class SearchParametersListComponent { constructor() { } }
{ "content_hash": "dad1693b38a19d1575b6a6aa32253e4a", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 74, "avg_line_length": 35.666666666666664, "alnum_prop": 0.7149532710280374, "repo_name": "QuinntyneBrown/azure-search-getting-started", "id": "77c4a0797a33dfec6d49f631a1dc0178df560851", "size": "428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Chloe/wwwroot/search-parameters/search-parameters-list.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "536816" }, { "name": "CSS", "bytes": "21945" }, { "name": "HTML", "bytes": "105717" }, { "name": "JavaScript", "bytes": "140796" }, { "name": "TypeScript", "bytes": "626935" } ], "symlink_target": "" }
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.weblayer_private; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.RemoteException; import android.util.AndroidRuntimeException; import android.webkit.ValueCallback; import org.chromium.base.ContextUtils; import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.NativeMethods; import org.chromium.components.browser_ui.notifications.ChromeNotification; import org.chromium.components.browser_ui.notifications.NotificationManagerProxy; import org.chromium.components.browser_ui.notifications.NotificationManagerProxyImpl; import org.chromium.components.browser_ui.notifications.NotificationMetadata; import org.chromium.components.browser_ui.notifications.PendingIntentProvider; import org.chromium.components.browser_ui.notifications.channels.ChannelsInitializer; import org.chromium.components.webrtc.MediaCaptureNotificationUtil; import org.chromium.components.webrtc.MediaCaptureNotificationUtil.MediaType; import org.chromium.content_public.browser.WebContents; import org.chromium.weblayer_private.interfaces.IMediaCaptureCallbackClient; import org.chromium.weblayer_private.interfaces.ObjectWrapper; import java.util.HashSet; import java.util.Set; /** * A per-tab object that manages notifications for ongoing media capture streams * (microphone/camera). This object is created by {@link TabImpl} and creates and destroys its * native equivalent. */ @JNINamespace("weblayer") public class MediaStreamManager { private static final String WEBRTC_PREFIX = "org.chromium.weblayer.webrtc"; private static final String EXTRA_TAB_ID = WEBRTC_PREFIX + ".TAB_ID"; private static final String ACTIVATE_TAB_INTENT = WEBRTC_PREFIX + ".ACTIVATE_TAB"; private static final String AV_STREAM_TAG = WEBRTC_PREFIX + ".avstream"; /** * A key used in the app's shared preferences to track a set of active streaming notifications. * This is used to clear notifications that may have persisted across restarts due to a crash. * TODO(estade): remove this approach and simply iterate across all notifications via * {@link NotificationManager#getActiveNotifications} once the minimum API level is 23. */ private static final String PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS = WEBRTC_PREFIX + ".avstream_notifications"; private IMediaCaptureCallbackClient mClient; private TabImpl mTab; // The notification ID matches the tab ID, which uniquely identifies the notification when // paired with the tag. private int mNotificationId; // Pointer to the native MediaStreamManager. private long mNative; /** * @return a string that prefixes all intents that can be handled by {@link forwardIntent}. */ public static String getIntentPrefix() { return WEBRTC_PREFIX; } /** * Handles an intent coming from a media streaming notification. * @param intent the intent which was previously posted via {@link update}. */ public static void forwardIntent(Intent intent) { assert intent.getAction().equals(ACTIVATE_TAB_INTENT); int tabId = intent.getIntExtra(EXTRA_TAB_ID, -1); TabImpl tab = TabImpl.getTabById(tabId); if (tab == null) return; try { tab.getClient().bringTabToFront(); } catch (RemoteException e) { throw new AndroidRuntimeException(e); } } /** * To be called when WebLayer is started. Clears notifications that may have persisted from * before a crash. */ public static void onWebLayerInit() { SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); Set<String> staleNotificationIds = prefs.getStringSet(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS, null); if (staleNotificationIds == null) return; NotificationManagerProxy manager = getNotificationManager(); if (manager == null) return; for (String id : staleNotificationIds) { manager.cancel(AV_STREAM_TAG, Integer.parseInt(id)); } prefs.edit().remove(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS).apply(); } public MediaStreamManager(TabImpl tab) { mTab = tab; mNotificationId = tab.getId(); mNative = MediaStreamManagerJni.get().create(this, tab.getWebContents()); } public void destroy() { cancelNotification(); MediaStreamManagerJni.get().destroy(mNative); mNative = 0; mClient = null; } public void setClient(IMediaCaptureCallbackClient client) { mClient = client; } public void stopStreaming() { MediaStreamManagerJni.get().stopStreaming(mNative); } private void cancelNotification() { NotificationManagerProxy notificationManager = getNotificationManager(); if (notificationManager != null) { notificationManager.cancel(AV_STREAM_TAG, mNotificationId); } notifyClient(false, false); updateActiveNotifications(false); } private void notifyClient(boolean audio, boolean video) { if (mClient != null) { try { mClient.onMediaCaptureStateChanged(audio, video); } catch (RemoteException e) { throw new AndroidRuntimeException(e); } } } /** * Updates the list of active notifications stored in the SharedPrefences. * * @param active if true, then {@link mNotificationId} will be added to the list of active * notifications, otherwise it will be removed. */ private void updateActiveNotifications(boolean active) { SharedPreferences prefs = ContextUtils.getAppSharedPreferences(); Set<String> activeIds = new HashSet<String>( prefs.getStringSet(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS, new HashSet<String>())); if (active) { activeIds.add(Integer.toString(mNotificationId)); } else { activeIds.remove(Integer.toString(mNotificationId)); } prefs.edit() .putStringSet(PREF_ACTIVE_AV_STREAM_NOTIFICATION_IDS, activeIds.isEmpty() ? null : activeIds) .apply(); } @CalledByNative private void prepareToStream(boolean audio, boolean video, int requestId) throws RemoteException { if (mClient == null) { respondToStreamRequest(requestId, true); } else { mClient.onMediaCaptureRequested( audio, video, ObjectWrapper.wrap(new ValueCallback<Boolean>() { @Override public void onReceiveValue(Boolean allowed) { respondToStreamRequest(requestId, allowed.booleanValue()); } })); } } private void respondToStreamRequest(int requestId, boolean allow) { if (mNative == 0) return; MediaStreamManagerJni.get().onClientReadyToStream(mNative, requestId, allow); } /** * Called after the tab's media streaming state has changed. * * A notification should be shown (or updated) iff one of the parameters is true, otherwise * any existing notification will be removed. * * @param audio true if the tab is streaming audio. * @param video true if the tab is streaming video. */ @CalledByNative private void update(boolean audio, boolean video) { // The notification intent is not handled in the client prior to M84. if (WebLayerFactoryImpl.getClientMajorVersion() < 84) return; if (!audio && !video) { cancelNotification(); return; } Context appContext = ContextUtils.getApplicationContext(); Intent intent = WebLayerImpl.createIntent(); intent.putExtra(EXTRA_TAB_ID, mNotificationId); intent.setAction(ACTIVATE_TAB_INTENT); PendingIntentProvider contentIntent = PendingIntentProvider.getBroadcast(appContext, mNotificationId, intent, 0); int mediaType = audio && video ? MediaType.AUDIO_AND_VIDEO : audio ? MediaType.AUDIO_ONLY : MediaType.VIDEO_ONLY; NotificationManagerProxy notificationManagerProxy = getNotificationManager(); ChannelsInitializer channelsInitializer = new ChannelsInitializer(notificationManagerProxy, WebLayerNotificationChannels.getInstance(), appContext.getResources()); // TODO(crbug/1076098): don't pass a URL in incognito. ChromeNotification notification = MediaCaptureNotificationUtil.createNotification( new WebLayerNotificationBuilder(appContext, WebLayerNotificationChannels.ChannelId.WEBRTC_CAM_AND_MIC, channelsInitializer, new NotificationMetadata(0, AV_STREAM_TAG, mNotificationId)), mediaType, mTab.getWebContents().getVisibleUrl().getSpec(), WebLayerImpl.getClientApplicationName(), contentIntent, null /*stopIntent*/); notificationManagerProxy.notify(notification); updateActiveNotifications(true); notifyClient(audio, video); } private static NotificationManagerProxy getNotificationManager() { return new NotificationManagerProxyImpl(ContextUtils.getApplicationContext()); } @NativeMethods interface Natives { long create(MediaStreamManager caller, WebContents webContents); void destroy(long manager); void onClientReadyToStream(long nativeMediaStreamManager, int requestId, boolean allow); void stopStreaming(long nativeMediaStreamManager); } }
{ "content_hash": "51c8655fad227ce0b3da514599490cf6", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 99, "avg_line_length": 40.57831325301205, "alnum_prop": 0.683095803642122, "repo_name": "endlessm/chromium-browser", "id": "446af44ea47fb71ecb11112e6778bc1352193467", "size": "10104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "weblayer/browser/java/org/chromium/weblayer_private/MediaStreamManager.java", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#define C_LUCY_POLYQUERY #define C_LUCY_POLYCOMPILER #include "Lucy/Util/ToolSet.h" #include "Lucy/Search/PolyQuery.h" #include "Lucy/Index/DocVector.h" #include "Lucy/Index/Similarity.h" #include "Lucy/Plan/Schema.h" #include "Lucy/Search/Searcher.h" #include "Lucy/Search/Span.h" #include "Lucy/Store/InStream.h" #include "Lucy/Store/OutStream.h" #include "Lucy/Util/Freezer.h" PolyQuery* PolyQuery_init(PolyQuery *self, Vector *children) { const size_t num_kids = children ? Vec_Get_Size(children) : 0; Query_init((Query*)self, 1.0f); PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); ivars->children = Vec_new(num_kids); for (size_t i = 0; i < num_kids; i++) { PolyQuery_Add_Child(self, (Query*)Vec_Fetch(children, i)); } return self; } void PolyQuery_Destroy_IMP(PolyQuery *self) { PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); DECREF(ivars->children); SUPER_DESTROY(self, POLYQUERY); } void PolyQuery_Add_Child_IMP(PolyQuery *self, Query *query) { CERTIFY(query, QUERY); PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); Vec_Push(ivars->children, INCREF(query)); } void PolyQuery_Set_Children_IMP(PolyQuery *self, Vector *children) { PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); Vector *temp = ivars->children; ivars->children = (Vector*)INCREF(children); DECREF(temp); } Vector* PolyQuery_Get_Children_IMP(PolyQuery *self) { return PolyQuery_IVARS(self)->children; } void PolyQuery_Serialize_IMP(PolyQuery *self, OutStream *outstream) { PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); const uint32_t num_kids = (uint32_t)Vec_Get_Size(ivars->children); OutStream_Write_F32(outstream, ivars->boost); OutStream_Write_U32(outstream, num_kids); for (uint32_t i = 0; i < num_kids; i++) { Query *child = (Query*)Vec_Fetch(ivars->children, i); FREEZE(child, outstream); } } PolyQuery* PolyQuery_Deserialize_IMP(PolyQuery *self, InStream *instream) { float boost = InStream_Read_F32(instream); uint32_t num_children = InStream_Read_U32(instream); PolyQuery_init(self, NULL); PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); PolyQuery_Set_Boost(self, boost); Vec_Grow(ivars->children, num_children); while (num_children--) { Vec_Push(ivars->children, THAW(instream)); } return self; } Obj* PolyQuery_Dump_IMP(PolyQuery *self) { PolyQueryIVARS *ivars = PolyQuery_IVARS(self); PolyQuery_Dump_t super_dump = SUPER_METHOD_PTR(POLYQUERY, LUCY_PolyQuery_Dump); Hash *dump = (Hash*)CERTIFY(super_dump(self), HASH); Hash_Store_Utf8(dump, "children", 8, Freezer_dump((Obj*)ivars->children)); return (Obj*)dump; } Obj* PolyQuery_Load_IMP(PolyQuery *self, Obj *dump) { Hash *source = (Hash*)CERTIFY(dump, HASH); PolyQuery_Load_t super_load = SUPER_METHOD_PTR(POLYQUERY, LUCY_PolyQuery_Load); PolyQuery *loaded = (PolyQuery*)super_load(self, dump); Obj *children = CERTIFY(Hash_Fetch_Utf8(source, "children", 8), OBJ); PolyQuery_IVARS(loaded)->children = (Vector*)CERTIFY(Freezer_load(children), VECTOR); return (Obj*)loaded; } bool PolyQuery_Equals_IMP(PolyQuery *self, Obj *other) { if ((PolyQuery*)other == self) { return true; } if (!Obj_is_a(other, POLYQUERY)) { return false; } PolyQueryIVARS *const ivars = PolyQuery_IVARS(self); PolyQueryIVARS *const ovars = PolyQuery_IVARS((PolyQuery*)other); if (ivars->boost != ovars->boost) { return false; } if (!Vec_Equals(ovars->children, (Obj*)ivars->children)) { return false; } return true; } /**********************************************************************/ PolyCompiler* PolyCompiler_init(PolyCompiler *self, PolyQuery *parent, Searcher *searcher, float boost) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); PolyQueryIVARS *const parent_ivars = PolyQuery_IVARS(parent); const size_t num_kids = Vec_Get_Size(parent_ivars->children); Compiler_init((Compiler*)self, (Query*)parent, searcher, NULL, boost); ivars->children = Vec_new(num_kids); // Iterate over the children, creating a Compiler for each one. for (size_t i = 0; i < num_kids; i++) { Query *child_query = (Query*)Vec_Fetch(parent_ivars->children, i); float sub_boost = boost * Query_Get_Boost(child_query); Compiler *child_compiler = Query_Make_Compiler(child_query, searcher, sub_boost, true); Vec_Push(ivars->children, (Obj*)child_compiler); } return self; } void PolyCompiler_Destroy_IMP(PolyCompiler *self) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); DECREF(ivars->children); SUPER_DESTROY(self, POLYCOMPILER); } float PolyCompiler_Sum_Of_Squared_Weights_IMP(PolyCompiler *self) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); float sum = 0; float my_boost = PolyCompiler_Get_Boost(self); for (size_t i = 0, max = Vec_Get_Size(ivars->children); i < max; i++) { Compiler *child = (Compiler*)Vec_Fetch(ivars->children, i); sum += Compiler_Sum_Of_Squared_Weights(child); } // Compound the weight of each child. sum *= my_boost * my_boost; return sum; } void PolyCompiler_Apply_Norm_Factor_IMP(PolyCompiler *self, float factor) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); for (size_t i = 0, max = Vec_Get_Size(ivars->children); i < max; i++) { Compiler *child = (Compiler*)Vec_Fetch(ivars->children, i); Compiler_Apply_Norm_Factor(child, factor); } } Vector* PolyCompiler_Highlight_Spans_IMP(PolyCompiler *self, Searcher *searcher, DocVector *doc_vec, String *field) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); Vector *spans = Vec_new(0); for (size_t i = 0, max = Vec_Get_Size(ivars->children); i < max; i++) { Compiler *child = (Compiler*)Vec_Fetch(ivars->children, i); Vector *child_spans = Compiler_Highlight_Spans(child, searcher, doc_vec, field); if (child_spans) { Vec_Push_All(spans, child_spans); DECREF(child_spans); } } return spans; } void PolyCompiler_Serialize_IMP(PolyCompiler *self, OutStream *outstream) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); Freezer_serialize_string(PolyCompiler_get_class_name(self), outstream); Freezer_serialize_varray(ivars->children, outstream); PolyCompiler_Serialize_t super_serialize = SUPER_METHOD_PTR(POLYCOMPILER, LUCY_PolyCompiler_Serialize); super_serialize(self, outstream); } PolyCompiler* PolyCompiler_Deserialize_IMP(PolyCompiler *self, InStream *instream) { PolyCompilerIVARS *const ivars = PolyCompiler_IVARS(self); String *class_name = Freezer_read_string(instream); DECREF(class_name); // TODO Don't serialize class name. ivars->children = Freezer_read_varray(instream); PolyCompiler_Deserialize_t super_deserialize = SUPER_METHOD_PTR(POLYCOMPILER, LUCY_PolyCompiler_Deserialize); return super_deserialize(self, instream); }
{ "content_hash": "4a64416367baac4b66e1783718cb96a6", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 78, "avg_line_length": 34.76190476190476, "alnum_prop": 0.6573972602739726, "repo_name": "rectang/lucy", "id": "2bc5daa03209813f0ffe06e87d8a80d0bdc06369", "size": "8098", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "core/Lucy/Search/PolyQuery.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3183" }, { "name": "C", "bytes": "3871350" }, { "name": "CSS", "bytes": "1202" }, { "name": "Go", "bytes": "234653" }, { "name": "HTML", "bytes": "4793" }, { "name": "Java", "bytes": "8587" }, { "name": "Makefile", "bytes": "1869" }, { "name": "Perl", "bytes": "746549" }, { "name": "Ruby", "bytes": "8374" }, { "name": "Shell", "bytes": "13221" }, { "name": "VimL", "bytes": "2936" }, { "name": "Yacc", "bytes": "4679" } ], "symlink_target": "" }
<?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> <parent> <groupId>org.sonatype.oss</groupId> <artifactId>oss-parent</artifactId> <version>7</version> </parent> <groupId>org.jbake</groupId> <artifactId>jbake-core</artifactId> <version>2.5.0-SNAPSHOT</version> <packaging>jar</packaging> <name>jbake</name> <description>JBake is a Java based open source static site/blog generator for developers.</description> <url>http://jbake.org</url> <developers> <developer> <id>jonbullock</id> <name>Jonathan Bullock</name> <email>[email protected]</email> <url>http://jonathanbullock.com</url> <timezone>0</timezone> </developer> </developers> <scm> <url>https://github.com/jbake-org/jbake/</url> <connection>scm:git:[email protected]:jbake-org/jbake.git</connection> <developerConnection>scm:git:https://github.com/jbake-org/jbake.git</developerConnection> </scm> <issueManagement> <system>GitHub Issues</system> <url>https://github.com/jbake-org/jbake/issues</url> </issueManagement> <mailingLists> <mailingList> <name>jbake-dev</name> <subscribe>[email protected]</subscribe> <unsubscribe>[email protected]</unsubscribe> <archive>http://groups.google.com/group/jbake-dev</archive> </mailingList> <mailingList> <name>jbake-user</name> <subscribe>[email protected]</subscribe> <unsubscribe>[email protected]</unsubscribe> <archive>http://groups.google.com/group/jbake-user</archive> </mailingList> </mailingLists> <licenses> <license> <name>The MIT License (MIT)</name> <url>http://opensource.org/licenses/MIT</url> </license> </licenses> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <timestamp>${maven.build.timestamp}</timestamp> <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ssa</maven.build.timestamp.format> <asciidoctorj.version>1.5.4</asciidoctorj.version> <commons.io.version>2.4</commons.io.version> <commons.configuration.version>1.9</commons.configuration.version> <commons.vfs2.version>2.0</commons.vfs2.version> <args4j.version>2.0.26</args4j.version> <freemarker.version>2.3.20</freemarker.version> <junit.version>4.11</junit.version> <pegdown.version>1.4.2</pegdown.version> <jetty.version>8.1.12.v20130726</jetty.version> <orientdb.version>1.6.4</orientdb.version> <groovy.version>2.4.1</groovy.version> <slf4j.version>1.7.6</slf4j.version> <logback.version>1.1.1</logback.version> <assertj.version>1.7.0</assertj.version> <thymeleaf.version>2.1.3.RELEASE</thymeleaf.version> <thymeleaf.extras.version>2.1.1.RELEASE</thymeleaf.extras.version> <json-simple.version>1.1.1</json-simple.version> <!-- <pebble.version>1.3.0</pebble.version> --> <jade.version>0.4.2</jade.version> <!-- <spock.version>1.0-groovy-2.4</spock.version> --> </properties> <build> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <downloadSources>true</downloadSources> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-scm-plugin</artifactId> <version>1.1</version> <executions> <execution> <id>checkout-example-project-freemarker</id> <phase>prepare-package</phase> <goals> <goal>checkout</goal> </goals> <configuration> <checkoutDirectory>${project.build.directory}/example-project-freemarker</checkoutDirectory> <connectionUrl>scm:git:git://github.com/jbake-org/jbake-example-project-freemarker.git </connectionUrl> </configuration> </execution> <execution> <id>checkout-example-project-groovy</id> <phase>prepare-package</phase> <goals> <goal>checkout</goal> </goals> <configuration> <checkoutDirectory>${project.build.directory}/example-project-groovy</checkoutDirectory> <connectionUrl>scm:git:git://github.com/jbake-org/jbake-example-project-groovy.git </connectionUrl> </configuration> </execution> <execution> <id>checkout-example-project-thymeleaf</id> <phase>prepare-package</phase> <goals> <goal>checkout</goal> </goals> <configuration> <checkoutDirectory>${project.build.directory}/example-project-thymeleaf</checkoutDirectory> <connectionUrl>scm:git:git://github.com/jbake-org/jbake-example-project-thymeleaf.git </connectionUrl> </configuration> </execution> <execution> <id>checkout-example-project-jade</id> <phase>prepare-package</phase> <goals> <goal>checkout</goal> </goals> <configuration> <checkoutDirectory>${project.build.directory}/example-project-jade</checkoutDirectory> <!-- TODO: Move this project to jbake repo --> <connectionUrl>scm:git:git://github.com/mariuszs/jbake-example-project-jade.git</connectionUrl> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>org.jbake.launcher.Main</mainClass> <packageName>org.jbake.launcher</packageName> </manifest> <manifestEntries> <Class-Path>lib/</Class-Path> </manifestEntries> </archive> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.4.1</version> <configuration> <filesets> <fileset> <directory>dist</directory> </fileset> </filesets> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <excludeScope>test</excludeScope> <includeScope>compile</includeScope> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.4</version> <executions> <execution> <id>zip-example-project-freemarker</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <finalName>example_project_freemarker</finalName> <appendAssemblyId>false</appendAssemblyId> <descriptors> <descriptor>src/main/assembly/assembly-example-project-freemarker.xml</descriptor> </descriptors> <attach>false</attach> </configuration> </execution> <execution> <id>zip-example-project-groovy</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <finalName>example_project_groovy</finalName> <appendAssemblyId>false</appendAssemblyId> <descriptors> <descriptor>src/main/assembly/assembly-example-project-groovy.xml</descriptor> </descriptors> <attach>false</attach> </configuration> </execution> <execution> <id>zip-example-project-thymeleaf</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <finalName>example_project_thymeleaf</finalName> <appendAssemblyId>false</appendAssemblyId> <descriptors> <descriptor>src/main/assembly/assembly-example-project-thymeleaf.xml</descriptor> </descriptors> <attach>false</attach> </configuration> </execution> <execution> <id>zip-example-project-jade</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <finalName>example_project_jade</finalName> <appendAssemblyId>false</appendAssemblyId> <descriptors> <descriptor>src/main/assembly/assembly-example-project-jade.xml</descriptor> </descriptors> <attach>false</attach> </configuration> </execution> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <outputDirectory>dist</outputDirectory> <finalName>jbake-${project.version}</finalName> <descriptors> <descriptor>src/main/assembly/assembly.xml</descriptor> </descriptors> <attach>false</attach> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.7.2.201409121644</version> <executions> <execution> <id>prepare-agent</id> <goals> <goal>prepare-agent</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.eluder.coveralls</groupId> <artifactId>coveralls-maven-plugin</artifactId> <version>2.0.1</version> <configuration> <!-- <repoToken>yourcoverallsprojectrepositorytoken</repoToken> --> <!-- <timestamp>yyyy-MM-dd HH:mm:ssa</timestamp> --> </configuration> </plugin> <!-- Mandatory plugins for using Spock --> <!-- The gmavenplus plugin is used to compile Groovy code. To learn more about this plugin, visit https://github.com/groovy/GMavenPlus/wiki --> <!-- <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.5</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18.1</version> <configuration> <includes> <include>**/*Test.class</include> <include>**/*Spec.class</include> </includes> </configuration> </plugin> --> </plugins> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> <dependencies> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons.io.version}</version> </dependency> <dependency> <groupId>commons-configuration</groupId> <artifactId>commons-configuration</artifactId> <version>${commons.configuration.version}</version> </dependency> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>${json-simple.version}</version> </dependency> <dependency> <groupId>args4j</groupId> <artifactId>args4j</artifactId> <version>${args4j.version}</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>com.orientechnologies</groupId> <artifactId>orient-commons</artifactId> <version>${orientdb.version}</version> </dependency> <dependency> <groupId>com.orientechnologies</groupId> <artifactId>orientdb-core</artifactId> <version>${orientdb.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- <dependency> <groupId>org.spockframework</groupId> <artifactId>spock-core</artifactId> <version>${spock.version}</version> <scope>test</scope> </dependency> --> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>${assertj.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.pegdown</groupId> <artifactId>pegdown</artifactId> <version>${pegdown.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctorj</artifactId> <version>${asciidoctorj.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>${jetty.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>${groovy.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-templates</artifactId> <version>${groovy.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>${thymeleaf.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-conditionalcomments</artifactId> <version>${thymeleaf.extras.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>de.neuland-bfi</groupId> <artifactId>jade4j</artifactId> <version>${jade.version}</version> <optional>true</optional> </dependency> <!-- sl4j Logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> <optional>true</optional> </dependency> <!-- <dependency> <groupId>com.mitchellbosecke</groupId> <artifactId>pebble</artifactId> <version>${pebble.version}</version> <optional>true</optional> </dependency> --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-vfs2</artifactId> <version>${commons.vfs2.version}</version> <optional>true</optional> </dependency> </dependencies> </project>
{ "content_hash": "1937b6662d2d39cf6ffa5533551e1059", "timestamp": "", "source": "github", "line_count": 499, "max_line_length": 155, "avg_line_length": 40.83567134268537, "alnum_prop": 0.5052264808362369, "repo_name": "danielgrycman/jbake", "id": "ffaffc1cf43cf4680b3156c8ea92d63f5c6f54e3", "size": "20377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "49" }, { "name": "FreeMarker", "bytes": "7971" }, { "name": "Groovy", "bytes": "8217" }, { "name": "HTML", "bytes": "10045" }, { "name": "Java", "bytes": "212681" }, { "name": "Shell", "bytes": "114" }, { "name": "Smarty", "bytes": "8106" } ], "symlink_target": "" }
<!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>GoAtThrottleUp - Cameras</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, maximum-scale=1"> <!-- CSS --> <link rel="Shortcut Icon" href="favicon.ico" type="image/x-icon" /> <link href="css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="jqwidgets/styles/jqx.base.css" type="text/css" /> <link rel="stylesheet" href="jqwidgets/styles/jqx.arctic.css" type="text/css" /> <link rel="stylesheet" href="css/leaflet.ksp-src.css" type="text/css" /> <link rel="stylesheet" href="css/main.css"> <!-- Fonts --> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'> <!-- JS --> <script src="js/jquery-2.1.0.min.js"></script> <script type="text/javascript" src="jqwidgets/jqxcore.js"></script> <script type="text/javascript" src="jqwidgets/jqxdata.js"></script> <script type="text/javascript" src="jqwidgets/jqxchart.js"></script> <script type="text/javascript" src="jqwidgets/jqxgauge.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/main.js"></script> </head> <body> <div class="container-fluid"> <div class="row header-row"> <div class="col-md-8"><h1><span class="glyphicon glyphicon-camera"></span> Cameras</h1><div id="linksbar"></div></div> <div class="col-md-4"> <h3><span class="glyphicon glyphicon-time"></span> Mission Time</h3> <table class="table table-condensed"> <tbody> <tr><td><span class="readout-label">Mission:</span></td><td class="text-right"><span class="mission-time-readout">alt</span></td></tr> <tr><td><span class="readout-label">Universal:</span></td><td class="text-right"><span class="u-time-readout">alt</span></td></tr> </tbody> </table> </div> </div> <!-- end row --> <div class="row"> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera1-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera1-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera2-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera2-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera3-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera3-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera4-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera4-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> </div> <!-- end row --> <div class="row"> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera5-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera5-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera6-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera6-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera7-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera7-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> <div class="col-md-3 camera-general-height"> <div class="camera-wrapper"> <img id="camera8-active" class="grid-camera-display grid-camera-display-active"></img> <img id="camera8-passive" class="grid-camera-display grid-camera-display-passive"></img> <div class="grid-camera-display grid-camera-display-static"></div> </div> </div> </div> <!-- end row --> </div><!-- end container --> </body> </html>
{ "content_hash": "bd4f9aab51899b0a19e27ea34d22cf09", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 142, "avg_line_length": 48.8018018018018, "alnum_prop": 0.611962340779029, "repo_name": "RacerXx/GoAtThrottleUp", "id": "8e4aee8d8140fc1ac9bece3ec7d13d2e486c26a5", "size": "5417", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "ServerRelay/static/cameras.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1550" }, { "name": "C#", "bytes": "88703" }, { "name": "CSS", "bytes": "509426" }, { "name": "HTML", "bytes": "51996" }, { "name": "JavaScript", "bytes": "136104" }, { "name": "Python", "bytes": "1217580" } ], "symlink_target": "" }
package org.kie.workbench.common.dmn.client.editors.expressions.types.relation; import org.kie.soup.commons.validation.PortablePreconditions; import org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionCellValue; import org.kie.workbench.common.dmn.client.widgets.grid.columns.factory.TextAreaSingletonDOMElementFactory; import org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridColumn; import org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple; import org.uberfire.client.callbacks.Callback; import org.uberfire.ext.wires.core.grids.client.model.GridCell; import org.uberfire.ext.wires.core.grids.client.model.GridCellValue; import org.uberfire.ext.wires.core.grids.client.model.GridData; import org.uberfire.ext.wires.core.grids.client.model.GridRow; import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCell; import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue; import org.uberfire.ext.wires.core.grids.client.widget.context.GridBodyCellRenderContext; import org.uberfire.ext.wires.core.grids.client.widget.dom.HasDOMElementResources; import org.uberfire.ext.wires.core.grids.client.widget.dom.single.HasSingletonDOMElementResource; public class RelationColumn extends DMNGridColumn<String> implements HasSingletonDOMElementResource { private final TextAreaSingletonDOMElementFactory factory; public RelationColumn(final HeaderMetaData headerMetaData, final TextAreaSingletonDOMElementFactory factory, final RelationGrid gridWidget) { super(headerMetaData, new RelationColumnRenderer(factory), gridWidget); this.factory = PortablePreconditions.checkNotNull("factory", factory); setMovable(true); setResizable(false); } @Override public Double getMinimumWidth() { final double minimumWidth = super.getMinimumWidth(); final double minimumWidthOfPeers = getMinimumWidthOfPeers(); final double widthOfThisEditor = gridWidget.getWidth(); final double widthOfThisColumn = getWidth(); return Math.max(minimumWidth, minimumWidthOfPeers - (widthOfThisEditor - widthOfThisColumn)); } private double getMinimumWidthOfPeers() { final GridCellTuple parent = ((RelationGrid) gridWidget).getParentInformation(); final GridData parentUiModel = parent.getGridData(); final int parentUiRowIndex = parent.getRowIndex(); final int parentUiColumnIndex = parent.getColumnIndex(); double minimumWidth = super.getMinimumWidth(); for (int uiRowIndex = 0; uiRowIndex < parentUiModel.getRowCount(); uiRowIndex++) { if (uiRowIndex != parentUiRowIndex) { final GridRow row = parentUiModel.getRow(uiRowIndex); final GridCell<?> cell = row.getCells().get(parentUiColumnIndex); if (cell != null) { final GridCellValue<?> value = cell.getValue(); if (value instanceof ExpressionCellValue) { final ExpressionCellValue ecv = (ExpressionCellValue) value; minimumWidth = Math.max(minimumWidth, ecv.getMinimumWidth().orElse(0.0) + DMNGridColumn.PADDING * 2); } } } } return minimumWidth; } @Override public void edit(final GridCell<String> cell, final GridBodyCellRenderContext context, final Callback<GridCellValue<String>> callback) { factory.attachDomElement(context, (e) -> e.getWidget().setValue(assertCell(cell).getValue().getValue()), (e) -> e.getWidget().setFocus(true)); } private GridCell<String> assertCell(final GridCell<String> cell) { if (cell != null && cell.getValue() != null && cell.getValue().getValue() != null) { return cell; } return new BaseGridCell<>(new BaseGridCellValue<>("")); } @Override public void flush() { factory.flush(); } @Override public void destroyResources() { factory.destroyResources(); getHeaderMetaData().stream() .filter(md -> md instanceof HasDOMElementResources) .map(md -> (HasDOMElementResources) md) .forEach(HasDOMElementResources::destroyResources); } @Override public void setWidth(final double width) { super.setWidth(width); updateWidthOfPeers(); } }
{ "content_hash": "4a38af9f9f41c5d934c560981a6dab83", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 111, "avg_line_length": 43.60550458715596, "alnum_prop": 0.6581106669471912, "repo_name": "ederign/kie-wb-common", "id": "38036969998b2947a290c89ddace8c3b3db56485", "size": "5372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/editors/expressions/types/relation/RelationColumn.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "67975" }, { "name": "FreeMarker", "bytes": "36748" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "213132" }, { "name": "Java", "bytes": "27302200" }, { "name": "JavaScript", "bytes": "19109" }, { "name": "Shell", "bytes": "151" }, { "name": "Visual Basic", "bytes": "78106" } ], "symlink_target": "" }
package eu.leads.processor.core.net; /** * Created by vagvaz on 7/8/14. */ public class ComUtils { public static int DEFAULT_RETRIES = 3; public static long DEFAULT_TIMEOUT = 60000; public static final java.lang.String P2P = "P2P"; public static final java.lang.String GROUP = "GROUP"; public static final java.lang.String ALLGROUP = "ALLGROUP"; }
{ "content_hash": "9df354455eb47e9662354218810808fb", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 61, "avg_line_length": 25.928571428571427, "alnum_prop": 0.7162534435261708, "repo_name": "leads-project/multicloud-mr", "id": "23e30ba453ef6f63f761e2582f2a79a6722cd7b2", "size": "363", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/common-core/src/main/java/eu/leads/processor/core/net/ComUtils.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1374696" }, { "name": "Shell", "bytes": "188" } ], "symlink_target": "" }
package de.terrestris.shogun2.importer.communication; import de.terrestris.shogun2.importer.communication.AbstractRESTEntity; /** * A data is the description of the source data of a import (overall) or a * task. In case the import has a global data definition, this normally refers * to an aggregate store such as a directory or a database, and the data * associated to the tasks refers to a single element inside such aggregation, * such as a single file or table. * <p> * A import can have a "data" representing the source of the data to be * imported. The data can be of different types, in particular: "file", * "directory", "mosaic", "database" and "remote". During the import * initialization the importer will scan the contents of said resource, and * generate import tasks for each data found in it. * * @author Daniel Koch * @author terrestris GmbH & Co. KG */ public class RESTData extends AbstractRESTEntity { /** * */ private String type; /** * */ private String format; /** * */ private String file; /** * */ private String location; /** * Default constructor. */ public RESTData() { } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the format */ public String getFormat() { return format; } /** * @param format the format to set */ public void setFormat(String format) { this.format = format; } /** * @return the file */ public String getFile() { return file; } /** * @param file the file to set */ public void setFile(String file) { this.file = file; } /** * @return */ public String getLocation() { return location; } /** * @param location */ public void setLocation(String location) { this.location = location; } }
{ "content_hash": "f38958ecad389677c12c4628ff67cb8c", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 78, "avg_line_length": 20.037735849056602, "alnum_prop": 0.5870998116760828, "repo_name": "marcjansen/shogun2", "id": "4a60bb0ecb12e5a1b46770c8d1f16ace4cc6bd28", "size": "2124", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/shogun2-core/src/main/java/de/terrestris/shogun2/importer/communication/RESTData.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "292" }, { "name": "Java", "bytes": "1192908" }, { "name": "Shell", "bytes": "1612" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html lang='en'> <head> <meta name="generator" content="AWStats 6.7 (build 1.892) from config file awstats.2818332.conf (http://awstats.sourceforge.net)"> <meta name="robots" content="noindex,nofollow"> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1"> <meta http-equiv="description" content="Awstats - Advanced Web Statistics for 0340a95.netsolhost.com (2011-11)"> <title>Statistics for 0340a95.netsolhost.com (2011-11)</title> <style type="text/css"> <!-- body { font: 11px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; margin-top: 0; margin-bottom: 0; } .aws_bodyl { } .aws_border { border-collapse: collapse; background-color: #CCCCDD; padding: 1px 1px 1px 1px; margin-top: 0px; margin-bottom: 0px; } .aws_title { font: 13px verdana, arial, helvetica, sans-serif; font-weight: bold; background-color: #CCCCDD; text-align: center; margin-top: 0; margin-bottom: 0; padding: 1px 1px 1px 1px; color: #000000; } .aws_blank { font: 13px verdana, arial, helvetica, sans-serif; background-color: #FFFFFF; text-align: center; margin-bottom: 0; padding: 1px 1px 1px 1px; } .aws_data { background-color: #FFFFFF; border-top-width: 1px; border-left-width: 0px; border-right-width: 0px; border-bottom-width: 0px; } .aws_formfield { font: 13px verdana, arial, helvetica; } .aws_button { font-family: arial,verdana,helvetica, sans-serif; font-size: 12px; border: 1px solid #ccd7e0; background-image : url(/awstats/icon/other/button.gif); } th { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } th.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; padding: 1px 2px 1px 1px; font-size: 13px; font-weight: bold; } td { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:center; color: #000000; } td.aws { border-color: #ECECEC; border-left-width: 0px; border-right-width: 1px; border-top-width: 0px; border-bottom-width: 1px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px;} td.awsm { border-left-width: 0px; border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; font: 11px verdana, arial, helvetica, sans-serif; text-align:left; color: #000000; padding: 0px; } b { font-weight: bold; } a { font: 11px verdana, arial, helvetica, sans-serif; } a:link { color: #0011BB; text-decoration: none; } a:visited { color: #0011BB; text-decoration: none; } a:hover { color: #605040; text-decoration: underline; } .currentday { font-weight: bold; } //--> </style> </head> <body style="margin-top: 0px"> <a name="top">&nbsp;</a> <a name="menu">&nbsp;</a> <form name="FormDateFilter" action="/cgi-bin/awstats.pl?config=2818332.1111&amp;configdir=/data/22/2/81/47/2570699/meta/2818332/config&amp;output=lastrobots" style="padding: 0px 0px 0px 0px; margin-top: 0"> <table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td> <table class="aws_data" border="0" cellpadding="1" cellspacing="0" width="100%"> <tr><td class="aws" valign="middle"><b>Statistics for:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 14px;">0340a95.netsolhost.com</span></td><td align="right" rowspan="3"><a href="http://awstats.sourceforge.net" target="awstatshome"><img src="/awstats/icon/other/awstats_logo6.png" border="0" alt='Awstats Web Site' title='Awstats Web Site' /></a></td></tr> <tr valign="middle"><td class="aws" valign="middle" width="150"><b>Last Update:</b>&nbsp;</td><td class="aws" valign="middle"><span style="font-size: 12px;">01 Dec 2011 - 03:18</span></td></tr> <tr><td class="aws" valign="middle"><b>Reported period:</b></td><td class="aws" valign="middle"><span style="font-size: 14px;">Month Nov 2011</span></td></tr> </table> </td></tr></table> </form> <table> <tr><td class="aws"><a href="javascript:parent.window.close();">Close window</a></td></tr> </table> <a name="robots">&nbsp;</a><br /> <table class="aws_border" border="0" cellpadding="2" cellspacing="0" width="100%"> <tr><td class="aws_title" width="70%">Last visit </td><td class="aws_blank">&nbsp;</td></tr> <tr><td colspan="2"> <table class="aws_data" border="1" cellpadding="2" cellspacing="0" width="100%"> <tr bgcolor="#ECECEC"><th>8 different robots</th><th bgcolor="#66DDEE" width="80">Hits</th><th bgcolor="#2EA495" width="80">Bandwidth</th><th width="120">Last visit</th></tr> <tr><td class="aws"><a href="http://www.baidu.com/search/spider.html" title="Bot home page [new window]" target="_blank">BaiDuSpider</a></td><td>185</td><td>1.61 MB</td><td>30 Nov 2011 - 20:14</td></tr> <tr><td class="aws">Unknown robot (identified by 'bot/' or 'bot-')</td><td>64</td><td>976.81 KB</td><td>30 Nov 2011 - 14:34</td></tr> <tr><td class="aws">Yandex bot</td><td>144</td><td>1.39 MB</td><td>30 Nov 2011 - 08:35</td></tr> <tr><td class="aws">Unknown robot (identified by 'spider')</td><td>11</td><td>70.70 KB</td><td>30 Nov 2011 - 05:04</td></tr> <tr><td class="aws"><a href="http://www.google.com/bot.html" title="Bot home page [new window]" target="_blank">Googlebot</a></td><td>31</td><td>624.31 KB</td><td>29 Nov 2011 - 00:44</td></tr> <tr><td class="aws">Unknown robot (identified by 'robot')</td><td>1</td><td>7.59 KB</td><td>26 Nov 2011 - 03:08</td></tr> <tr><td class="aws"><a href="http://www.netcraft.com/survey/" title="Bot home page [new window]" target="_blank">Netcraft</a></td><td>2</td><td>15.18 KB</td><td>25 Nov 2011 - 18:58</td></tr> <tr><td class="aws">SurveyBot</td><td>4</td><td>30.36 KB</td><td>19 Nov 2011 - 20:12</td></tr> </table></td></tr></table><span style="font: 11px verdana, arial, helvetica;">* Robots shown here gave hits or traffic "not viewed" by visitors, so they are not included in other charts.</span><br /> <br /> <br /><br /> <span dir="ltr" style="font: 11px verdana, arial, helvetica; color: #000000;"><b>Advanced Web Statistics 6.7 (build 1.892)</b> - <a href="http://awstats.sourceforge.net" target="awstatshome">Created by awstats</a></span><br /> <br /> </body> </html>
{ "content_hash": "f9bb0324e3f26eb0dbfbaa40efa8a6e8", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 382, "avg_line_length": 72.80681818181819, "alnum_prop": 0.6858123926954893, "repo_name": "zparnold/cd-risc", "id": "a3b21b2739785e9e3f6dbcd045a2f4c437c02d90", "size": "6407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "awstats/1111/awstats.2818332.1111.lastrobots.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "194" }, { "name": "CSS", "bytes": "7308" }, { "name": "HTML", "bytes": "22246715" }, { "name": "PHP", "bytes": "6854" } ], "symlink_target": "" }
<html> <head> <title></title> <script type="text/javascript" src="../../lib/scenejs.js"></script> <link href="../web/style.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="container"> <div id="header"> <div id="header-nav"> </div> <div id="header-inner"> <h1><a href="http://scenejs.org">SceneJS</a> &gt; <a href="../index.html">Examples</a> &gt;&nbsp;Enabling and Disabling Layers </h1> <a class="a2a_dd" href="http://www.addtoany.com/share_save?linkname=s&amp;linkurl=s"><img src="http://static.addtoany.com/buttons/share_save_171_16.png" width="171" height="16" border="0" alt="Share/Bookmark"/></a> <script type="text/javascript"> var a2a_linkname = "SceneJS Live Examples"; var a2a_linkurl = window.location; var a2a_onclick = 1;</script> <script type="text/javascript" src="http://static.addtoany.com/menu/page.js"></script> </div> </div> <div id="content"> <canvas id="theCanvas" width="1030" height="700"> <p>This example requires a browser that supports the <a href="http://www.w3.org/html/wg/html5/">HTML5</a> &lt;canvas&gt; feature.</p> </canvas> <div id="info"> <h2>Enabling and Disabling Layers</h2> <p>In this example, we define a scene containing four teapots, each in a separate layer.</p> <br/> <p>Then just before we render this scene we enable/disable a selection of the layers to specify which of them are included in the scene traversal.</p> <br/> <p>We can specify a priority for layers if we wanted to control the order in which the geometries within them are rendered, but for this example we're just specifying the default priority of 0 because we're just demonstrating enabling/disabling of layers.</p> <br/> <br/> <ul> <li><a target="_other" href="enable-layers.js">Scene source code</a></li> <li><a target="_other" href="http://scenejs.wikispaces.com/Layers">Wiki page on layers</a></li> </ul> </div> <div id="log"> <h3>Log</h3> <div id="theLoggingDiv"></div> </div> </div> </div> <script type="text/javascript" src="enable-layers.js"></script> </body> </html>
{ "content_hash": "4a7b26bd22cf805fd0f5dd8afe4b416b", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 117, "avg_line_length": 38.11940298507463, "alnum_prop": 0.5497259201252936, "repo_name": "fridek/scenejs-physics", "id": "8e54e12209b3105611e7c514b366d43c9c1f9553", "size": "2554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/enable-layers/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7405" }, { "name": "JavaScript", "bytes": "12875512" } ], "symlink_target": "" }
namespace Gringo { namespace Input { namespace Test { TEST_CASE("input-nongroundlexer", "[input]") { Gringo::Test::TestGringoModule module; std::ostringstream oss; Potassco::TheoryData td; Output::OutputBase out(td, {}, oss); Program prg; Defines defs; Gringo::Test::TestContext context; NongroundProgramBuilder pb(context, prg, out, defs); bool incmode; NonGroundParser ngp(pb, incmode); std::string in = "#script (python) #end " "%*xyz\nxyz\n*%" "%xyz\n" "#minimize " "#minimise " "#infimum " "#inf " ";* " ";\n * " "not " "xyz " "_xyz " "__xyz " "___xyz " // TODO: check errors too: "# " ; ngp.pushStream("-", std::unique_ptr<std::istream>(new std::stringstream(in)), module.logger); Location loc("<undef>", 0, 0, "<undef>", 0, 0); NonGroundGrammar::parser::semantic_type val; REQUIRE(int(NonGroundGrammar::parser::token::PYTHON) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::MINIMIZE) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::MINIMIZE) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::INFIMUM) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::INFIMUM) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::SEM) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::MUL) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::SEM) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::MUL) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::NOT) == ngp.lex(&val, loc)); REQUIRE(int(NonGroundGrammar::parser::token::IDENTIFIER) == ngp.lex(&val, loc)); REQUIRE(String("xyz") == String::fromRep(val.str)); REQUIRE(int(NonGroundGrammar::parser::token::IDENTIFIER) == ngp.lex(&val, loc)); REQUIRE(String("_xyz") == String::fromRep(val.str)); REQUIRE(int(NonGroundGrammar::parser::token::IDENTIFIER) == ngp.lex(&val, loc)); REQUIRE(String("__xyz") == String::fromRep(val.str)); REQUIRE(int(NonGroundGrammar::parser::token::IDENTIFIER) == ngp.lex(&val, loc)); REQUIRE(String("___xyz") == String::fromRep(val.str)); REQUIRE(5 == loc.beginLine); REQUIRE(23 == loc.beginColumn); REQUIRE(int(NonGroundGrammar::parser::token::SYNC) == ngp.lex(&val, loc)); REQUIRE(0 == ngp.lex(&val, loc)); } // }}} } } } // namespace Test Input Gringo
{ "content_hash": "1639ffc06ebed33a83a6158a2bd34293", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 97, "avg_line_length": 40.84126984126984, "alnum_prop": 0.6148464827050136, "repo_name": "peschue/clingo", "id": "370ffb9c42c402fca33017b51b0706a2ee3e39a2", "size": "3961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libgringo/tests/input/nongroundlexer.cc", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "114" }, { "name": "C", "bytes": "6576" }, { "name": "C++", "bytes": "3621505" }, { "name": "CMake", "bytes": "36575" }, { "name": "Haskell", "bytes": "1685" }, { "name": "Makefile", "bytes": "2752" }, { "name": "Objective-C", "bytes": "140599" }, { "name": "Python", "bytes": "65413" }, { "name": "Shell", "bytes": "20404" }, { "name": "Yacc", "bytes": "49815" } ], "symlink_target": "" }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > Since when call is used for Function constructor themself new function instance creates and then first argument(thisArg) should be ignored es5id: 15.3_A3_T3 description: First argument is this, and this don`t have needed variable ---*/ var f=Function.call(this, "return planet;"); var g=Function.call(this, "return color;"); //CHECK#1 if (f()!==undefined) { $ERROR('#1: '); } var planet="mars"; //CHECK#2 if (f() !== "mars") { $ERROR('#2: '); } //CHECK#3 try{ g(); $ERROR('#3: '); } catch(e){ if (!(e instanceof ReferenceError)) $ERROR('#3.1: '); } this.color="red"; //CHECK#4 if (g() !== "red") { $ERROR('#4: '); }
{ "content_hash": "3187cb838db11d7831def63af2efc8fe", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 91, "avg_line_length": 19.414634146341463, "alnum_prop": 0.6256281407035176, "repo_name": "m0ppers/arangodb", "id": "e5970dbd6a06013e96c7296fa75f2e6b3da7bdca", "size": "796", "binary": false, "copies": "4", "ref": "refs/heads/devel", "path": "3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Function/S15.3_A3_T3.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "397438" }, { "name": "Batchfile", "bytes": "36479" }, { "name": "C", "bytes": "4981599" }, { "name": "C#", "bytes": "96430" }, { "name": "C++", "bytes": "273207213" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "526333" }, { "name": "CSS", "bytes": "634304" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "33549" }, { "name": "Emacs Lisp", "bytes": "14357" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groff", "bytes": "272212" }, { "name": "Groovy", "bytes": "131" }, { "name": "HTML", "bytes": "3470113" }, { "name": "IDL", "bytes": "14" }, { "name": "Java", "bytes": "2325801" }, { "name": "JavaScript", "bytes": "66968092" }, { "name": "LLVM", "bytes": "38070" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "16189" }, { "name": "M4", "bytes": "64965" }, { "name": "Makefile", "bytes": "1268118" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "28404" }, { "name": "Objective-C", "bytes": "30435" }, { "name": "Objective-C++", "bytes": "2503" }, { "name": "PHP", "bytes": "39473" }, { "name": "Pascal", "bytes": "145688" }, { "name": "Perl", "bytes": "205308" }, { "name": "Python", "bytes": "6937381" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "R", "bytes": "5123" }, { "name": "Rebol", "bytes": "354" }, { "name": "Ruby", "bytes": "910409" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "986221" }, { "name": "Swift", "bytes": "116" }, { "name": "Vim script", "bytes": "4075" }, { "name": "XSLT", "bytes": "473118" }, { "name": "Yacc", "bytes": "72510" } ], "symlink_target": "" }
package br.edu.ufcg.splab.designmetrics.mocks.cbo2; public class ClassFive { private Integer id; private String name; private ClassTwo two; public ClassFive() { this.id = 5; this.name = "Five"; this.two = new ClassTwo(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ClassTwo getTwo() { return two; } public void setTwo(ClassTwo two) { this.two = two; } public Integer getSum() { Integer a = getTwo().getId(); ClassThree three = new ClassThree(); Integer b = three.getId(); return a + b; } }
{ "content_hash": "2103f0cc5aaa73c4f6001aefb66cec6f", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 51, "avg_line_length": 17.638297872340427, "alnum_prop": 0.5428226779252111, "repo_name": "tacianosilva/designmetrics", "id": "1a12e81462555d1667f8041207b634d8f274e445", "size": "829", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/br/edu/ufcg/splab/designmetrics/mocks/cbo2/ClassFive.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "153171" }, { "name": "R", "bytes": "275" } ], "symlink_target": "" }
const NavigationCallExp = require("./NavigationCallExp"); const codeGenMixin = require("../CodeGenMixins/AssociationClassCallExp"); class AssociationClassCallExp extends codeGenMixin(NavigationCallExp) { constructor() { super(); } }//end AssociationClassCallExp module.exports = AssociationClassCallExp;
{ "content_hash": "6ce4716dd9a8d4aa5cd10eacb3147aff", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 73, "avg_line_length": 17.77777777777778, "alnum_prop": 0.775, "repo_name": "evonox/NodeMDA-OCL-to-JavaScript-compiler", "id": "148638cd52c6982e9b330114fb02f015a8e340b5", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ocl/AssociationClassCallExp.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "106" }, { "name": "HTML", "bytes": "14733" }, { "name": "JavaScript", "bytes": "90473" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('organization', '0014_auto_20160619_1837'), ] operations = [ migrations.AlterField( model_name='organization', name='verified', field=models.BooleanField(default=False, help_text='Verified organizations are visible to all users', verbose_name='Verified'), ), ]
{ "content_hash": "45b79bc4208488e6c68c809f0b2373bc", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 139, "avg_line_length": 26.666666666666668, "alnum_prop": 0.6416666666666667, "repo_name": "sakset/getyourdata", "id": "159033cdd60bdcd91b41d54b7069963f002ffbb3", "size": "552", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "getyourdata/organization/migrations/0015_auto_20160619_1852.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2791" }, { "name": "HTML", "bytes": "64735" }, { "name": "JavaScript", "bytes": "1519" }, { "name": "Python", "bytes": "218082" }, { "name": "Shell", "bytes": "2722" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="authorGroupDAO"> <resultMap id="authorGroup" type="egovframework.com.sec.rgm.service.AuthorGroupVO"> <result property="userId" column="USER_ID"/> <result property="userNm" column="USER_NM"/> <result property="groupId" column="GROUP_ID"/> <result property="mberTyCode" column="MBER_TY_CODE"/> <result property="mberTyNm" column="MBER_TY_NM"/> <result property="authorCode" column="AUTHOR_CODE"/> <result property="regYn" column="REG_YN"/> <result property="uniqId" column="ESNTL_ID"/> </resultMap> <select id="selectAuthorGroupList" parameterType="egovframework.com.sec.rgm.service.AuthorGroupVO" resultMap="authorGroup"> SELECT * FROM ( SELECT ROWNUM RNUM, ALL_LIST.* FROM ( SELECT A.USER_ID, A.USER_NM, A.GROUP_ID, A.MBER_TY_CODE, (SELECT CODE_NM FROM COMTCCMMNDETAILCODE WHERE CODE_ID = 'COM012' AND CODE = A.MBER_TY_CODE AND USE_AT = 'Y') AS MBER_TY_NM, B.AUTHOR_CODE, (CASE WHEN B.SCRTY_DTRMN_TRGET_ID IS NULL THEN 'N' ELSE 'Y' END) AS REG_YN, ESNTL_ID FROM (SELECT MBER_ID USER_ID, MBER_NM USER_NM, GROUP_ID, 'USR01' MBER_TY_CODE, ESNTL_ID FROM COMTNGNRLMBER UNION ALL SELECT ENTRPRS_MBER_ID USER_ID, CMPNY_NM USER_NM, GROUP_ID, 'USR02' MBER_TY_CODE, ESNTL_ID FROM COMTNENTRPRSMBER UNION ALL SELECT EMPLYR_ID USER_ID, USER_NM USER_NM, GROUP_ID, 'USR03' MBER_TY_CODE, ESNTL_ID FROM COMTNEMPLYRINFO ) A LEFT OUTER JOIN COMTNEMPLYRSCRTYESTBS B ON A.ESNTL_ID = B.SCRTY_DTRMN_TRGET_ID WHERE 1 = 1 <if test="searchKeyword != null and searchKeyword != ''"> <if test="searchCondition == 1">AND A.USER_ID LIKE '%'||#{searchKeyword}||'%' </if> <if test="searchCondition == 2">AND A.USER_NM LIKE '%'||#{searchKeyword}||'%' </if> <if test="searchCondition == 3">AND A.GROUP_ID = #{searchKeyword} </if> </if> <![CDATA[ ) ALL_LIST ) Z WHERE RNUM > #{firstIndex} AND RNUM <= #{firstIndex} + #{recordCountPerPage} ]]> </select> <insert id="insertAuthorGroup" parameterType="egovframework.com.sec.rgm.service.AuthorGroup"> INSERT INTO COMTNEMPLYRSCRTYESTBS ( SCRTY_DTRMN_TRGET_ID , MBER_TY_CODE , AUTHOR_CODE) VALUES ( #{uniqId} , #{mberTyCode} , #{authorCode}) </insert> <update id="updateAuthorGroup" parameterType="egovframework.com.sec.rgm.service.AuthorGroup"> UPDATE COMTNEMPLYRSCRTYESTBS SET MBER_TY_CODE=#{mberTyCode} , AUTHOR_CODE=#{authorCode} WHERE SCRTY_DTRMN_TRGET_ID=#{uniqId} </update> <delete id="deleteAuthorGroup"> DELETE FROM COMTNEMPLYRSCRTYESTBS WHERE SCRTY_DTRMN_TRGET_ID=#{uniqId} </delete> <select id="selectAuthorGroupListTotCnt" parameterType="egovframework.com.sec.rgm.service.AuthorGroupVO" resultType="int"> SELECT COUNT(*) AS totcnt FROM (SELECT MBER_ID USER_ID, MBER_NM USER_NM, GROUP_ID, 'USR01' MBER_TY_CODE FROM COMTNGNRLMBER UNION ALL SELECT ENTRPRS_MBER_ID USER_ID, CMPNY_NM USER_NM, GROUP_ID, 'USR02' MBER_TY_CODE FROM COMTNENTRPRSMBER UNION ALL SELECT EMPLYR_ID USER_ID, USER_NM USER_NM, GROUP_ID, 'USR03' MBER_TY_CODE FROM COMTNEMPLYRINFO ) A LEFT OUTER JOIN COMTNEMPLYRSCRTYESTBS B ON A.USER_ID = B.SCRTY_DTRMN_TRGET_ID WHERE 1 = 1 <if test="searchKeyword != null and searchKeyword != ''"> <if test="searchCondition == 1">AND A.USER_ID LIKE '%'||#{searchKeyword}||'%' </if> <if test="searchCondition == 2">AND A.USER_NM LIKE '%'||#{searchKeyword}||'%' </if> <if test="searchCondition == 3">AND A.GROUP_ID = #{searchKeyword} </if> </if> </select> </mapper>
{ "content_hash": "4e93be35ff6f517ff34a5baacb80a27d", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 127, "avg_line_length": 41.41463414634146, "alnum_prop": 0.4933254809579898, "repo_name": "dasomel/egovframework", "id": "784393a41c5d53a97adb83309f2ae826c86d8ac2", "size": "5094", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "common-component/v3.9.0/src/main/resources/egovframework/mapper/com/sec/rgm/EgovAuthorGroup_SQL_cubrid.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
class CreateVotes < ActiveRecord::Migration def change create_table :votes do |t| t.belongs_to :user, index: true t.belongs_to :post, index: true t.integer :weight, null: false t.timestamps null: false end add_foreign_key :votes, :users add_foreign_key :votes, :posts end end
{ "content_hash": "6e2373e6b9d44ac63c08fafe1c88c8a2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 43, "avg_line_length": 24.692307692307693, "alnum_prop": 0.6510903426791277, "repo_name": "GUC-SE-2015/redditRails", "id": "194582abd8ec01585d5fbffef648af9e72283b84", "size": "321", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reddit/db/migrate/20150206175334_create_votes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14802" }, { "name": "CoffeeScript", "bytes": "1266" }, { "name": "JavaScript", "bytes": "667" }, { "name": "Ruby", "bytes": "35728" } ], "symlink_target": "" }
import Controller from '@ember/controller'; import { computed } from '@ember/object'; export default Controller.extend({ modes: computed(function() { return ['tree', 'view', 'form', 'code', 'text']; }), mode: 'tree', name: 'JSONEditor' });
{ "content_hash": "29273aa6bc7f0d12917c3d57f233b94d", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 52, "avg_line_length": 25.3, "alnum_prop": 0.6403162055335968, "repo_name": "Glavin001/ember-jsoneditor", "id": "cce8bfdd2348b3a2a1632d813cd0a731ec1064e5", "size": "253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/dummy/app/controllers/application.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "800" }, { "name": "HTML", "bytes": "4025" }, { "name": "JavaScript", "bytes": "16003" } ], "symlink_target": "" }
'use strict'; /** * Module dependencies. */ var should = require('should'), mongoose = require('mongoose'), User = mongoose.model('User'), House = mongoose.model('House'); /** * Globals */ var user, house; /** * Unit tests */ describe('House Model Unit Tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: '[email protected]', username: 'username', password: 'password' }); user.save(function() { house = new House({ name: 'House Name', user: user }); done(); }); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return house.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function(done) { house.name = ''; return house.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { House.remove().exec(); User.remove().exec(); done(); }); });
{ "content_hash": "6a301fac05346b2f37eca401712b5ad8", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 87, "avg_line_length": 17.1875, "alnum_prop": 0.5890909090909091, "repo_name": "lodgefy/lfy-api", "id": "284d378cb5676b6f9988489ad522adad00dfeb2d", "size": "1100", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/tests/house.server.model.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "500" }, { "name": "HTML", "bytes": "27561" }, { "name": "JavaScript", "bytes": "108282" }, { "name": "Perl", "bytes": "48" }, { "name": "Shell", "bytes": "414" } ], "symlink_target": "" }