code stringlengths 9 256k |
|---|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Solution : <EOL> def singleNumber ( self , A ) : <EOL> """<STR_LIT>""" <EOL> storage = <NUM_LIT:0> <EOL> for element in A : <EOL> storage ^= element <EOL> return storage </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Solution : <EOL> def isIsomorphic ( self , s , t ) : <EOL> """<STR_LIT>""" <EOL> m = { } <EOL> mapped = set ( ) <EOL> for i in xrange ( len ( s ) ) : <EOL> if s [ i ] not in m and t [ i ] not in mapped : <EOL> m [ s [ i ] ] = t [ i ] <EOL> mapped . add ( t [ i ] ) <EOL> elif s [ i ] in m and m [ s [ i ] ] == t [ i ] : <EOL> pass <EOL> else : <EOL> return False <EOL> return True </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Queue : <EOL> def __init__ ( self ) : <EOL> self . in_stk = [ ] <EOL> self . out_stk = [ ] <EOL> def push ( self , x ) : <EOL> """<STR_LIT>""" <EOL> self . in_stk . append ( x ) <EOL> def pop ( self ) : <EOL> """<STR_LIT>""" <EOL> if not self . out_stk : <EOL> while self . in_stk : <EOL> self . out_stk . append ( self . in_stk . pop ( ) ) <EOL> self . out_stk . pop ( ) <EOL> def peek ( self ) : <EOL> """<STR_LIT>""" <EOL> if not self . out_stk : <EOL> while self . in_stk : <EOL> self . out_stk . append ( self . in_stk . pop ( ) ) <EOL> return self . out_stk [ - <NUM_LIT:1> ] <EOL> def empty ( self ) : <EOL> """<STR_LIT>""" <EOL> return not self . out_stk and not self . in_stk </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Solution ( object ) : <EOL> def threeSumSmaller ( self , nums , target ) : <EOL> """<STR_LIT>""" <EOL> nums . sort ( ) <EOL> cnt = <NUM_LIT:0> <EOL> n = len ( nums ) <EOL> for i in xrange ( n - <NUM_LIT:2> ) : <EOL> l = i + <NUM_LIT:1> <EOL> h = n - <NUM_LIT:1> <EOL> while l < h : <EOL> if nums [ i ] + nums [ l ] + nums [ h ] < target : <EOL> cnt += h - l <EOL> l += <NUM_LIT:1> <EOL> else : <EOL> h -= <NUM_LIT:1> <EOL> return cnt </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Solution ( object ) : <EOL> def findDuplicate ( self , nums ) : <EOL> """<STR_LIT>""" <EOL> f , s = <NUM_LIT:0> , <NUM_LIT:0> <EOL> while True : <EOL> f = nums [ nums [ f ] ] <EOL> s = nums [ s ] <EOL> if f == s : <EOL> break <EOL> t = <NUM_LIT:0> <EOL> while t != s : <EOL> t = nums [ t ] <EOL> s = nums [ s ] <EOL> return t <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> assert Solution ( ) . findDuplicate ( [ <NUM_LIT:1> , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> , <NUM_LIT:5> ] ) == <NUM_LIT:5> </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class TreeNode ( object ) : <EOL> def __init__ ( self , start , end , cnt = <NUM_LIT:0> ) : <EOL> self . start = start <EOL> self . end = end <EOL> self . cnt = cnt <EOL> self . left = None <EOL> self . right = None <EOL> class SegmentTree ( object ) : <EOL> def __init__ ( self , n ) : <EOL> self . root = self . build ( <NUM_LIT:0> , n ) <EOL> def build ( self , start , end ) : <EOL> if start >= end : return <EOL> if start == end - <NUM_LIT:1> : return TreeNode ( start , end ) <EOL> node = TreeNode ( start , end ) <EOL> node . left = self . build ( start , ( start + end ) / <NUM_LIT:2> ) <EOL> node . right = self . build ( ( start + end ) / <NUM_LIT:2> , end ) <EOL> return node <EOL> def inc ( self , idx , val ) : <EOL> cur = self . root <EOL> while cur : <EOL> cur . cnt += val <EOL> mid = ( cur . start + cur . end ) / <NUM_LIT:2> <EOL> if cur . start <= idx < mid : <EOL> cur = cur . left <EOL> elif mid <= idx < cur . end : <EOL> cur = cur . right <EOL> else : <EOL> return <EOL> def query_less ( self , cur , idx ) : <EOL> if not cur : <EOL> return <NUM_LIT:0> <EOL> mid = ( cur . start + cur . end ) / <NUM_LIT:2> <EOL> if cur . start <= idx < mid : <EOL> return self . query_less ( cur . left , idx ) <EOL> elif mid <= idx < cur . end : <EOL> return ( cur . left . cnt if cur . left else <NUM_LIT:0> ) + self . query_less ( cur . right , idx ) <EOL> else : <EOL> return <NUM_LIT:0> <EOL> class Solution ( object ) : <EOL> def countSmaller ( self , nums ) : <EOL> """<STR_LIT>""" <EOL> h = { } <EOL> for i , v in enumerate ( sorted ( nums ) ) : <EOL> h [ v ] = i <EOL> A = [ h [ v ] for v in nums ] <EOL> n = len ( A ) <EOL> st = SegmentTree ( n ) <EOL> ret = [ ] <EOL> for i in xrange ( n - <NUM_LIT:1> , - <NUM_LIT:1> , - <NUM_LIT:1> ) : <EOL> ret . append ( st . query_less ( st . root , A [ i ] ) ) <EOL> st . inc ( A [ i ] , <NUM_LIT:1> ) <EOL> return ret [ : : - <NUM_LIT:1> ] <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> assert Solution ( ) . countSmaller ( [ <NUM_LIT:5> , <NUM_LIT:2> , <NUM_LIT:6> , <NUM_LIT:1> ] ) == [ <NUM_LIT:2> , <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:0> ] <EOL> assert Solution ( ) . countSmaller ( [ - <NUM_LIT:1> , - <NUM_LIT:1> ] ) == [ <NUM_LIT:0> , <NUM_LIT:0> ] </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Solution : <EOL> def copyBooks ( self , pages , k ) : <EOL> """<STR_LIT>""" <EOL> n = len ( pages ) <EOL> s = [ <NUM_LIT:0> for _ in xrange ( n + <NUM_LIT:1> ) ] <EOL> for i in xrange ( <NUM_LIT:1> , n + <NUM_LIT:1> ) : <EOL> s [ i ] = s [ i - <NUM_LIT:1> ] + pages [ i - <NUM_LIT:1> ] <EOL> F = [ [ s [ j ] for j in xrange ( n + <NUM_LIT:1> ) ] for _ in xrange ( k + <NUM_LIT:1> ) ] <EOL> for i in xrange ( <NUM_LIT:2> , k + <NUM_LIT:1> ) : <EOL> l = <NUM_LIT:0> <EOL> r = <NUM_LIT:1> <EOL> while r < n + <NUM_LIT:1> : <EOL> F [ i ] [ r ] = min ( F [ i ] [ r ] , <EOL> max ( F [ i - <NUM_LIT:1> ] [ l ] , s [ r ] - s [ l ] ) <EOL> ) <EOL> if F [ i - <NUM_LIT:1> ] [ l ] < s [ r ] - s [ l ] and l < r : <EOL> l += <NUM_LIT:1> <EOL> else : <EOL> if l > <NUM_LIT:0> : l -= <NUM_LIT:1> <EOL> r += <NUM_LIT:1> <EOL> return F [ - <NUM_LIT:1> ] [ - <NUM_LIT:1> ] <EOL> class Solution_TLE : <EOL> def copyBooks ( self , pages , k ) : <EOL> """<STR_LIT>""" <EOL> n = len ( pages ) <EOL> s = [ <NUM_LIT:0> for _ in xrange ( n + <NUM_LIT:1> ) ] <EOL> for i in xrange ( <NUM_LIT:1> , n + <NUM_LIT:1> ) : <EOL> s [ i ] = s [ i - <NUM_LIT:1> ] + pages [ i - <NUM_LIT:1> ] <EOL> F = [ [ s [ j ] for j in xrange ( n + <NUM_LIT:1> ) ] for _ in xrange ( k + <NUM_LIT:1> ) ] <EOL> for i in xrange ( <NUM_LIT:2> , k + <NUM_LIT:1> ) : <EOL> for j in xrange ( <NUM_LIT:1> , n + <NUM_LIT:1> ) : <EOL> F [ i ] [ j ] = min ( <EOL> max ( F [ i - <NUM_LIT:1> ] [ t ] , s [ j ] - s [ t ] ) for t in xrange ( j ) <EOL> ) <EOL> return F [ - <NUM_LIT:1> ] [ - <NUM_LIT:1> ] <EOL> class Solution_search : <EOL> def copyBooks ( self , pages , k ) : <EOL> """<STR_LIT>""" <EOL> return self . bisect ( pages , k , sum ( pages ) / k , sum ( pages ) ) <EOL> def bisect ( self , pages , k , lower , upper ) : <EOL> """<STR_LIT>""" <EOL> while lower < upper : <EOL> mid = ( lower + upper ) / <NUM_LIT:2> <EOL> if self . valid ( pages , k , mid ) : <EOL> upper = mid <EOL> else : <EOL> lower = mid + <NUM_LIT:1> <EOL> return lower <EOL> def valid ( self , pages , k , limit ) : <EOL> cnt = <NUM_LIT:0> <EOL> k -= <NUM_LIT:1> <EOL> for p in pages : <EOL> if p > limit : return False <EOL> cnt += p <EOL> if cnt > limit : <EOL> cnt = p <EOL> k -= <NUM_LIT:1> <EOL> if k < <NUM_LIT:0> : return False <EOL> return True <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> assert Solution ( ) . copyBooks ( [ <NUM_LIT:3> , <NUM_LIT:2> ] , <NUM_LIT:5> ) == <NUM_LIT:3> </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Node ( object ) : <EOL> def __init__ ( self , key , val ) : <EOL> self . key = key <EOL> self . val = val <EOL> self . pre , self . next = None , None <EOL> class LRUCache ( object ) : <EOL> def __init__ ( self , capacity ) : <EOL> self . cap = capacity <EOL> self . map = { } <EOL> self . head = None <EOL> self . tail = None <EOL> def get ( self , key ) : <EOL> if key in self . map : <EOL> cur = self . map [ key ] <EOL> self . _elevate ( cur ) <EOL> return cur . val <EOL> return - <NUM_LIT:1> <EOL> def set ( self , key , value ) : <EOL> if key in self . map : <EOL> cur = self . map [ key ] <EOL> cur . val = value <EOL> self . _elevate ( cur ) <EOL> else : <EOL> cur = Node ( key , value ) <EOL> self . map [ key ] = cur <EOL> self . _appendleft ( cur ) <EOL> if len ( self . map ) > self . cap : <EOL> last = self . _pop ( ) <EOL> del self . map [ last . key ] <EOL> def _appendleft ( self , cur ) : <EOL> """<STR_LIT>""" <EOL> if not self . head and not self . tail : <EOL> self . head = cur <EOL> self . tail = cur <EOL> return <EOL> head = self . head <EOL> cur . next , cur . pre , head . pre = head , None , cur <EOL> self . head = cur <EOL> def _pop ( self ) : <EOL> """<STR_LIT>""" <EOL> last = self . tail <EOL> if self . head == self . tail : <EOL> self . head , self . tail = None , None <EOL> return last <EOL> pre = last . pre <EOL> pre . next = None <EOL> self . tail = pre <EOL> return last <EOL> def _elevate ( self , cur ) : <EOL> """<STR_LIT>""" <EOL> pre , nxt = cur . pre , cur . next <EOL> if not pre : <EOL> return <EOL> elif not nxt : <EOL> assert self . tail == cur <EOL> self . _pop ( ) <EOL> else : <EOL> pre . next , nxt . pre = nxt , pre <EOL> self . _appendleft ( cur ) </s>
|
<s> """<STR_LIT>""" <EOL> import random <EOL> __author__ = '<STR_LIT>' <EOL> class Point ( object ) : <EOL> def __init__ ( self , a = <NUM_LIT:0> , b = <NUM_LIT:0> ) : <EOL> self . x = a <EOL> self . y = b <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % ( self . x , self . y ) <EOL> class UnionFind ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , rows , cols ) : <EOL> self . pi = [ - <NUM_LIT:1> for _ in xrange ( rows * cols ) ] <EOL> self . sz = [ - <NUM_LIT:1> for _ in xrange ( rows * cols ) ] <EOL> self . count = <NUM_LIT:0> <EOL> def add ( self , item ) : <EOL> if self . pi [ item ] == - <NUM_LIT:1> : <EOL> self . pi [ item ] = item <EOL> self . sz [ item ] = <NUM_LIT:1> <EOL> self . count += <NUM_LIT:1> <EOL> def union ( self , a , b ) : <EOL> pi1 = self . _pi ( a ) <EOL> pi2 = self . _pi ( b ) <EOL> if pi1 != pi2 : <EOL> if self . sz [ pi1 ] > self . sz [ pi2 ] : <EOL> pi1 , pi2 = pi2 , pi1 <EOL> self . pi [ pi1 ] = pi2 <EOL> self . sz [ pi2 ] += self . sz [ pi1 ] <EOL> self . count -= <NUM_LIT:1> <EOL> def _pi ( self , item ) : <EOL> pi = self . pi [ item ] <EOL> if item != pi : <EOL> self . pi [ item ] = self . _pi ( pi ) <EOL> return self . pi [ item ] <EOL> class Solution : <EOL> def __init__ ( self ) : <EOL> self . dirs = ( ( - <NUM_LIT:1> , <NUM_LIT:0> ) , ( <NUM_LIT:1> , <NUM_LIT:0> ) , ( <NUM_LIT:0> , - <NUM_LIT:1> ) , ( <NUM_LIT:0> , <NUM_LIT:1> ) ) <EOL> def numIslands2 ( self , n , m , operators ) : <EOL> """<STR_LIT>""" <EOL> rows = n <EOL> cols = m <EOL> unroll = lambda x , y : x * cols + y <EOL> mat = [ [ <NUM_LIT:0> for _ in xrange ( cols ) ] for _ in xrange ( rows ) ] <EOL> uf = UnionFind ( rows , cols ) <EOL> ret = [ ] <EOL> for op in operators : <EOL> uf . add ( unroll ( op . x , op . y ) ) <EOL> mat [ op . x ] [ op . y ] = <NUM_LIT:1> <EOL> for dir in self . dirs : <EOL> x1 = op . x + dir [ <NUM_LIT:0> ] <EOL> y1 = op . y + dir [ <NUM_LIT:1> ] <EOL> if <NUM_LIT:0> <= x1 < rows and <NUM_LIT:0> <= y1 < cols and mat [ x1 ] [ y1 ] == <NUM_LIT:1> : <EOL> uf . union ( unroll ( op . x , op . y ) , unroll ( x1 , y1 ) ) <EOL> ret . append ( uf . count ) <EOL> return ret <EOL> class TestCaseGenerator ( object ) : <EOL> def _generate ( self ) : <EOL> dim = <NUM_LIT:10> <EOL> m = random . randrange ( <NUM_LIT:1> , dim ) <EOL> n = random . randrange ( <NUM_LIT:1> , dim ) <EOL> k = random . randrange ( <NUM_LIT:1> , max ( <NUM_LIT:2> , m * n / <NUM_LIT:3> ) ) <EOL> operators = [ ] <EOL> visited = set ( ) <EOL> while len ( operators ) < k : <EOL> p = random . randrange ( m * n ) <EOL> if p not in visited : <EOL> x = p / n <EOL> y = p % n <EOL> operators . append ( Point ( x , y ) ) <EOL> visited . add ( p ) <EOL> print ( m ) <EOL> print ( n ) <EOL> print ( operators ) <EOL> def generate ( self , T = <NUM_LIT:50> ) : <EOL> for _ in xrange ( T ) : <EOL> self . _generate ( ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> assert Solution ( ) . numIslands2 ( <NUM_LIT:3> , <NUM_LIT:3> , map ( lambda x : Point ( x [ <NUM_LIT:0> ] , x [ <NUM_LIT:1> ] ) , [ ( <NUM_LIT:0> , <NUM_LIT:0> ) , ( <NUM_LIT:0> , <NUM_LIT:1> ) , ( <NUM_LIT:2> , <NUM_LIT:2> ) , ( <NUM_LIT:2> , <NUM_LIT:1> ) ] ) ) == [ <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:2> , <EOL> <NUM_LIT:2> ] <EOL> testcase = TestCaseGenerator ( ) <EOL> testcase . generate ( ) </s>
|
<s> """<STR_LIT>""" <EOL> __author__ = '<STR_LIT>' <EOL> class Solution : <EOL> def submatrixSum ( self , matrix ) : <EOL> """<STR_LIT>""" <EOL> m = len ( matrix ) <EOL> n = len ( matrix [ <NUM_LIT:0> ] ) <EOL> to_top = [ [ <NUM_LIT:0> for _ in xrange ( n + <NUM_LIT:1> ) ] for _ in xrange ( m + <NUM_LIT:1> ) ] <EOL> for i in xrange ( <NUM_LIT:1> , m + <NUM_LIT:1> ) : <EOL> for j in xrange ( <NUM_LIT:1> , n + <NUM_LIT:1> ) : <EOL> to_top [ i ] [ j ] = to_top [ i - <NUM_LIT:1> ] [ j ] + matrix [ i - <NUM_LIT:1> ] [ j - <NUM_LIT:1> ] <EOL> for up in xrange ( m ) : <EOL> for down in xrange ( up , m ) : <EOL> h = { } <EOL> s = <NUM_LIT:0> <EOL> h [ s ] = - <NUM_LIT:1> <EOL> for j in xrange ( n ) : <EOL> s += to_top [ down + <NUM_LIT:1> ] [ j + <NUM_LIT:1> ] - to_top [ up ] [ j + <NUM_LIT:1> ] <EOL> if s in h : <EOL> return [ [ up , h [ s ] + <NUM_LIT:1> ] , [ down , j ] ] <EOL> h [ s ] = j <EOL> return [ [ - <NUM_LIT:1> , - <NUM_LIT:1> ] , [ - <NUM_LIT:1> , - <NUM_LIT:1> ] ] <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> assert Solution ( ) . submatrixSum ( [ <EOL> [ <NUM_LIT:1> , <NUM_LIT:5> , <NUM_LIT:7> ] , <EOL> [ <NUM_LIT:3> , <NUM_LIT:7> , - <NUM_LIT:8> ] , <EOL> [ <NUM_LIT:4> , - <NUM_LIT:8> , <NUM_LIT:9> ] , <EOL> ] ) == [ [ <NUM_LIT:1> , <NUM_LIT:1> ] , [ <NUM_LIT:2> , <NUM_LIT:2> ] ] </s>
|
<s> import active <EOL> import unittest <EOL> import numpy as np ; <EOL> import common <EOL> from Matrix_Utils import * ; <EOL> class ActiveTester ( unittest . TestCase ) : <EOL> def test_active ( self ) : <EOL> a = np . array ( [ [ <NUM_LIT:1.0> , <NUM_LIT:2> ] , [ <NUM_LIT:0> , <NUM_LIT:0> ] , [ - <NUM_LIT:1> , - <NUM_LIT:2> ] ] ) ; <EOL> standard = np . array ( [ [ <NUM_LIT> , <NUM_LIT> ] , [ <NUM_LIT:0.5> , <NUM_LIT:0.5> ] , [ <NUM_LIT> , <NUM_LIT> ] ] ) ; <EOL> a_sgmoid = active . active ( a ) ; <EOL> self . assertEqual ( is_matrix_equals ( a_sgmoid , standard ) , True ) ; <EOL> a_linear = active . active ( a , '<STR_LIT>' ) ; <EOL> self . assertEqual ( is_matrix_equals ( a_linear , a ) , True ) ; <EOL> a = np . array ( [ [ <NUM_LIT:0.1> , - <NUM_LIT> ] , [ <NUM_LIT:0> , <NUM_LIT:10> ] ] ) ; <EOL> standard = np . array ( [ [ <NUM_LIT> , - <NUM_LIT> ] , [ <NUM_LIT:0> , <NUM_LIT> ] ] ) ; <EOL> a_tanh = active . active ( a , "<STR_LIT>" ) ; <EOL> self . assertTrue ( is_matrix_equals ( a_tanh , standard ) ) ; <EOL> standard = np . array ( [ [ <NUM_LIT:0.1> , <NUM_LIT:0> ] , [ <NUM_LIT:0> , <NUM_LIT:10> ] ] ) ; <EOL> a_rel = active . active ( a , "<STR_LIT:relu>" ) ; <EOL> self . assertTrue ( is_matrix_equals ( a_rel , standard ) ) ; <EOL> with self . assertRaises ( Exception ) : <EOL> active . active ( a , "<STR_LIT>" ) <EOL> def test_loss ( self ) : <EOL> a = np . array ( [ [ <NUM_LIT:0.1> , <NUM_LIT> ] , [ <NUM_LIT> , <NUM_LIT> ] ] ) ; <EOL> y = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:0> ] , [ <NUM_LIT:0> , <NUM_LIT:1> ] ] ) ; <EOL> idx = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:1> ] , [ <NUM_LIT:1> , <NUM_LIT:0> ] ] ) ; <EOL> loss = active . loss ( a , y ) ; <EOL> self . assertLess ( abs ( loss - <NUM_LIT> ) , <NUM_LIT> ) ; <EOL> loss = active . loss ( a , y , idx = idx ) ; <EOL> self . assertLess ( abs ( loss - <NUM_LIT> ) , <NUM_LIT> ) ; <EOL> loss = active . loss ( a , y , "<STR_LIT>" ) ; <EOL> self . assertLess ( abs ( loss - <NUM_LIT> ) , <NUM_LIT> ) ; <EOL> loss = active . loss ( a , y , "<STR_LIT>" , idx ) ; <EOL> self . assertLess ( abs ( loss - <NUM_LIT> ) , <NUM_LIT> ) ; <EOL> '''<STR_LIT>''' <EOL> with self . assertRaises ( Exception ) : <EOL> active . loss ( a , y , "<STR_LIT>" ) ; <EOL> def test_grad ( self ) : <EOL> a = np . array ( [ [ <NUM_LIT:0.1> , <NUM_LIT> ] , [ <NUM_LIT> , <NUM_LIT> ] ] ) ; <EOL> y = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:0> ] , [ <NUM_LIT:0> , <NUM_LIT:1> ] ] ) ; <EOL> with self . assertRaises ( Exception ) : <EOL> active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> grad = active . grad ( a , y , grad_type = "<STR_LIT>" ) ; <EOL> tx = np . array ( [ [ - <NUM_LIT> , <NUM_LIT> ] , [ <NUM_LIT> , - <NUM_LIT:0.1> ] ] ) ; <EOL> self . assertTrue ( is_matrix_equals ( grad , tx ) , True ) ; <EOL> grad = active . grad ( a , y , grad_type = "<STR_LIT>" ) ; <EOL> tx = np . array ( [ [ - <NUM_LIT> , <NUM_LIT> ] , [ <NUM_LIT> , - <NUM_LIT> ] ] ) ; <EOL> self . assertTrue ( is_matrix_equals ( grad , tx ) , True ) ; <EOL> a = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:1> , - <NUM_LIT:2> , <NUM_LIT:1> ] ] ) <EOL> y = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:0> ] ] ) <EOL> grad = active . grad ( a , y , grad_type = common . grad . linear_weighted_approximate_rank_pairwise ) <EOL> st = np . array ( [ [ - <NUM_LIT:1.0> , - <NUM_LIT:1.0> , <NUM_LIT:0> , <NUM_LIT:2> ] ] ) <EOL> self . assertTrue ( is_matrix_equals ( grad , st ) , True ) <EOL> a = np . array ( [ [ <NUM_LIT:0.1> , - <NUM_LIT:2> ] , [ <NUM_LIT> , <NUM_LIT:9> ] ] ) ; <EOL> y = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:0> ] , [ <NUM_LIT:0> , <NUM_LIT:1> ] ] ) ; <EOL> '''<STR_LIT>''' <EOL> a = np . array ( [ [ <NUM_LIT:0.1> , <NUM_LIT> ] , [ <NUM_LIT> , <NUM_LIT> ] ] ) ; <EOL> grad = active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> tx = np . array ( [ [ <NUM_LIT> , <NUM_LIT> ] , [ <NUM_LIT> , <NUM_LIT> ] ] ) ; <EOL> self . assertTrue ( is_matrix_equals ( grad , tx ) , True ) ; <EOL> grad = active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> tx = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:1> ] , [ <NUM_LIT:1> , <NUM_LIT:1> ] ] ) ; <EOL> self . assertTrue ( is_matrix_equals ( grad , tx ) , True ) ; <EOL> grad = active . grad ( a , grad_type = "<STR_LIT>" ) ; <EOL> tx = np . array ( [ [ <NUM_LIT> , <NUM_LIT> ] , [ <NUM_LIT> , <NUM_LIT> ] ] ) ; <EOL> self . assertTrue ( is_matrix_equals ( grad , tx ) , True ) ; <EOL> a = np . array ( [ [ <NUM_LIT:0.1> , - <NUM_LIT> ] , [ - <NUM_LIT> , <NUM_LIT:10> ] ] ) ; <EOL> grad = active . grad ( a , grad_type = "<STR_LIT:relu>" ) ; <EOL> tx = np . array ( [ [ <NUM_LIT:1> , <NUM_LIT:0> ] , [ <NUM_LIT:0> , <NUM_LIT:1> ] ] ) ; <EOL> self . assertTrue ( is_matrix_equals ( grad , tx ) , True ) ; <EOL> with self . assertRaises ( Exception ) : <EOL> active . grad ( a , y , "<STR_LIT>" ) ; </s>
|
<s> """<STR_LIT>""" <EOL> import sys <EOL> import os <EOL> from flask . ext . script import Manager <EOL> from flask . ext . migrate import Migrate , MigrateCommand <EOL> sys . path . append ( os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , os . path . pardir ) ) ) <EOL> from website import app , db <EOL> migrate = Migrate ( app , db ) <EOL> manager = Manager ( app ) <EOL> manager . add_command ( '<STR_LIT>' , MigrateCommand ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> manager . run ( ) </s>
|
<s> import begin <EOL> @ begin . start ( short_args = False ) <EOL> def run ( name = '<STR_LIT>' , quest = '<STR_LIT>' , colour = '<STR_LIT>' , * knights ) : <EOL> "<STR_LIT>" </s>
|
<s> import gc <EOL> import mock <EOL> import warnings <EOL> import sys <EOL> try : <EOL> import unittest2 as unittest <EOL> except ImportError : <EOL> import unittest <EOL> import magic <EOL> class TestMagic ( unittest . TestCase ) : <EOL> def test_has_version ( self ) : <EOL> self . assertTrue ( magic . __version__ ) <EOL> def test_consistent_database ( self ) : <EOL> with magic . Magic ( ) as m : <EOL> self . assertTrue ( m . consistent ) <EOL> def test_invalid_database ( self ) : <EOL> self . assertRaises ( magic . MagicError , magic . Magic , <EOL> paths = [ '<STR_LIT>' ] ) <EOL> def test_use_after_closed ( self ) : <EOL> with magic . Magic ( ) as m : <EOL> pass <EOL> self . assertRaises ( magic . MagicError , m . list , '<STR_LIT>' ) <EOL> def test_id_filename ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] ) as m : <EOL> id = m . id_filename ( '<STR_LIT>' ) <EOL> self . assertTrue ( id . startswith ( '<STR_LIT>' ) ) <EOL> def test_id_buffer ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] ) as m : <EOL> id = m . id_buffer ( '<STR_LIT>' ) <EOL> self . assertTrue ( id . startswith ( '<STR_LIT>' ) ) <EOL> def test_mime_type_file ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] , <EOL> flags = magic . MAGIC_MIME_TYPE ) as m : <EOL> id = m . id_filename ( '<STR_LIT>' ) <EOL> self . assertEqual ( id , '<STR_LIT>' ) <EOL> def test_mime_type_desc ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] , <EOL> flags = magic . MAGIC_MIME_TYPE ) as m : <EOL> id = m . id_buffer ( '<STR_LIT>' ) <EOL> self . assertEqual ( id , '<STR_LIT>' ) <EOL> def test_mime_encoding_file ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] , <EOL> flags = magic . MAGIC_MIME_ENCODING ) as m : <EOL> id = m . id_filename ( '<STR_LIT>' ) <EOL> self . assertEqual ( id , '<STR_LIT>' ) <EOL> def test_mime_encoding_desc ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] , <EOL> flags = magic . MAGIC_MIME_ENCODING ) as m : <EOL> id = m . id_buffer ( '<STR_LIT>' ) <EOL> self . assertEqual ( id , '<STR_LIT>' ) <EOL> def test_repr ( self ) : <EOL> with magic . Magic ( paths = [ '<STR_LIT>' ] , <EOL> flags = magic . MAGIC_MIME_ENCODING ) as m : <EOL> n = eval ( repr ( m ) , { '<STR_LIT>' : magic . Magic } ) <EOL> n . close ( ) <EOL> @ unittest . skipIf ( not hasattr ( unittest . TestCase , '<STR_LIT>' ) , <EOL> '<STR_LIT>' ) <EOL> def test_resource_warning ( self ) : <EOL> with self . assertWarns ( ResourceWarning ) : <EOL> m = magic . Magic ( ) <EOL> del m <EOL> @ unittest . skipIf ( hasattr ( sys , '<STR_LIT>' ) , <EOL> '<STR_LIT>' ) <EOL> def test_weakref ( self ) : <EOL> magic_close = magic . api . magic_close <EOL> with mock . patch ( '<STR_LIT>' ) as close_mock : <EOL> close_mock . side_effect = magic_close <EOL> with warnings . catch_warnings ( ) : <EOL> warnings . simplefilter ( '<STR_LIT:ignore>' ) <EOL> m = magic . Magic ( ) <EOL> del m <EOL> gc . collect ( ) <EOL> self . assertEqual ( close_mock . call_count , <NUM_LIT:1> ) <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> unittest . main ( ) </s>
|
<s> from __future__ import absolute_import , print_function , division <EOL> import petl as etl <EOL> table1 = [ [ '<STR_LIT:id>' , '<STR_LIT>' , '<STR_LIT:value>' ] , <EOL> [ '<STR_LIT:1>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:2>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:3>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:4>' , '<STR_LIT>' , '<STR_LIT>' ] ] <EOL> table2 = etl . capture ( table1 , '<STR_LIT>' , '<STR_LIT>' , <EOL> [ '<STR_LIT>' , '<STR_LIT:time>' ] ) <EOL> table2 <EOL> table3 = etl . capture ( table1 , '<STR_LIT>' , '<STR_LIT>' , <EOL> [ '<STR_LIT>' , '<STR_LIT:time>' ] , <EOL> include_original = True ) <EOL> table3 <EOL> import petl as etl <EOL> table1 = [ [ '<STR_LIT:id>' , '<STR_LIT>' , '<STR_LIT:value>' ] , <EOL> [ '<STR_LIT:1>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:2>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:3>' , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:4>' , '<STR_LIT>' , '<STR_LIT>' ] ] <EOL> table2 = etl . split ( table1 , '<STR_LIT>' , '<STR_LIT:d>' , [ '<STR_LIT>' , '<STR_LIT>' ] ) <EOL> table2 <EOL> import petl as etl <EOL> table1 = [ [ '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT:12> , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ] ] <EOL> table2 = etl . search ( table1 , '<STR_LIT>' ) <EOL> table2 <EOL> table3 = etl . search ( table1 , '<STR_LIT:foo>' , '<STR_LIT>' ) <EOL> table3 <EOL> import petl as etl <EOL> table1 = [ [ '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT:12> , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ] , <EOL> [ '<STR_LIT>' , <NUM_LIT> , '<STR_LIT>' ] ] <EOL> table2 = etl . searchcomplement ( table1 , '<STR_LIT>' ) <EOL> table2 <EOL> table3 = etl . searchcomplement ( table1 , '<STR_LIT:foo>' , '<STR_LIT>' ) <EOL> table3 </s>
|
<s> from __future__ import absolute_import , print_function , division <EOL> from petl . compat import PY2 <EOL> from petl . util . base import Table <EOL> from petl . io . sources import read_source_from_arg , write_source_from_arg <EOL> if PY2 : <EOL> from petl . io . csv_py2 import fromcsv_impl , tocsv_impl , appendcsv_impl , teecsv_impl <EOL> else : <EOL> from petl . io . csv_py3 import fromcsv_impl , tocsv_impl , appendcsv_impl , teecsv_impl <EOL> def fromcsv ( source = None , encoding = None , errors = '<STR_LIT:strict>' , ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> source = read_source_from_arg ( source ) <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return fromcsv_impl ( source = source , encoding = encoding , errors = errors , <EOL> ** csvargs ) <EOL> def fromtsv ( source = None , encoding = None , errors = '<STR_LIT:strict>' , ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return fromcsv ( source , encoding = encoding , errors = errors , ** csvargs ) <EOL> def tocsv ( table , source = None , encoding = None , errors = '<STR_LIT:strict>' , write_header = True , <EOL> ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> source = write_source_from_arg ( source ) <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> tocsv_impl ( table , source = source , encoding = encoding , errors = errors , <EOL> write_header = write_header , ** csvargs ) <EOL> Table . tocsv = tocsv <EOL> def appendcsv ( table , source = None , encoding = None , errors = '<STR_LIT:strict>' , <EOL> write_header = False , ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> source = write_source_from_arg ( source ) <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> appendcsv_impl ( table , source = source , encoding = encoding , errors = errors , <EOL> write_header = write_header , ** csvargs ) <EOL> Table . appendcsv = appendcsv <EOL> def totsv ( table , source = None , encoding = None , errors = '<STR_LIT:strict>' , <EOL> write_header = True , ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return tocsv ( table , source = source , encoding = encoding , errors = errors , <EOL> write_header = write_header , ** csvargs ) <EOL> Table . totsv = totsv <EOL> def appendtsv ( table , source = None , encoding = None , errors = '<STR_LIT:strict>' , <EOL> write_header = False , ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return appendcsv ( table , source = source , encoding = encoding , errors = errors , <EOL> write_header = write_header , ** csvargs ) <EOL> Table . appendtsv = appendtsv <EOL> def teecsv ( table , source = None , encoding = None , errors = '<STR_LIT:strict>' , write_header = True , <EOL> ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> source = write_source_from_arg ( source ) <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return teecsv_impl ( table , source = source , encoding = encoding , <EOL> errors = errors , write_header = write_header , <EOL> ** csvargs ) <EOL> Table . teecsv = teecsv <EOL> def teetsv ( table , source = None , encoding = None , errors = '<STR_LIT:strict>' , write_header = True , <EOL> ** csvargs ) : <EOL> """<STR_LIT>""" <EOL> csvargs . setdefault ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> return teecsv ( table , source = source , encoding = encoding , errors = errors , <EOL> write_header = write_header , ** csvargs ) <EOL> Table . teetsv = teetsv </s>
|
<s> from __future__ import absolute_import , print_function , division <EOL> from tempfile import NamedTemporaryFile <EOL> import io <EOL> from petl . test . helpers import eq_ <EOL> from petl . io . html import tohtml <EOL> def test_tohtml ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT:b>' , ( <NUM_LIT:1> , <NUM_LIT:2> ) ) , <EOL> ( '<STR_LIT:c>' , False ) ) <EOL> f = NamedTemporaryFile ( delete = False ) <EOL> tohtml ( table , f . name , encoding = '<STR_LIT:ascii>' , lineterminator = '<STR_LIT:\n>' ) <EOL> with io . open ( f . name , mode = '<STR_LIT>' , encoding = '<STR_LIT:ascii>' , newline = '<STR_LIT>' ) as o : <EOL> actual = o . read ( ) <EOL> expect = ( <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> ) <EOL> eq_ ( expect , actual ) <EOL> def test_tohtml_caption ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT:b>' , ( <NUM_LIT:1> , <NUM_LIT:2> ) ) ) <EOL> f = NamedTemporaryFile ( delete = False ) <EOL> tohtml ( table , f . name , encoding = '<STR_LIT:ascii>' , caption = '<STR_LIT>' , <EOL> lineterminator = '<STR_LIT:\n>' ) <EOL> with io . open ( f . name , mode = '<STR_LIT>' , encoding = '<STR_LIT:ascii>' , newline = '<STR_LIT>' ) as o : <EOL> actual = o . read ( ) <EOL> expect = ( <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> u"<STR_LIT>" <EOL> ) <EOL> eq_ ( expect , actual ) </s>
|
<s> from __future__ import absolute_import , print_function , division <EOL> import operator <EOL> from petl . compat import OrderedDict <EOL> from petl . test . helpers import ieq <EOL> from petl . util import strjoin <EOL> from petl . transform . reductions import rowreduce , aggregate , mergeduplicates , Conflict , fold <EOL> def test_rowreduce ( ) : <EOL> table1 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> ) ) <EOL> def sumbar ( key , rows ) : <EOL> return [ key , sum ( row [ <NUM_LIT:1> ] for row in rows ) ] <EOL> table2 = rowreduce ( table1 , key = '<STR_LIT:foo>' , reducer = sumbar , <EOL> header = [ '<STR_LIT:foo>' , '<STR_LIT>' ] ) <EOL> expect2 = ( ( '<STR_LIT:foo>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:10> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:12> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> ) ) <EOL> ieq ( expect2 , table2 ) <EOL> def test_rowreduce_fieldnameaccess ( ) : <EOL> table1 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> ) ) <EOL> def sumbar ( key , records ) : <EOL> return [ key , sum ( [ rec [ '<STR_LIT:bar>' ] for rec in records ] ) ] <EOL> table2 = rowreduce ( table1 , key = '<STR_LIT:foo>' , reducer = sumbar , <EOL> header = [ '<STR_LIT:foo>' , '<STR_LIT>' ] ) <EOL> expect2 = ( ( '<STR_LIT:foo>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:10> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:12> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> ) ) <EOL> ieq ( expect2 , table2 ) <EOL> def test_rowreduce_more ( ) : <EOL> table1 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:3> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:7> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:9> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:4> ) ) <EOL> def sumbar ( key , records ) : <EOL> return [ key , sum ( rec [ '<STR_LIT:bar>' ] for rec in records ) ] <EOL> table2 = rowreduce ( table1 , key = '<STR_LIT:foo>' , reducer = sumbar , <EOL> header = [ '<STR_LIT:foo>' , '<STR_LIT>' ] ) <EOL> expect2 = ( ( '<STR_LIT:foo>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:10> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:12> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:4> ) ) <EOL> ieq ( expect2 , table2 ) <EOL> def test_rowreduce_empty ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , ) <EOL> expect = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , ) <EOL> reducer = lambda key , rows : ( key , [ r [ <NUM_LIT:0> ] for r in rows ] ) <EOL> actual = rowreduce ( table , key = '<STR_LIT:foo>' , reducer = reducer , <EOL> header = ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) ) <EOL> ieq ( expect , actual ) <EOL> def test_aggregate_simple ( ) : <EOL> table1 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> , True ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> , False ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> , True ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> , False ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> , False ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> , True ) ) <EOL> table2 = aggregate ( table1 , '<STR_LIT:foo>' , len ) <EOL> expect2 = ( ( '<STR_LIT:foo>' , '<STR_LIT:value>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:3> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:1> ) ) <EOL> ieq ( expect2 , table2 ) <EOL> ieq ( expect2 , table2 ) <EOL> table3 = aggregate ( table1 , '<STR_LIT:foo>' , sum , '<STR_LIT:bar>' ) <EOL> expect3 = ( ( '<STR_LIT:foo>' , '<STR_LIT:value>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:10> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> ) ) <EOL> ieq ( expect3 , table3 ) <EOL> ieq ( expect3 , table3 ) <EOL> table4 = aggregate ( table1 , key = ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , aggregation = list , <EOL> value = ( '<STR_LIT:bar>' , '<STR_LIT>' ) ) <EOL> expect4 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT:value>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> , [ ( <NUM_LIT:3> , True ) ] ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> , [ ( <NUM_LIT:7> , False ) ] ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> , [ ( <NUM_LIT:2> , True ) , ( <NUM_LIT:2> , False ) ] ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> , [ ( <NUM_LIT:9> , False ) ] ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> , [ ( <NUM_LIT:4> , True ) ] ) ) <EOL> ieq ( expect4 , table4 ) <EOL> ieq ( expect4 , table4 ) <EOL> def test_aggregate_multifield ( ) : <EOL> table1 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> ) ) <EOL> aggregators = OrderedDict ( ) <EOL> aggregators [ '<STR_LIT:count>' ] = len <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , min <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , max <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , sum <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , list <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , strjoin ( '<STR_LIT:U+002CU+0020>' ) <EOL> table2 = aggregate ( table1 , '<STR_LIT:foo>' , aggregators ) <EOL> expect2 = ( ( '<STR_LIT:foo>' , '<STR_LIT:count>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:7> , <NUM_LIT:10> , [ <NUM_LIT:3> , <NUM_LIT:7> ] , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:3> , <NUM_LIT:1> , <NUM_LIT:9> , <NUM_LIT:12> , [ <NUM_LIT:2> , <NUM_LIT:1> , <NUM_LIT:9> ] , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:1> , <NUM_LIT:4> , <NUM_LIT:4> , <NUM_LIT:4> , [ <NUM_LIT:4> ] , '<STR_LIT:4>' ) ) <EOL> ieq ( expect2 , table2 ) <EOL> ieq ( expect2 , table2 ) <EOL> table3 = aggregate ( table1 , '<STR_LIT:foo>' ) <EOL> table3 [ '<STR_LIT:count>' ] = len <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , min <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , max <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , sum <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , strjoin ( '<STR_LIT:U+002CU+0020>' ) <EOL> ieq ( expect2 , table3 ) <EOL> aggregators = [ ( '<STR_LIT:count>' , len ) , <EOL> ( '<STR_LIT>' , '<STR_LIT:bar>' , min ) , <EOL> ( '<STR_LIT>' , '<STR_LIT:bar>' , max ) , <EOL> ( '<STR_LIT>' , '<STR_LIT:bar>' , sum ) , <EOL> ( '<STR_LIT>' , '<STR_LIT:bar>' , list ) , <EOL> ( '<STR_LIT>' , '<STR_LIT:bar>' , strjoin ( '<STR_LIT:U+002CU+0020>' ) ) ] <EOL> table4 = aggregate ( table1 , '<STR_LIT:foo>' , aggregators ) <EOL> ieq ( expect2 , table4 ) <EOL> ieq ( expect2 , table4 ) <EOL> def test_aggregate_more ( ) : <EOL> table1 = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:3> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:7> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:1> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:9> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:4> ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:3> ) ) <EOL> aggregators = OrderedDict ( ) <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , min <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , max <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , sum <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , strjoin ( '<STR_LIT:U+002CU+0020>' ) <EOL> table2 = aggregate ( table1 , '<STR_LIT:foo>' , aggregators ) <EOL> expect2 = ( ( '<STR_LIT:foo>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:3> , <NUM_LIT:7> , <NUM_LIT:10> , [ <NUM_LIT:3> , <NUM_LIT:7> ] , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:1> , <NUM_LIT:9> , <NUM_LIT:12> , [ <NUM_LIT:2> , <NUM_LIT:1> , <NUM_LIT:9> ] , '<STR_LIT>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:4> , <NUM_LIT:4> , <NUM_LIT:4> , [ <NUM_LIT:4> ] , '<STR_LIT:4>' ) , <EOL> ( '<STR_LIT>' , <NUM_LIT:3> , <NUM_LIT:3> , <NUM_LIT:3> , [ <NUM_LIT:3> ] , '<STR_LIT:3>' ) ) <EOL> ieq ( expect2 , table2 ) <EOL> ieq ( expect2 , table2 ) <EOL> table3 = aggregate ( table1 , '<STR_LIT:foo>' ) <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , min <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , max <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , sum <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' <EOL> table3 [ '<STR_LIT>' ] = '<STR_LIT:bar>' , strjoin ( '<STR_LIT:U+002CU+0020>' ) <EOL> ieq ( expect2 , table3 ) <EOL> def test_aggregate_multiple_source_fields ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> , True ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> , False ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> , True ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> , False ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> , False ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> , True ) ) <EOL> expect = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT:value>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:3> , [ ( <NUM_LIT:3> , True ) ] ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:7> , [ ( <NUM_LIT:7> , False ) ] ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:2> , [ ( <NUM_LIT:2> , True ) , ( <NUM_LIT:2> , False ) ] ) , <EOL> ( '<STR_LIT:b>' , <NUM_LIT:9> , [ ( <NUM_LIT:9> , False ) ] ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:4> , [ ( <NUM_LIT:4> , True ) ] ) ) <EOL> actual = aggregate ( table , ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , list , ( '<STR_LIT:bar>' , '<STR_LIT>' ) ) <EOL> ieq ( expect , actual ) <EOL> ieq ( expect , actual ) <EOL> actual = aggregate ( table , key = ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , aggregation = list , <EOL> value = ( '<STR_LIT:bar>' , '<STR_LIT>' ) ) <EOL> ieq ( expect , actual ) <EOL> ieq ( expect , actual ) <EOL> actual = aggregate ( table , key = ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) ) <EOL> actual [ '<STR_LIT:value>' ] = ( '<STR_LIT:bar>' , '<STR_LIT>' ) , list <EOL> ieq ( expect , actual ) <EOL> ieq ( expect , actual ) <EOL> def test_aggregate_empty ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , ) <EOL> aggregators = OrderedDict ( ) <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , min <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , max <EOL> aggregators [ '<STR_LIT>' ] = '<STR_LIT:bar>' , sum <EOL> actual = aggregate ( table , '<STR_LIT:foo>' , aggregators ) <EOL> expect = ( ( '<STR_LIT:foo>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) , ) <EOL> ieq ( expect , actual ) <EOL> def test_mergeduplicates ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:A>' , <NUM_LIT:1> , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT:B>' , '<STR_LIT:2>' , None ) , <EOL> ( '<STR_LIT:D>' , '<STR_LIT>' , <NUM_LIT> ) , <EOL> ( '<STR_LIT:B>' , None , u'<STR_LIT>' , True ) , <EOL> ( '<STR_LIT:E>' , None , <NUM_LIT> ) , <EOL> ( '<STR_LIT:D>' , '<STR_LIT>' , <NUM_LIT> ) , <EOL> ( '<STR_LIT:A>' , <NUM_LIT:2> , None ) ) <EOL> result = mergeduplicates ( table , '<STR_LIT:foo>' , missing = None ) <EOL> expectation = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:A>' , Conflict ( [ <NUM_LIT:1> , <NUM_LIT:2> ] ) , <NUM_LIT:2> ) , <EOL> ( '<STR_LIT:B>' , '<STR_LIT:2>' , u'<STR_LIT>' ) , <EOL> ( '<STR_LIT:D>' , '<STR_LIT>' , Conflict ( [ <NUM_LIT> , <NUM_LIT> ] ) ) , <EOL> ( '<STR_LIT:E>' , None , <NUM_LIT> ) ) <EOL> ieq ( expectation , result ) <EOL> def test_mergeduplicates_empty ( ) : <EOL> table = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , ) <EOL> expect = ( ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) , ) <EOL> actual = mergeduplicates ( table , key = '<STR_LIT:foo>' ) <EOL> ieq ( expect , actual ) <EOL> def test_mergeduplicates_shortrows ( ) : <EOL> table = [ [ '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:a>' , <NUM_LIT:1> , True ] , <EOL> [ '<STR_LIT:b>' , <NUM_LIT:2> , True ] , <EOL> [ '<STR_LIT:b>' , <NUM_LIT:3> ] ] <EOL> actual = mergeduplicates ( table , '<STR_LIT:foo>' ) <EOL> expect = [ ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:1> , True ) , <EOL> ( '<STR_LIT:b>' , Conflict ( [ <NUM_LIT:2> , <NUM_LIT:3> ] ) , True ) ] <EOL> ieq ( expect , actual ) <EOL> def test_mergeduplicates_compoundkey ( ) : <EOL> table = [ [ '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ] , <EOL> [ '<STR_LIT:a>' , <NUM_LIT:1> , True ] , <EOL> [ '<STR_LIT:a>' , <NUM_LIT:1> , True ] , <EOL> [ '<STR_LIT:a>' , <NUM_LIT:2> , False ] , <EOL> [ '<STR_LIT:a>' , <NUM_LIT:2> , None ] , <EOL> [ '<STR_LIT:c>' , <NUM_LIT:3> , True ] , <EOL> [ '<STR_LIT:c>' , <NUM_LIT:3> , False ] , <EOL> ] <EOL> actual = mergeduplicates ( table , key = ( '<STR_LIT:foo>' , '<STR_LIT:bar>' ) ) <EOL> expect = [ ( '<STR_LIT:foo>' , '<STR_LIT:bar>' , '<STR_LIT>' ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:1> , True ) , <EOL> ( '<STR_LIT:a>' , <NUM_LIT:2> , False ) , <EOL> ( '<STR_LIT:c>' , <NUM_LIT:3> , Conflict ( [ True , False ] ) ) ] <EOL> ieq ( expect , actual ) <EOL> def test_fold ( ) : <EOL> t1 = ( ( '<STR_LIT:id>' , '<STR_LIT:count>' ) , ( <NUM_LIT:1> , <NUM_LIT:3> ) , ( <NUM_LIT:1> , <NUM_LIT:5> ) , ( <NUM_LIT:2> , <NUM_LIT:4> ) , ( <NUM_LIT:2> , <NUM_LIT:8> ) ) <EOL> t2 = fold ( t1 , '<STR_LIT:id>' , operator . add , '<STR_LIT:count>' , presorted = True ) <EOL> expect = ( ( '<STR_LIT:key>' , '<STR_LIT:value>' ) , ( <NUM_LIT:1> , <NUM_LIT:8> ) , ( <NUM_LIT:2> , <NUM_LIT:12> ) ) <EOL> ieq ( expect , t2 ) <EOL> ieq ( expect , t2 ) </s>
|
<s> from __future__ import absolute_import , print_function , division <EOL> import operator <EOL> from petl . compat import OrderedDict , next , string_types , text_type <EOL> from petl . errors import ArgumentError <EOL> from petl . util . base import Table , expr , rowgroupby , Record <EOL> from petl . transform . sorts import sort <EOL> def fieldmap ( table , mappings = None , failonerror = False , errorvalue = None ) : <EOL> """<STR_LIT>""" <EOL> return FieldMapView ( table , mappings = mappings , failonerror = failonerror , <EOL> errorvalue = errorvalue ) <EOL> Table . fieldmap = fieldmap <EOL> class FieldMapView ( Table ) : <EOL> def __init__ ( self , source , mappings = None , failonerror = False , <EOL> errorvalue = None ) : <EOL> self . source = source <EOL> if mappings is None : <EOL> self . mappings = OrderedDict ( ) <EOL> else : <EOL> self . mappings = mappings <EOL> self . failonerror = failonerror <EOL> self . errorvalue = errorvalue <EOL> def __setitem__ ( self , key , value ) : <EOL> self . mappings [ key ] = value <EOL> def __iter__ ( self ) : <EOL> return iterfieldmap ( self . source , self . mappings , self . failonerror , <EOL> self . errorvalue ) <EOL> def iterfieldmap ( source , mappings , failonerror , errorvalue ) : <EOL> it = iter ( source ) <EOL> hdr = next ( it ) <EOL> flds = list ( map ( text_type , hdr ) ) <EOL> outhdr = mappings . keys ( ) <EOL> yield tuple ( outhdr ) <EOL> mapfuns = dict ( ) <EOL> for outfld , m in mappings . items ( ) : <EOL> if m in hdr : <EOL> mapfuns [ outfld ] = operator . itemgetter ( m ) <EOL> elif isinstance ( m , int ) and m < len ( hdr ) : <EOL> mapfuns [ outfld ] = operator . itemgetter ( m ) <EOL> elif isinstance ( m , string_types ) : <EOL> mapfuns [ outfld ] = expr ( m ) <EOL> elif callable ( m ) : <EOL> mapfuns [ outfld ] = m <EOL> elif isinstance ( m , ( tuple , list ) ) and len ( m ) == <NUM_LIT:2> : <EOL> srcfld = m [ <NUM_LIT:0> ] <EOL> fm = m [ <NUM_LIT:1> ] <EOL> if callable ( fm ) : <EOL> mapfuns [ outfld ] = composefun ( fm , srcfld ) <EOL> elif isinstance ( fm , dict ) : <EOL> mapfuns [ outfld ] = composedict ( fm , srcfld ) <EOL> else : <EOL> raise ArgumentError ( '<STR_LIT>' ) <EOL> else : <EOL> raise ArgumentError ( '<STR_LIT>' % ( outfld , m ) ) <EOL> it = ( Record ( row , flds ) for row in it ) <EOL> for row in it : <EOL> outrow = list ( ) <EOL> for outfld in outhdr : <EOL> try : <EOL> val = mapfuns [ outfld ] ( row ) <EOL> except Exception as e : <EOL> if failonerror : <EOL> raise e <EOL> else : <EOL> val = errorvalue <EOL> outrow . append ( val ) <EOL> yield tuple ( outrow ) <EOL> def composefun ( f , srcfld ) : <EOL> def g ( rec ) : <EOL> return f ( rec [ srcfld ] ) <EOL> return g <EOL> def composedict ( d , srcfld ) : <EOL> def g ( rec ) : <EOL> k = rec [ srcfld ] <EOL> if k in d : <EOL> return d [ k ] <EOL> else : <EOL> return k <EOL> return g <EOL> def rowmap ( table , rowmapper , header , failonerror = False ) : <EOL> """<STR_LIT>""" <EOL> return RowMapView ( table , rowmapper , header , failonerror = failonerror ) <EOL> Table . rowmap = rowmap <EOL> class RowMapView ( Table ) : <EOL> def __init__ ( self , source , rowmapper , header , failonerror = False ) : <EOL> self . source = source <EOL> self . rowmapper = rowmapper <EOL> self . header = header <EOL> self . failonerror = failonerror <EOL> def __iter__ ( self ) : <EOL> return iterrowmap ( self . source , self . rowmapper , self . header , <EOL> self . failonerror ) <EOL> def iterrowmap ( source , rowmapper , header , failonerror ) : <EOL> it = iter ( source ) <EOL> hdr = next ( it ) <EOL> flds = list ( map ( text_type , hdr ) ) <EOL> yield tuple ( header ) <EOL> it = ( Record ( row , flds ) for row in it ) <EOL> for row in it : <EOL> try : <EOL> outrow = rowmapper ( row ) <EOL> yield tuple ( outrow ) <EOL> except Exception as e : <EOL> if failonerror : <EOL> raise e <EOL> def rowmapmany ( table , rowgenerator , header , failonerror = False ) : <EOL> """<STR_LIT>""" <EOL> return RowMapManyView ( table , rowgenerator , header , failonerror = failonerror ) <EOL> Table . rowmapmany = rowmapmany <EOL> class RowMapManyView ( Table ) : <EOL> def __init__ ( self , source , rowgenerator , header , failonerror = False ) : <EOL> self . source = source <EOL> self . rowgenerator = rowgenerator <EOL> self . header = header <EOL> self . failonerror = failonerror <EOL> def __iter__ ( self ) : <EOL> return iterrowmapmany ( self . source , self . rowgenerator , self . header , <EOL> self . failonerror ) <EOL> def iterrowmapmany ( source , rowgenerator , header , failonerror ) : <EOL> it = iter ( source ) <EOL> hdr = next ( it ) <EOL> flds = list ( map ( text_type , hdr ) ) <EOL> yield tuple ( header ) <EOL> it = ( Record ( row , flds ) for row in it ) <EOL> for row in it : <EOL> try : <EOL> for outrow in rowgenerator ( row ) : <EOL> yield tuple ( outrow ) <EOL> except Exception as e : <EOL> if failonerror : <EOL> raise e <EOL> else : <EOL> pass <EOL> def rowgroupmap ( table , key , mapper , header = None , presorted = False , <EOL> buffersize = None , tempdir = None , cache = True ) : <EOL> """<STR_LIT>""" <EOL> return RowGroupMapView ( table , key , mapper , header = header , <EOL> presorted = presorted , <EOL> buffersize = buffersize , tempdir = tempdir , cache = cache ) <EOL> Table . rowgroupmap = rowgroupmap <EOL> class RowGroupMapView ( Table ) : <EOL> def __init__ ( self , source , key , mapper , header = None , <EOL> presorted = False , buffersize = None , tempdir = None , cache = True ) : <EOL> if presorted : <EOL> self . source = source <EOL> else : <EOL> self . source = sort ( source , key , buffersize = buffersize , <EOL> tempdir = tempdir , cache = cache ) <EOL> self . key = key <EOL> self . header = header <EOL> self . mapper = mapper <EOL> def __iter__ ( self ) : <EOL> return iterrowgroupmap ( self . source , self . key , self . mapper , self . header ) <EOL> def iterrowgroupmap ( source , key , mapper , header ) : <EOL> yield tuple ( header ) <EOL> for key , rows in rowgroupby ( source , key ) : <EOL> for row in mapper ( key , rows ) : <EOL> yield row </s>
|
<s> from __future__ import absolute_import , print_function , division <EOL> import logging <EOL> import inspect <EOL> import sys <EOL> import os <EOL> import time <EOL> from datetime import datetime <EOL> from itertools import islice <EOL> import numpy as np <EOL> from vcfnp . vcflib import PyVariantCallFile , TYPE_STRING , NUMBER_ALLELE , NUMBER_GENOTYPE <EOL> from vcfnp . compat import string_types <EOL> from vcfnp . iter import itervariants , itercalldata <EOL> import vcfnp . config as config <EOL> logger = logging . getLogger ( __name__ ) <EOL> debug = lambda msg : logger . debug ( '<STR_LIT>' % ( inspect . stack ( ) [ <NUM_LIT:1> ] [ <NUM_LIT:3> ] , msg ) ) <EOL> def variants ( vcf_fn , region = None , fields = None , exclude_fields = None , dtypes = None , <EOL> arities = None , fills = None , transformers = None , vcf_types = None , <EOL> count = None , progress = <NUM_LIT:0> , logstream = None , condition = None , <EOL> slice_args = None , flatten_filter = False , verbose = True , cache = False , <EOL> cachedir = None , skip_cached = False , truncate = True ) : <EOL> """<STR_LIT>""" <EOL> loader = _VariantsLoader ( vcf_fn , region = region , fields = fields , <EOL> exclude_fields = exclude_fields , dtypes = dtypes , <EOL> arities = arities , fills = fills , <EOL> transformers = transformers , vcf_types = vcf_types , <EOL> count = count , progress = progress , <EOL> logstream = logstream , condition = condition , <EOL> slice_args = slice_args , <EOL> flatten_filter = flatten_filter , verbose = verbose , <EOL> cache = cache , cachedir = cachedir , <EOL> skip_cached = skip_cached , truncate = truncate ) <EOL> return loader . load ( ) <EOL> class _ArrayLoader ( object ) : <EOL> """<STR_LIT>""" <EOL> array_type = None <EOL> def __init__ ( self , vcf_fn , logstream = None , verbose = True , ** kwargs ) : <EOL> debug ( '<STR_LIT>' ) <EOL> self . vcf_fn = vcf_fn <EOL> self . vcf_fns = _filenames_from_arg ( vcf_fn ) <EOL> self . log = _get_logger ( logstream , verbose ) <EOL> for k , v in kwargs . items ( ) : <EOL> setattr ( self , k , v ) <EOL> def load ( self ) : <EOL> log = self . log <EOL> array_type = self . array_type <EOL> vcf_fn = self . vcf_fn <EOL> region = self . region <EOL> cache = self . cache <EOL> cachedir = self . cachedir <EOL> skip_cached = self . skip_cached <EOL> if cache : <EOL> log ( '<STR_LIT>' ) <EOL> cache_fn , is_cached = _get_cache ( vcf_fn , array_type = array_type , <EOL> region = region , cachedir = cachedir , <EOL> log = log ) <EOL> if not is_cached : <EOL> log ( '<STR_LIT>' ) <EOL> arr = self . build ( ) <EOL> log ( '<STR_LIT>' , cache_fn ) <EOL> np . save ( cache_fn , arr ) <EOL> elif skip_cached : <EOL> log ( '<STR_LIT>' , cache_fn ) <EOL> arr = None <EOL> else : <EOL> log ( '<STR_LIT>' , cache_fn ) <EOL> arr = np . load ( cache_fn ) <EOL> else : <EOL> log ( '<STR_LIT>' ) <EOL> log ( '<STR_LIT>' ) <EOL> arr = self . build ( ) <EOL> return arr <EOL> def build ( self ) : <EOL> pass <EOL> def _filenames_from_arg ( filename ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( filename , string_types ) : <EOL> filenames = [ filename ] <EOL> elif isinstance ( filename , ( list , tuple ) ) : <EOL> filenames = filename <EOL> else : <EOL> raise Exception ( '<STR_LIT>' ) <EOL> for fn in filenames : <EOL> if not os . path . exists ( fn ) : <EOL> raise ValueError ( '<STR_LIT>' % fn ) <EOL> if not os . path . isfile ( fn ) : <EOL> raise ValueError ( '<STR_LIT>' % fn ) <EOL> return filenames <EOL> class _Logger ( object ) : <EOL> def __init__ ( self , logstream = None ) : <EOL> if logstream is None : <EOL> logstream = sys . stderr <EOL> self . logstream = logstream <EOL> def __call__ ( self , * msg ) : <EOL> s = ( '<STR_LIT>' <EOL> + str ( datetime . now ( ) ) <EOL> + '<STR_LIT>' <EOL> + '<STR_LIT:U+0020>' . join ( [ str ( m ) for m in msg ] ) ) <EOL> print ( s , file = self . logstream ) <EOL> self . logstream . flush ( ) <EOL> def _nolog ( * args , ** kwargs ) : <EOL> pass <EOL> def _get_logger ( logstream , verbose ) : <EOL> if verbose : <EOL> log = _Logger ( logstream ) <EOL> else : <EOL> log = _nolog <EOL> return log <EOL> def _mk_cache_fn ( vcf_fn , array_type , region = None , cachedir = None ) : <EOL> """<STR_LIT>""" <EOL> if cachedir is None : <EOL> cachedir = vcf_fn + config . CACHEDIR_SUFFIX <EOL> if not os . path . exists ( cachedir ) : <EOL> os . makedirs ( cachedir ) <EOL> else : <EOL> assert os . path . isdir ( cachedir ) , '<STR_LIT>' % cachedir <EOL> if region is None : <EOL> cache_fn = os . path . join ( cachedir , '<STR_LIT>' % array_type ) <EOL> else : <EOL> region = region . replace ( '<STR_LIT::>' , '<STR_LIT:_>' ) . replace ( '<STR_LIT:->' , '<STR_LIT:_>' ) <EOL> cache_fn = os . path . join ( cachedir , '<STR_LIT>' % ( array_type , region ) ) <EOL> return cache_fn <EOL> def _get_cache ( vcf_fn , array_type , region , cachedir , log ) : <EOL> """<STR_LIT>""" <EOL> if isinstance ( vcf_fn , ( list , tuple ) ) : <EOL> raise Exception ( <EOL> '<STR_LIT>' <EOL> ) <EOL> cache_fn = _mk_cache_fn ( vcf_fn , array_type = array_type , region = region , <EOL> cachedir = cachedir ) <EOL> if not os . path . exists ( cache_fn ) : <EOL> log ( '<STR_LIT>' ) <EOL> is_cached = False <EOL> elif os . path . getmtime ( vcf_fn ) > os . path . getmtime ( cache_fn ) : <EOL> is_cached = False <EOL> log ( '<STR_LIT>' ) <EOL> else : <EOL> is_cached = True <EOL> log ( '<STR_LIT>' ) <EOL> return cache_fn , is_cached <EOL> class _VariantsLoader ( _ArrayLoader ) : <EOL> """<STR_LIT>""" <EOL> array_type = '<STR_LIT>' <EOL> def build ( self ) : <EOL> log = self . log <EOL> vcf_fns = self . vcf_fns <EOL> vcf = PyVariantCallFile ( vcf_fns [ <NUM_LIT:0> ] ) <EOL> filter_ids = vcf . filter_ids <EOL> _warn_duplicates ( filter_ids ) <EOL> filter_ids = sorted ( set ( filter_ids ) ) <EOL> if '<STR_LIT>' not in filter_ids : <EOL> filter_ids . append ( '<STR_LIT>' ) <EOL> filter_ids = tuple ( filter_ids ) <EOL> _warn_duplicates ( vcf . info_ids ) <EOL> info_ids = tuple ( sorted ( set ( vcf . info_ids ) ) ) <EOL> info_types = vcf . info_types <EOL> info_counts = vcf . info_counts <EOL> fields = _variants_fields ( self . fields , self . exclude_fields , info_ids ) <EOL> parse_info = any ( [ f not in config . STANDARD_VARIANT_FIELDS <EOL> for f in fields ] ) <EOL> vcf_types = self . vcf_types <EOL> for f in fields : <EOL> if f not in config . STANDARD_VARIANT_FIELDS and f not in info_ids : <EOL> info_types [ f ] = TYPE_STRING <EOL> info_counts [ f ] = <NUM_LIT:1> <EOL> if vcf_types is not None and f in vcf_types : <EOL> info_types [ f ] = config . TYPESTRING2KEY [ vcf_types [ f ] ] <EOL> info_types = tuple ( info_types [ f ] if f in info_types else - <NUM_LIT:1> <EOL> for f in fields ) <EOL> info_counts = tuple ( info_counts [ f ] if f in info_counts else - <NUM_LIT:1> <EOL> for f in fields ) <EOL> arities = _variants_arities ( fields , self . arities , info_counts ) <EOL> fills = _variants_fills ( fields , self . fills , info_types ) <EOL> transformers = _info_transformers ( fields , self . transformers ) <EOL> flatten_filter = self . flatten_filter <EOL> dtype = _variants_dtype ( fields , self . dtypes , arities , filter_ids , <EOL> flatten_filter , info_types ) <EOL> region = self . region <EOL> truncate = self . truncate <EOL> condition = self . condition <EOL> if condition is not None : <EOL> condition = np . asarray ( condition ) . astype ( '<STR_LIT>' ) <EOL> it = itervariants ( vcf_fns , region = region , fields = fields , <EOL> arities = arities , fills = fills , <EOL> info_types = info_types , transformers = transformers , <EOL> filter_ids = filter_ids , flatten_filter = flatten_filter , <EOL> parse_info = parse_info , condition = condition , <EOL> truncate = truncate ) <EOL> slice_args = self . slice_args <EOL> if slice_args : <EOL> it = islice ( it , * slice_args ) <EOL> arr = _fromiter ( it , dtype , self . count , self . progress , log ) <EOL> return arr <EOL> def _warn_duplicates ( fields ) : <EOL> visited = set ( ) <EOL> for f in fields : <EOL> if f in visited : <EOL> print ( '<STR_LIT>' % f , <EOL> file = sys . stderr ) <EOL> visited . add ( f ) <EOL> def _variants_fields ( fields , exclude_fields , info_ids ) : <EOL> """<STR_LIT>""" <EOL> if fields is None : <EOL> fields = config . STANDARD_VARIANT_FIELDS + info_ids <EOL> else : <EOL> for f in fields : <EOL> if f not in config . STANDARD_VARIANT_FIELDS and f not in info_ids : <EOL> print ( '<STR_LIT>' % f , <EOL> file = sys . stderr ) <EOL> if exclude_fields is not None : <EOL> fields = [ f for f in fields if f not in exclude_fields ] <EOL> return tuple ( f for f in fields ) <EOL> def _variants_arities ( fields , arities , info_counts ) : <EOL> """<STR_LIT>""" <EOL> if arities is None : <EOL> arities = dict ( ) <EOL> for f , vcf_count in zip ( fields , info_counts ) : <EOL> if f == '<STR_LIT>' : <EOL> arities [ f ] = <NUM_LIT:1> <EOL> elif f not in arities : <EOL> if f in config . STANDARD_VARIANT_FIELDS : <EOL> arities [ f ] = config . DEFAULT_VARIANT_ARITY [ f ] <EOL> elif vcf_count == NUMBER_ALLELE : <EOL> arities [ f ] = <NUM_LIT:1> <EOL> elif vcf_count <= <NUM_LIT:0> : <EOL> arities [ f ] = <NUM_LIT:1> <EOL> else : <EOL> arities [ f ] = vcf_count <EOL> arities = tuple ( arities [ f ] for f in fields ) <EOL> return arities <EOL> def _variants_fills ( fields , fills , info_types ) : <EOL> """<STR_LIT>""" <EOL> if fills is None : <EOL> fills = dict ( ) <EOL> for f , vcf_type in zip ( fields , info_types ) : <EOL> if f == '<STR_LIT>' : <EOL> fills [ f ] = False <EOL> elif f not in fills : <EOL> if f in config . STANDARD_VARIANT_FIELDS : <EOL> fills [ f ] = config . DEFAULT_VARIANT_FILL [ f ] <EOL> else : <EOL> fills [ f ] = config . DEFAULT_FILL_MAP [ vcf_type ] <EOL> fills = tuple ( fills [ f ] for f in fields ) <EOL> return fills <EOL> def _info_transformers ( fields , transformers ) : <EOL> """<STR_LIT>""" <EOL> if transformers is None : <EOL> transformers = dict ( ) <EOL> for f in fields : <EOL> if f not in transformers : <EOL> transformers [ f ] = config . DEFAULT_TRANSFORMER . get ( f , None ) <EOL> return tuple ( transformers [ f ] for f in fields ) <EOL> def _variants_dtype ( fields , dtypes , arities , filter_ids , flatten_filter , <EOL> info_types ) : <EOL> """<STR_LIT>""" <EOL> dtype = list ( ) <EOL> for f , n , vcf_type in zip ( fields , arities , info_types ) : <EOL> if f == '<STR_LIT>' and flatten_filter : <EOL> for flt in filter_ids : <EOL> nm = '<STR_LIT>' + flt <EOL> dtype . append ( ( nm , '<STR_LIT>' ) ) <EOL> elif f == '<STR_LIT>' and not flatten_filter : <EOL> t = [ ( flt , '<STR_LIT>' ) for flt in filter_ids ] <EOL> dtype . append ( ( f , t ) ) <EOL> else : <EOL> if dtypes is not None and f in dtypes : <EOL> t = dtypes [ f ] <EOL> elif f in config . STANDARD_VARIANT_FIELDS : <EOL> t = config . DEFAULT_VARIANT_DTYPE [ f ] <EOL> elif f in config . DEFAULT_INFO_DTYPE : <EOL> t = config . DEFAULT_INFO_DTYPE [ f ] <EOL> else : <EOL> t = config . DEFAULT_TYPE_MAP [ vcf_type ] <EOL> if n == <NUM_LIT:1> : <EOL> dtype . append ( ( f , t ) ) <EOL> else : <EOL> dtype . append ( ( f , t , ( n , ) ) ) <EOL> return dtype <EOL> def _fromiter ( it , dtype , count , progress , log ) : <EOL> """<STR_LIT>""" <EOL> if progress > <NUM_LIT:0> : <EOL> it = _iter_withprogress ( it , progress , log ) <EOL> if count is not None : <EOL> a = np . fromiter ( it , dtype = dtype , count = count ) <EOL> else : <EOL> a = np . fromiter ( it , dtype = dtype ) <EOL> return a <EOL> def _iter_withprogress ( iterable , progress , log ) : <EOL> """<STR_LIT>""" <EOL> before_all = time . time ( ) <EOL> before = before_all <EOL> n = <NUM_LIT:0> <EOL> for i , o in enumerate ( iterable ) : <EOL> yield o <EOL> n = i + <NUM_LIT:1> <EOL> if n % progress == <NUM_LIT:0> : <EOL> after = time . time ( ) <EOL> log ( '<STR_LIT>' <EOL> % ( n , after - before_all , after - before , progress / ( after - before ) ) ) <EOL> before = after <EOL> after_all = time . time ( ) <EOL> log ( '<STR_LIT>' <EOL> % ( n , after_all - before_all , n / ( after_all - before_all ) ) ) <EOL> def calldata ( vcf_fn , region = None , samples = None , ploidy = <NUM_LIT:2> , fields = None , <EOL> exclude_fields = None , dtypes = None , arities = None , fills = None , <EOL> vcf_types = None , count = None , progress = <NUM_LIT:0> , logstream = None , <EOL> condition = None , slice_args = None , verbose = True , cache = False , <EOL> cachedir = None , skip_cached = False , truncate = True ) : <EOL> """<STR_LIT>""" <EOL> loader = _CalldataLoader ( vcf_fn , region = region , samples = samples , <EOL> ploidy = ploidy , fields = fields , <EOL> exclude_fields = exclude_fields , dtypes = dtypes , <EOL> arities = arities , fills = fills , vcf_types = vcf_types , <EOL> count = count , progress = progress , <EOL> logstream = logstream , condition = condition , <EOL> slice_args = slice_args , verbose = verbose , <EOL> cache = cache , cachedir = cachedir , <EOL> skip_cached = skip_cached , truncate = truncate ) <EOL> arr = loader . load ( ) <EOL> return arr <EOL> class _CalldataLoader ( _ArrayLoader ) : <EOL> array_type = '<STR_LIT>' <EOL> def build ( self ) : <EOL> log = self . log <EOL> vcf_fns = self . vcf_fns <EOL> vcf = PyVariantCallFile ( vcf_fns [ <NUM_LIT:0> ] ) <EOL> _warn_duplicates ( vcf . format_ids ) <EOL> format_ids = tuple ( sorted ( set ( vcf . format_ids ) ) ) <EOL> format_types = vcf . format_types <EOL> format_counts = vcf . format_counts <EOL> all_samples = vcf . sample_names <EOL> samples = self . samples <EOL> if samples is None : <EOL> samples = all_samples <EOL> else : <EOL> for s in samples : <EOL> assert s in all_samples , '<STR_LIT>' % s <EOL> samples = tuple ( samples ) <EOL> debug ( samples ) <EOL> fields = _calldata_fields ( self . fields , self . exclude_fields , format_ids ) <EOL> vcf_types = self . vcf_types <EOL> for f in fields : <EOL> if f not in config . STANDARD_CALLDATA_FIELDS and f not in format_ids : <EOL> format_types [ f ] = TYPE_STRING <EOL> format_counts [ f ] = <NUM_LIT:1> <EOL> if vcf_types is not None and f in vcf_types : <EOL> format_types [ f ] = config . TYPESTRING2KEY [ vcf_types [ f ] ] <EOL> format_types = tuple ( format_types [ f ] if f in format_types else - <NUM_LIT:1> <EOL> for f in fields ) <EOL> format_counts = tuple ( format_counts [ f ] if f in format_counts else - <NUM_LIT:1> <EOL> for f in fields ) <EOL> ploidy = self . ploidy <EOL> arities = _calldata_arities ( fields , self . arities , format_counts , ploidy ) <EOL> fills = _calldata_fills ( fields , self . fills , format_types , ploidy ) <EOL> dtype = _calldata_dtype ( fields , self . dtypes , format_types , arities , <EOL> samples , ploidy ) <EOL> condition = self . condition <EOL> if condition is not None : <EOL> condition = np . asarray ( condition ) . astype ( '<STR_LIT>' ) <EOL> region = self . region <EOL> truncate = self . truncate <EOL> it = itercalldata ( vcf_fns = vcf_fns , region = region , samples = samples , <EOL> ploidy = ploidy , fields = fields , arities = arities , <EOL> fills = fills , format_types = format_types , <EOL> condition = condition , truncate = truncate ) <EOL> slice_args = self . slice_args <EOL> if slice_args : <EOL> it = islice ( it , * slice_args ) <EOL> arr = _fromiter ( it , dtype , self . count , self . progress , log ) <EOL> return arr <EOL> def calldata_2d ( vcf_fn , region = None , samples = None , ploidy = <NUM_LIT:2> , fields = None , <EOL> exclude_fields = None , dtypes = None , arities = None , fills = None , <EOL> vcf_types = None , count = None , progress = <NUM_LIT:0> , logstream = None , <EOL> condition = None , slice_args = None , verbose = True , cache = False , <EOL> cachedir = None , skip_cached = False , truncate = True ) : <EOL> """<STR_LIT>""" <EOL> loader = _Calldata2DLoader ( vcf_fn , region = region , samples = samples , <EOL> ploidy = ploidy , fields = fields , <EOL> exclude_fields = exclude_fields , dtypes = dtypes , <EOL> arities = arities , fills = fills , <EOL> vcf_types = vcf_types , count = count , <EOL> progress = progress , logstream = logstream , <EOL> condition = condition , slice_args = slice_args , <EOL> verbose = verbose , cache = cache , cachedir = cachedir , <EOL> skip_cached = skip_cached , truncate = truncate ) <EOL> arr = loader . load ( ) <EOL> return arr <EOL> class _Calldata2DLoader ( _CalldataLoader ) : <EOL> array_type = '<STR_LIT>' <EOL> def build ( self ) : <EOL> arr = super ( _Calldata2DLoader , self ) . build ( ) <EOL> return view2d ( arr ) <EOL> def _calldata_fields ( fields , exclude_fields , format_ids ) : <EOL> """<STR_LIT>""" <EOL> if fields is None : <EOL> fields = config . STANDARD_CALLDATA_FIELDS + format_ids <EOL> else : <EOL> for f in fields : <EOL> if f not in config . STANDARD_CALLDATA_FIELDS and f not in format_ids : <EOL> print ( '<STR_LIT>' % f , <EOL> file = sys . stderr ) <EOL> if exclude_fields is not None : <EOL> fields = [ f for f in fields if f not in exclude_fields ] <EOL> return tuple ( fields ) <EOL> def _calldata_arities ( fields , arities , format_counts , ploidy ) : <EOL> if arities is None : <EOL> arities = dict ( ) <EOL> for f , vcf_count in zip ( fields , format_counts ) : <EOL> if f not in arities : <EOL> if f == '<STR_LIT>' : <EOL> arities [ f ] = ploidy <EOL> elif f in config . DEFAULT_CALLDATA_ARITY : <EOL> arities [ f ] = config . DEFAULT_CALLDATA_ARITY [ f ] <EOL> elif vcf_count == NUMBER_ALLELE : <EOL> arities [ f ] = <NUM_LIT:2> <EOL> elif vcf_count == NUMBER_GENOTYPE : <EOL> arities [ f ] = ploidy + <NUM_LIT:1> <EOL> elif vcf_count <= <NUM_LIT:0> : <EOL> arities [ f ] = <NUM_LIT:1> <EOL> else : <EOL> arities [ f ] = vcf_count <EOL> return tuple ( arities [ f ] for f in fields ) <EOL> def _calldata_fills ( fields , fills , format_types , ploidy ) : <EOL> if fills is None : <EOL> fills = dict ( ) <EOL> for f , vcf_type in zip ( fields , format_types ) : <EOL> if f not in fills : <EOL> if f == '<STR_LIT>' : <EOL> fills [ f ] = '<STR_LIT:/>' . join ( [ '<STR_LIT:.>' ] * ploidy ) <EOL> elif f in config . DEFAULT_CALLDATA_FILL : <EOL> fills [ f ] = config . DEFAULT_CALLDATA_FILL [ f ] <EOL> else : <EOL> fills [ f ] = config . DEFAULT_FILL_MAP [ vcf_type ] <EOL> return tuple ( fills [ f ] for f in fields ) <EOL> def _calldata_dtype ( fields , dtypes , format_types , arities , samples , ploidy ) : <EOL> cell_dtype = list ( ) <EOL> for f , vcf_type , n in zip ( fields , format_types , arities ) : <EOL> if dtypes is not None and f in dtypes : <EOL> t = dtypes [ f ] <EOL> elif f == '<STR_LIT>' : <EOL> t = '<STR_LIT>' % ( ( ploidy * <NUM_LIT:2> ) - <NUM_LIT:1> ) <EOL> elif f in config . DEFAULT_CALLDATA_DTYPE : <EOL> t = config . DEFAULT_CALLDATA_DTYPE [ f ] <EOL> else : <EOL> t = config . DEFAULT_TYPE_MAP [ vcf_type ] <EOL> if n == <NUM_LIT:1> : <EOL> cell_dtype . append ( ( f , t ) ) <EOL> else : <EOL> cell_dtype . append ( ( f , t , ( n , ) ) ) <EOL> dtype = [ ( s , cell_dtype ) for s in samples ] <EOL> return dtype <EOL> def view2d ( a ) : <EOL> """<STR_LIT>""" <EOL> rows = a . size <EOL> cols = len ( a . dtype ) <EOL> dtype = a . dtype [ <NUM_LIT:0> ] <EOL> b = a . view ( dtype ) . reshape ( rows , cols ) <EOL> return b </s>
|
<s> """<STR_LIT:U+0020>""" <EOL> import unittest <EOL> import warnings <EOL> class DeprecationTests ( unittest . TestCase ) : <EOL> def test_insecure_setup ( self ) : <EOL> with warnings . catch_warnings ( record = True ) as w : <EOL> from flask import Flask <EOL> from flask_limiter import Limiter <EOL> app = Flask ( __name__ ) <EOL> Limiter ( app ) <EOL> self . assertEqual ( len ( w ) , <NUM_LIT:1> ) </s>
|
<s> from aliyunsdkcore . request import RoaRequest <EOL> class GetJobDescriptionRequest ( RoaRequest ) : <EOL> def __init__ ( self ) : <EOL> RoaRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . set_uri_pattern ( self , '<STR_LIT>' ) <EOL> self . set_method ( self , '<STR_LIT:GET>' ) <EOL> def get_ResourceName ( self ) : <EOL> return self . get_path_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceName ( self , ResourceName ) : <EOL> self . add_path_param ( '<STR_LIT>' , ResourceName ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class ProductBindBsnRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_num ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_num ( self , num ) : <EOL> self . add_query_param ( '<STR_LIT>' , num ) <EOL> def get_resourceType ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_resourceType ( self , resourceType ) : <EOL> self . add_query_param ( '<STR_LIT>' , resourceType ) <EOL> def get_resourceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_resourceId ( self , resourceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , resourceId ) <EOL> def get_aliuid ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_aliuid ( self , aliuid ) : <EOL> self . add_query_param ( '<STR_LIT>' , aliuid ) </s>
|
<s> __author__ = '<STR_LIT>' <EOL> HTTP = "<STR_LIT:http>" <EOL> HTTPS = "<STR_LIT>" </s>
|
<s> '''<STR_LIT>''' <EOL> from setuptools import setup , find_packages <EOL> import os <EOL> """<STR_LIT>""" <EOL> PACKAGE = "<STR_LIT>" <EOL> NAME = "<STR_LIT>" <EOL> DESCRIPTION = "<STR_LIT>" <EOL> AUTHOR = "<STR_LIT>" <EOL> AUTHOR_EMAIL = "<STR_LIT>" <EOL> URL = "<STR_LIT>" <EOL> TOPDIR = os . path . dirname ( __file__ ) or "<STR_LIT:.>" <EOL> VERSION = __import__ ( PACKAGE ) . __version__ <EOL> desc_file = open ( "<STR_LIT>" ) <EOL> try : <EOL> LONG_DESCRIPTION = desc_file . read ( ) <EOL> finally : <EOL> desc_file . close ( ) <EOL> setup ( <EOL> name = NAME , <EOL> version = VERSION , <EOL> description = DESCRIPTION , <EOL> long_description = LONG_DESCRIPTION , <EOL> author = AUTHOR , <EOL> author_email = AUTHOR_EMAIL , <EOL> license = "<STR_LIT>" , <EOL> url = URL , <EOL> keywords = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] , <EOL> packages = find_packages ( exclude = [ "<STR_LIT>" ] ) , <EOL> include_package_data = True , <EOL> platforms = "<STR_LIT>" , <EOL> install_requires = [ "<STR_LIT>" ] , <EOL> classifiers = ( <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> ) <EOL> ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DeleteSecurityGroupRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_SecurityGroupId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SecurityGroupId ( self , SecurityGroupId ) : <EOL> self . add_query_param ( '<STR_LIT>' , SecurityGroupId ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DescribeSecurityGroupsRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_VpcId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_VpcId ( self , VpcId ) : <EOL> self . add_query_param ( '<STR_LIT>' , VpcId ) <EOL> def get_PageNumber ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_PageNumber ( self , PageNumber ) : <EOL> self . add_query_param ( '<STR_LIT>' , PageNumber ) <EOL> def get_PageSize ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_PageSize ( self , PageSize ) : <EOL> self . add_query_param ( '<STR_LIT>' , PageSize ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) <EOL> def get_SecurityGroupIds ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SecurityGroupIds ( self , SecurityGroupIds ) : <EOL> self . add_query_param ( '<STR_LIT>' , SecurityGroupIds ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class ModifyVpcAttributeRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_VpcId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_VpcId ( self , VpcId ) : <EOL> self . add_query_param ( '<STR_LIT>' , VpcId ) <EOL> def get_Description ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_Description ( self , Description ) : <EOL> self . add_query_param ( '<STR_LIT>' , Description ) <EOL> def get_VpcName ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_VpcName ( self , VpcName ) : <EOL> self . add_query_param ( '<STR_LIT>' , VpcName ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DescribeScalingGroupsRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_PageNumber ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_PageNumber ( self , PageNumber ) : <EOL> self . add_query_param ( '<STR_LIT>' , PageNumber ) <EOL> def get_PageSize ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_PageSize ( self , PageSize ) : <EOL> self . add_query_param ( '<STR_LIT>' , PageSize ) <EOL> def get_ScalingGroupId1 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId1 ( self , ScalingGroupId1 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId1 ) <EOL> def get_ScalingGroupId2 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId2 ( self , ScalingGroupId2 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId2 ) <EOL> def get_ScalingGroupId3 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId3 ( self , ScalingGroupId3 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId3 ) <EOL> def get_ScalingGroupId4 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId4 ( self , ScalingGroupId4 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId4 ) <EOL> def get_ScalingGroupId5 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId5 ( self , ScalingGroupId5 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId5 ) <EOL> def get_ScalingGroupId6 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId6 ( self , ScalingGroupId6 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId6 ) <EOL> def get_ScalingGroupId7 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId7 ( self , ScalingGroupId7 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId7 ) <EOL> def get_ScalingGroupId8 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId8 ( self , ScalingGroupId8 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId8 ) <EOL> def get_ScalingGroupId9 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId9 ( self , ScalingGroupId9 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId9 ) <EOL> def get_ScalingGroupId10 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId10 ( self , ScalingGroupId10 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId10 ) <EOL> def get_ScalingGroupId12 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId12 ( self , ScalingGroupId12 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId12 ) <EOL> def get_ScalingGroupId13 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId13 ( self , ScalingGroupId13 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId13 ) <EOL> def get_ScalingGroupId14 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId14 ( self , ScalingGroupId14 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId14 ) <EOL> def get_ScalingGroupId15 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId15 ( self , ScalingGroupId15 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId15 ) <EOL> def get_ScalingGroupId16 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId16 ( self , ScalingGroupId16 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId16 ) <EOL> def get_ScalingGroupId17 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId17 ( self , ScalingGroupId17 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId17 ) <EOL> def get_ScalingGroupId18 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId18 ( self , ScalingGroupId18 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId18 ) <EOL> def get_ScalingGroupId19 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId19 ( self , ScalingGroupId19 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId19 ) <EOL> def get_ScalingGroupId20 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupId20 ( self , ScalingGroupId20 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupId20 ) <EOL> def get_ScalingGroupName1 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName1 ( self , ScalingGroupName1 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName1 ) <EOL> def get_ScalingGroupName2 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName2 ( self , ScalingGroupName2 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName2 ) <EOL> def get_ScalingGroupName3 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName3 ( self , ScalingGroupName3 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName3 ) <EOL> def get_ScalingGroupName4 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName4 ( self , ScalingGroupName4 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName4 ) <EOL> def get_ScalingGroupName5 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName5 ( self , ScalingGroupName5 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName5 ) <EOL> def get_ScalingGroupName6 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName6 ( self , ScalingGroupName6 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName6 ) <EOL> def get_ScalingGroupName7 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName7 ( self , ScalingGroupName7 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName7 ) <EOL> def get_ScalingGroupName8 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName8 ( self , ScalingGroupName8 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName8 ) <EOL> def get_ScalingGroupName9 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName9 ( self , ScalingGroupName9 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName9 ) <EOL> def get_ScalingGroupName10 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName10 ( self , ScalingGroupName10 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName10 ) <EOL> def get_ScalingGroupName11 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName11 ( self , ScalingGroupName11 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName11 ) <EOL> def get_ScalingGroupName12 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName12 ( self , ScalingGroupName12 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName12 ) <EOL> def get_ScalingGroupName13 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName13 ( self , ScalingGroupName13 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName13 ) <EOL> def get_ScalingGroupName14 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName14 ( self , ScalingGroupName14 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName14 ) <EOL> def get_ScalingGroupName15 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName15 ( self , ScalingGroupName15 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName15 ) <EOL> def get_ScalingGroupName16 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName16 ( self , ScalingGroupName16 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName16 ) <EOL> def get_ScalingGroupName17 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName17 ( self , ScalingGroupName17 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName17 ) <EOL> def get_ScalingGroupName18 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName18 ( self , ScalingGroupName18 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName18 ) <EOL> def get_ScalingGroupName19 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName19 ( self , ScalingGroupName19 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName19 ) <EOL> def get_ScalingGroupName20 ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ScalingGroupName20 ( self , ScalingGroupName20 ) : <EOL> self . add_query_param ( '<STR_LIT>' , ScalingGroupName20 ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class QuerySnapshotJobListRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_SnapshotJobIds ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SnapshotJobIds ( self , SnapshotJobIds ) : <EOL> self . add_query_param ( '<STR_LIT>' , SnapshotJobIds ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> '''<STR_LIT>''' <EOL> from setuptools import setup , find_packages <EOL> import os <EOL> """<STR_LIT>""" <EOL> PACKAGE = "<STR_LIT>" <EOL> NAME = "<STR_LIT>" <EOL> DESCRIPTION = "<STR_LIT>" <EOL> AUTHOR = "<STR_LIT>" <EOL> AUTHOR_EMAIL = "<STR_LIT>" <EOL> URL = "<STR_LIT>" <EOL> TOPDIR = os . path . dirname ( __file__ ) or "<STR_LIT:.>" <EOL> VERSION = __import__ ( PACKAGE ) . __version__ <EOL> desc_file = open ( "<STR_LIT>" ) <EOL> try : <EOL> LONG_DESCRIPTION = desc_file . read ( ) <EOL> finally : <EOL> desc_file . close ( ) <EOL> setup ( <EOL> name = NAME , <EOL> version = VERSION , <EOL> description = DESCRIPTION , <EOL> long_description = LONG_DESCRIPTION , <EOL> author = AUTHOR , <EOL> author_email = AUTHOR_EMAIL , <EOL> license = "<STR_LIT>" , <EOL> url = URL , <EOL> keywords = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] , <EOL> packages = find_packages ( exclude = [ "<STR_LIT>" ] ) , <EOL> include_package_data = True , <EOL> platforms = "<STR_LIT>" , <EOL> install_requires = [ "<STR_LIT>" ] , <EOL> classifiers = ( <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> ) <EOL> ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DescribeInstanceConfigRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) <EOL> def get_InstanceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_InstanceId ( self , InstanceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , InstanceId ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DeleteGroupRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . set_protocol_type ( '<STR_LIT>' ) ; <EOL> def get_GroupName ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_GroupName ( self , GroupName ) : <EOL> self . add_query_param ( '<STR_LIT>' , GroupName ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class ListPolicyVersionsRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> self . set_protocol_type ( '<STR_LIT>' ) ; <EOL> def get_PolicyType ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_PolicyType ( self , PolicyType ) : <EOL> self . add_query_param ( '<STR_LIT>' , PolicyType ) <EOL> def get_PolicyName ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_PolicyName ( self , PolicyName ) : <EOL> self . add_query_param ( '<STR_LIT>' , PolicyName ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class CreateBackupRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_DBInstanceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBInstanceId ( self , DBInstanceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBInstanceId ) <EOL> def get_DBName ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBName ( self , DBName ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBName ) <EOL> def get_BackupMethod ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_BackupMethod ( self , BackupMethod ) : <EOL> self . add_query_param ( '<STR_LIT>' , BackupMethod ) <EOL> def get_BackupType ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_BackupType ( self , BackupType ) : <EOL> self . add_query_param ( '<STR_LIT>' , BackupType ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DescribeDatabasesRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_DBInstanceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBInstanceId ( self , DBInstanceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBInstanceId ) <EOL> def get_DBName ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBName ( self , DBName ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBName ) <EOL> def get_DBStatus ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBStatus ( self , DBStatus ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBStatus ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class ImportDataFromDatabaseRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_DBInstanceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBInstanceId ( self , DBInstanceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBInstanceId ) <EOL> def get_SourceDatabaseIp ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SourceDatabaseIp ( self , SourceDatabaseIp ) : <EOL> self . add_query_param ( '<STR_LIT>' , SourceDatabaseIp ) <EOL> def get_SourceDatabasePort ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SourceDatabasePort ( self , SourceDatabasePort ) : <EOL> self . add_query_param ( '<STR_LIT>' , SourceDatabasePort ) <EOL> def get_SourceDatabaseUserName ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SourceDatabaseUserName ( self , SourceDatabaseUserName ) : <EOL> self . add_query_param ( '<STR_LIT>' , SourceDatabaseUserName ) <EOL> def get_SourceDatabasePassword ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SourceDatabasePassword ( self , SourceDatabasePassword ) : <EOL> self . add_query_param ( '<STR_LIT>' , SourceDatabasePassword ) <EOL> def get_ImportDataType ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ImportDataType ( self , ImportDataType ) : <EOL> self . add_query_param ( '<STR_LIT>' , ImportDataType ) <EOL> def get_IsLockTable ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_IsLockTable ( self , IsLockTable ) : <EOL> self . add_query_param ( '<STR_LIT>' , IsLockTable ) <EOL> def get_SourceDatabaseDBNames ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_SourceDatabaseDBNames ( self , SourceDatabaseDBNames ) : <EOL> self . add_query_param ( '<STR_LIT>' , SourceDatabaseDBNames ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class UnlockDBInstanceRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_DBInstanceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_DBInstanceId ( self , DBInstanceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , DBInstanceId ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DeleteLoadBalancerRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_OwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerId ( self , OwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerId ) <EOL> def get_ResourceOwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerAccount ( self , ResourceOwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerAccount ) <EOL> def get_ResourceOwnerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_ResourceOwnerId ( self , ResourceOwnerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , ResourceOwnerId ) <EOL> def get_LoadBalancerId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_LoadBalancerId ( self , LoadBalancerId ) : <EOL> self . add_query_param ( '<STR_LIT>' , LoadBalancerId ) <EOL> def get_OwnerAccount ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_OwnerAccount ( self , OwnerAccount ) : <EOL> self . add_query_param ( '<STR_LIT>' , OwnerAccount ) </s>
|
<s> '''<STR_LIT>''' <EOL> from setuptools import setup , find_packages <EOL> import os <EOL> """<STR_LIT>""" <EOL> PACKAGE = "<STR_LIT>" <EOL> NAME = "<STR_LIT>" <EOL> DESCRIPTION = "<STR_LIT>" <EOL> AUTHOR = "<STR_LIT>" <EOL> AUTHOR_EMAIL = "<STR_LIT>" <EOL> URL = "<STR_LIT>" <EOL> TOPDIR = os . path . dirname ( __file__ ) or "<STR_LIT:.>" <EOL> VERSION = __import__ ( PACKAGE ) . __version__ <EOL> desc_file = open ( "<STR_LIT>" ) <EOL> try : <EOL> LONG_DESCRIPTION = desc_file . read ( ) <EOL> finally : <EOL> desc_file . close ( ) <EOL> setup ( <EOL> name = NAME , <EOL> version = VERSION , <EOL> description = DESCRIPTION , <EOL> long_description = LONG_DESCRIPTION , <EOL> author = AUTHOR , <EOL> author_email = AUTHOR_EMAIL , <EOL> license = "<STR_LIT>" , <EOL> url = URL , <EOL> keywords = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] , <EOL> packages = find_packages ( exclude = [ "<STR_LIT>" ] ) , <EOL> include_package_data = True , <EOL> platforms = "<STR_LIT>" , <EOL> install_requires = [ "<STR_LIT>" ] , <EOL> classifiers = ( <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> "<STR_LIT>" , <EOL> ) <EOL> ) </s>
|
<s> from aliyunsdkcore . request import RpcRequest <EOL> class DetectVulByIpRequest ( RpcRequest ) : <EOL> def __init__ ( self ) : <EOL> RpcRequest . __init__ ( self , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> def get_InstanceId ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_InstanceId ( self , InstanceId ) : <EOL> self . add_query_param ( '<STR_LIT>' , InstanceId ) <EOL> def get_VulIp ( self ) : <EOL> return self . get_query_params ( ) . get ( '<STR_LIT>' ) <EOL> def set_VulIp ( self , VulIp ) : <EOL> self . add_query_param ( '<STR_LIT>' , VulIp ) </s>
|
<s> from django import template <EOL> from django . template . loader import render_to_string <EOL> import tinymce . settings <EOL> register = template . Library ( ) <EOL> def tinymce_preview ( element_id ) : <EOL> return render_to_string ( '<STR_LIT>' , <EOL> { '<STR_LIT>' : tinymce . settings . JS_BASE_URL , '<STR_LIT>' : element_id } ) <EOL> register . simple_tag ( tinymce_preview ) </s>
|
<s> WEIXIN_LOGIN_DOMAIN = '<STR_LIT>' <EOL> WEIXIN_LOGIN_PAGE = '<STR_LIT>' <EOL> WEIXIN_APPID = '<STR_LIT>' <EOL> QRCODE_TAG_CLASSES = '<STR_LIT>' <EOL> WEIXIN_QRCODE_PAGE = WEIXIN_LOGIN_DOMAIN + WEIXIN_LOGIN_PAGE + WEIXIN_APPID </s>
|
<s> from django . db import models , migrations <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> operations = [ <EOL> migrations . AddField ( <EOL> model_name = '<STR_LIT>' , <EOL> name = '<STR_LIT>' , <EOL> field = models . TextField ( blank = True , default = '<STR_LIT>' ) , <EOL> preserve_default = False , <EOL> ) , <EOL> migrations . AddField ( <EOL> model_name = '<STR_LIT>' , <EOL> name = '<STR_LIT>' , <EOL> field = models . TextField ( blank = True , default = '<STR_LIT>' ) , <EOL> preserve_default = False , <EOL> ) , <EOL> ] </s>
|
<s> """<STR_LIT>""" <EOL> import functools as ft <EOL> from django . contrib . auth . models import User <EOL> from django . core . urlresolvers import reverse <EOL> from django . test import TestCase <EOL> from powerdns . models . authorisations import Authorisation <EOL> from powerdns . utils import AutoPtrOptions <EOL> from powerdns . tests . utils import ( <EOL> DomainFactory , <EOL> RecordFactory , <EOL> user_client , <EOL> ) <EOL> def get_url ( model , obj_ ) : <EOL> return reverse ( model + '<STR_LIT>' , kwargs = { '<STR_LIT>' : obj_ . pk } ) <EOL> get_domain_url = ft . partial ( get_url , '<STR_LIT>' ) <EOL> get_record_url = ft . partial ( get_url , '<STR_LIT>' ) <EOL> class TestPermissions ( TestCase ) : <EOL> """<STR_LIT>""" <EOL> def setUp ( self ) : <EOL> self . superuser = User . objects . create_superuser ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:password>' <EOL> ) <EOL> self . user = User . objects . create_user ( <EOL> '<STR_LIT:user>' , '<STR_LIT>' , '<STR_LIT:password>' <EOL> ) <EOL> self . su_domain = DomainFactory ( <EOL> name = '<STR_LIT>' , <EOL> owner = self . superuser , <EOL> ) <EOL> self . unrestricted_domain = DomainFactory ( <EOL> name = '<STR_LIT>' , <EOL> owner = self . superuser , <EOL> unrestricted = True , <EOL> ) <EOL> self . u_domain = DomainFactory ( <EOL> name = '<STR_LIT>' , <EOL> owner = self . user , <EOL> ) <EOL> self . su_record = RecordFactory ( <EOL> domain = self . su_domain , <EOL> name = '<STR_LIT>' , <EOL> type = '<STR_LIT:A>' , <EOL> content = '<STR_LIT>' , <EOL> owner = self . superuser , <EOL> auto_ptr = AutoPtrOptions . NEVER , <EOL> ) <EOL> self . u_record = RecordFactory ( <EOL> domain = self . u_domain , <EOL> name = '<STR_LIT>' , <EOL> type = '<STR_LIT:A>' , <EOL> content = '<STR_LIT>' , <EOL> owner = self . user , <EOL> auto_ptr = AutoPtrOptions . NEVER , <EOL> ) <EOL> self . su_client = user_client ( self . superuser ) <EOL> self . u_client = user_client ( self . user ) <EOL> def test_su_can_edit_all_domains ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . su_client . patch ( <EOL> get_domain_url ( self . u_domain ) , <EOL> { '<STR_LIT:type>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT:200> ) <EOL> def test_user_cant_edit_other_domains ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . patch ( <EOL> get_domain_url ( self . su_domain ) , <EOL> { '<STR_LIT:type>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_authorised_user_can_edit_other_domains ( self ) : <EOL> """<STR_LIT>""" <EOL> Authorisation . objects . create ( <EOL> owner = self . superuser , <EOL> target = self . su_domain , <EOL> authorised = self . user <EOL> ) <EOL> request = self . u_client . patch ( <EOL> get_domain_url ( self . su_domain ) , <EOL> { '<STR_LIT:type>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT:200> ) <EOL> def test_user_can_edit_her_domains ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . patch ( <EOL> get_domain_url ( self . u_domain ) , <EOL> { '<STR_LIT:type>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT:200> ) <EOL> def test_user_can_create_domain ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' } <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_user_can_subdomain_her_own ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' } <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_user_cant_subdomain_others ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { '<STR_LIT:name>' : '<STR_LIT>' } <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_su_can_edit_all_records ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . su_client . patch ( <EOL> get_record_url ( self . u_record ) , <EOL> { '<STR_LIT:content>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT:200> ) <EOL> def test_u_cant_edit_other_records ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . patch ( <EOL> get_record_url ( self . su_record ) , <EOL> { '<STR_LIT:content>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_authorised_user_can_edit_other_records ( self ) : <EOL> """<STR_LIT>""" <EOL> Authorisation . objects . create ( <EOL> owner = self . superuser , <EOL> target = self . su_record , <EOL> authorised = self . user , <EOL> ) <EOL> request = self . u_client . patch ( <EOL> get_record_url ( self . su_record ) , <EOL> { '<STR_LIT:content>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT:200> ) <EOL> def test_u_can_edit_her_records ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . patch ( <EOL> get_record_url ( self . u_record ) , <EOL> { '<STR_LIT:content>' : '<STR_LIT>' } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT:200> ) <EOL> def test_su_can_create_records ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . su_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT:content>' : '<STR_LIT>' , <EOL> '<STR_LIT:type>' : '<STR_LIT:A>' , <EOL> '<STR_LIT>' : get_domain_url ( self . u_domain ) , <EOL> '<STR_LIT>' : AutoPtrOptions . NEVER . id , <EOL> } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_user_can_create_records_in_her_domain ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . su_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT:content>' : '<STR_LIT>' , <EOL> '<STR_LIT:type>' : '<STR_LIT:A>' , <EOL> '<STR_LIT>' : get_domain_url ( self . u_domain ) , <EOL> '<STR_LIT>' : AutoPtrOptions . NEVER . id , <EOL> } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_user_can_create_records_in_unrestricted_domain ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT:content>' : '<STR_LIT>' , <EOL> '<STR_LIT:type>' : '<STR_LIT:A>' , <EOL> '<STR_LIT>' : get_domain_url ( self . unrestricted_domain ) , <EOL> '<STR_LIT>' : AutoPtrOptions . NEVER . id , <EOL> } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) <EOL> def test_user_cant_create_records_in_other_domains ( self ) : <EOL> """<STR_LIT>""" <EOL> request = self . u_client . post ( <EOL> reverse ( '<STR_LIT>' ) , <EOL> { <EOL> '<STR_LIT:name>' : '<STR_LIT>' , <EOL> '<STR_LIT:content>' : '<STR_LIT>' , <EOL> '<STR_LIT:type>' : '<STR_LIT:A>' , <EOL> '<STR_LIT>' : get_domain_url ( self . su_domain ) , <EOL> '<STR_LIT>' : AutoPtrOptions . NEVER . id , <EOL> } , <EOL> ) <EOL> self . assertEqual ( request . status_code , <NUM_LIT> ) </s>
|
<s> from django . conf import settings <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from ralph . accounts . admin import AssetList , AssignedLicenceList , UserInfoMixin <EOL> from ralph . admin . mixins import RalphBaseTemplateView , RalphTemplateView <EOL> from ralph . licences . models import BaseObjectLicence <EOL> class UserProfileView ( RalphTemplateView ) : <EOL> template_name = '<STR_LIT>' <EOL> class MyEquipmentAssetList ( AssetList ) : <EOL> def user_licence ( self , item ) : <EOL> licences = BaseObjectLicence . objects . filter ( <EOL> base_object = item . id <EOL> ) . select_related ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> if licences : <EOL> result = [ <EOL> '<STR_LIT>' . format ( <EOL> bo_licence . licence . software . name , <EOL> bo_licence . licence . niw , <EOL> ) for bo_licence in licences <EOL> ] <EOL> return [ '<STR_LIT>' . join ( result ) ] <EOL> else : <EOL> return [ ] <EOL> class CurrentUserInfoView ( UserInfoMixin , RalphBaseTemplateView ) : <EOL> template_name = '<STR_LIT>' <EOL> def get_context_data ( self , ** kwargs ) : <EOL> context = super ( ) . get_context_data ( ** kwargs ) <EOL> context [ '<STR_LIT>' ] = self . get_links ( ) <EOL> asset_fields = [ <EOL> ( '<STR_LIT>' , _ ( '<STR_LIT>' ) ) , <EOL> '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , ( '<STR_LIT>' , _ ( '<STR_LIT>' ) ) , '<STR_LIT>' , '<STR_LIT:status>' <EOL> ] <EOL> if settings . MY_EQUIPMENT_SHOW_BUYOUT_DATE : <EOL> asset_fields += [ '<STR_LIT>' ] <EOL> if settings . MY_EQUIPMENT_REPORT_FAILURE_URL : <EOL> asset_fields += [ '<STR_LIT>' ] <EOL> context [ '<STR_LIT>' ] = MyEquipmentAssetList ( <EOL> self . get_asset_queryset ( ) , <EOL> asset_fields , <EOL> [ '<STR_LIT>' ] , <EOL> request = self . request , <EOL> ) <EOL> context [ '<STR_LIT>' ] = AssignedLicenceList ( <EOL> self . get_licence_queryset ( ) , <EOL> [ <EOL> ( '<STR_LIT>' , _ ( '<STR_LIT>' ) ) , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> ] , <EOL> request = self . request , <EOL> ) <EOL> return context <EOL> def get_links ( self ) : <EOL> result = [ ] <EOL> links = getattr ( <EOL> settings , '<STR_LIT>' , [ ] <EOL> ) <EOL> kwargs = { <EOL> '<STR_LIT:username>' : self . request . user . username , <EOL> } <EOL> for link in links : <EOL> result . append ( { <EOL> '<STR_LIT:url>' : link [ '<STR_LIT:url>' ] . format ( ** kwargs ) , <EOL> '<STR_LIT:name>' : link [ '<STR_LIT:name>' ] <EOL> } ) <EOL> return result <EOL> def get_user ( self ) : <EOL> return self . request . user </s>
|
<s> from django import forms <EOL> from django . conf . urls import url <EOL> from django . contrib import messages <EOL> from django . core . urlresolvers import reverse <EOL> from django . db import IntegrityError , models , transaction <EOL> from django . forms import ValidationError <EOL> from django . http import HttpResponseForbidden , HttpResponseRedirect <EOL> from django . shortcuts import get_object_or_404 <EOL> from django . utils . safestring import mark_safe <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from ralph . admin . fields import ( <EOL> IntegerMultilineField , <EOL> MultilineField , <EOL> MultivalueFormMixin <EOL> ) <EOL> from ralph . admin . mixins import RalphTemplateView <EOL> from ralph . admin . sites import ralph_site <EOL> from ralph . helpers import get_model_view_url_name <EOL> class MultiAddView ( RalphTemplateView ) : <EOL> """<STR_LIT>""" <EOL> template_name = '<STR_LIT>' <EOL> def dispatch ( self , request , object_pk , model , * args , ** kwargs ) : <EOL> admin_model = ralph_site . _registry [ model ] <EOL> self . model = model <EOL> if not request . user . has_perm ( '<STR_LIT>' . format ( <EOL> self . model . _meta . app_label , self . model . _meta . model_name <EOL> ) ) : <EOL> return HttpResponseForbidden ( ) <EOL> self . info_fields = admin_model . multiadd_info_fields <EOL> self . obj = get_object_or_404 ( model , pk = object_pk ) <EOL> self . fields = admin_model . get_multiadd_fields ( obj = self . obj ) <EOL> self . clear_fields = admin_model . get_multiadd_clear_fields ( obj = self . obj ) <EOL> self . one_of_mulitval_required = admin_model . one_of_mulitvalue_required <EOL> return super ( ) . dispatch ( request , * args , ** kwargs ) <EOL> def get_form ( self ) : <EOL> form_kwargs = { } <EOL> multi_form_attrs = { <EOL> '<STR_LIT>' : [ i [ '<STR_LIT>' ] for i in self . fields ] , <EOL> '<STR_LIT>' : self . model , <EOL> '<STR_LIT>' : self . one_of_mulitval_required , <EOL> } <EOL> for item in self . fields : <EOL> field_type = self . model . _meta . get_field ( item [ '<STR_LIT>' ] ) <EOL> required = item . get ( '<STR_LIT>' , not field_type . blank ) <EOL> if isinstance ( field_type , models . IntegerField ) : <EOL> multi_form_attrs [ item [ '<STR_LIT>' ] ] = IntegerMultilineField ( <EOL> allow_duplicates = item [ '<STR_LIT>' ] , <EOL> required = required , <EOL> ) <EOL> else : <EOL> multi_form_attrs [ item [ '<STR_LIT>' ] ] = MultilineField ( <EOL> allow_duplicates = item [ '<STR_LIT>' ] , <EOL> required = required , <EOL> ) <EOL> multi_form = type ( <EOL> '<STR_LIT>' , ( MultivalueFormMixin , forms . Form ) , multi_form_attrs <EOL> ) <EOL> if self . request . method == '<STR_LIT:POST>' : <EOL> form_kwargs [ '<STR_LIT:data>' ] = self . request . POST <EOL> return multi_form ( ** form_kwargs ) <EOL> def get_context_data ( self , ** kwargs ) : <EOL> context = super ( ) . get_context_data ( ** kwargs ) <EOL> context [ '<STR_LIT>' ] = self . get_form ( ) <EOL> context [ '<STR_LIT>' ] = self . obj <EOL> context [ '<STR_LIT>' ] = self . info_fields <EOL> return context <EOL> def post ( self , request , * args , ** kwargs ) : <EOL> form = self . get_form ( ) <EOL> if form . is_valid ( ) : <EOL> try : <EOL> return self . form_valid ( form ) <EOL> except IntegrityError as e : <EOL> context = self . get_context_data ( ) <EOL> context [ '<STR_LIT>' ] = form <EOL> form . add_error ( None , e . args [ <NUM_LIT:1> ] ) <EOL> return self . render_to_response ( context ) <EOL> else : <EOL> return self . form_invalid ( form ) <EOL> def form_invalid ( self , form ) : <EOL> context = self . get_context_data ( ) <EOL> context [ '<STR_LIT>' ] = form <EOL> return self . render_to_response ( context ) <EOL> def get_url_name ( self ) : <EOL> """<STR_LIT>""" <EOL> params = self . model . _meta . app_label , self . model . _meta . model_name <EOL> url = '<STR_LIT>' . format ( * params ) <EOL> return reverse ( url ) <EOL> def _get_ancestors_pointers ( self , model ) : <EOL> result = [ ] <EOL> for parent_model , parent_field in model . _meta . parents . items ( ) : <EOL> result . append ( parent_field . column ) <EOL> result . extend ( self . _get_ancestors_pointers ( parent_model ) ) <EOL> return result <EOL> @ transaction . atomic <EOL> def form_valid ( self , form ) : <EOL> saved_objects = [ ] <EOL> args = [ form . cleaned_data [ field [ '<STR_LIT>' ] ] for field in self . fields ] <EOL> for data in zip ( * args ) : <EOL> for field in self . _get_ancestors_pointers ( self . obj ) : <EOL> setattr ( self . obj , field , None ) <EOL> self . obj . id = self . obj . pk = None <EOL> for field in self . clear_fields : <EOL> setattr ( self . obj , field [ '<STR_LIT>' ] , field [ '<STR_LIT:value>' ] ) <EOL> for i , field in enumerate ( self . fields ) : <EOL> setattr ( self . obj , field [ '<STR_LIT>' ] , data [ i ] ) <EOL> try : <EOL> self . obj . clean ( ) <EOL> except ValidationError as exc : <EOL> for error in exc : <EOL> form . add_error ( error [ <NUM_LIT:0> ] , error [ <NUM_LIT:1> ] ) <EOL> return self . form_invalid ( form ) <EOL> self . obj . save ( ) <EOL> saved_objects . append ( '<STR_LIT>' . format ( <EOL> self . obj . get_absolute_url ( ) , <EOL> str ( self . obj ) <EOL> ) ) <EOL> messages . success ( <EOL> self . request , <EOL> mark_safe ( <EOL> _ ( '<STR_LIT>' ) % { <EOL> '<STR_LIT:count>' : len ( saved_objects ) , <EOL> '<STR_LIT>' : "<STR_LIT:U+002CU+0020>" . join ( saved_objects ) <EOL> } <EOL> ) <EOL> ) <EOL> return HttpResponseRedirect ( self . get_url_name ( ) ) <EOL> class MulitiAddAdminMixin ( object ) : <EOL> """<STR_LIT>""" <EOL> view = MultiAddView <EOL> one_of_mulitvalue_required = [ ] <EOL> multiadd_clear_fields = [ ] <EOL> @ property <EOL> def multiadd_info_fields ( self ) : <EOL> return self . list_display <EOL> def get_multiadd_fields ( self , obj = None ) : <EOL> raise NotImplementedError ( ) <EOL> def get_multiadd_clear_fields ( self , obj = None ) : <EOL> return self . multiadd_clear_fields <EOL> def get_url_name ( self , with_namespace = True ) : <EOL> return get_model_view_url_name ( self . model , '<STR_LIT>' , with_namespace ) <EOL> def add_view ( self , request , form_url = '<STR_LIT>' , extra_context = None ) : <EOL> if not extra_context : <EOL> extra_context = { } <EOL> if self . has_add_permission ( request ) : <EOL> extra_context . update ( { <EOL> '<STR_LIT>' : True <EOL> } ) <EOL> return super ( ) . add_view ( request , form_url , extra_context ) <EOL> def change_view ( self , request , object_id , form_url = '<STR_LIT>' , extra_context = None ) : <EOL> if not extra_context : <EOL> extra_context = { } <EOL> if self . has_add_permission ( request ) : <EOL> extra_context . update ( { <EOL> '<STR_LIT>' : reverse ( self . get_url_name ( ) , args = [ object_id ] ) <EOL> } ) <EOL> return super ( ) . change_view ( <EOL> request , object_id , form_url , extra_context <EOL> ) <EOL> def get_urls ( self ) : <EOL> urls = super ( ) . get_urls ( ) <EOL> _urls = [ <EOL> url ( <EOL> r'<STR_LIT>' , <EOL> self . admin_site . admin_view ( self . view . as_view ( ) ) , <EOL> { '<STR_LIT>' : self . model } , <EOL> name = self . get_url_name ( False ) , <EOL> ) , <EOL> ] <EOL> return _urls + urls <EOL> def response_add ( self , request , obj , post_url_continue = None ) : <EOL> """<STR_LIT>""" <EOL> if '<STR_LIT>' in request . POST : <EOL> return HttpResponseRedirect ( <EOL> reverse ( self . get_url_name ( ) , args = [ obj . pk ] ) <EOL> ) <EOL> return super ( ) . response_add ( request , obj , post_url_continue ) </s>
|
<s> from __future__ import unicode_literals <EOL> from django . db import migrations , models <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> operations = [ <EOL> migrations . AlterField ( <EOL> model_name = '<STR_LIT>' , <EOL> name = '<STR_LIT>' , <EOL> field = models . BooleanField ( default = False , help_text = '<STR_LIT>' ) , <EOL> ) , <EOL> ] </s>
|
<s> from django import forms <EOL> from django . db . models . loading import get_model <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from ralph . admin import RalphAdmin , RalphTabularInline , register <EOL> from ralph . admin . filters import LiquidatedStatusFilter , TagsListFilter <EOL> from ralph . admin . mixins import BulkEditChangeListMixin <EOL> from ralph . admin . sites import ralph_site <EOL> from ralph . admin . views . extra import RalphDetailViewAdmin <EOL> from ralph . admin . views . multiadd import MulitiAddAdminMixin <EOL> from ralph . admin . widgets import AutocompleteWidget <EOL> from ralph . assets . invoice_report import AssetInvoiceReportMixin <EOL> from ralph . attachments . admin import AttachmentsMixin <EOL> from ralph . back_office . models import ( <EOL> BackOfficeAsset , <EOL> OfficeInfrastructure , <EOL> Warehouse <EOL> ) <EOL> from ralph . back_office . views import ( <EOL> BackOfficeAssetComponents , <EOL> BackOfficeAssetSoftware <EOL> ) <EOL> from ralph . data_importer import resources <EOL> from ralph . lib . transitions . admin import TransitionAdminMixin <EOL> from ralph . licences . models import BaseObjectLicence , Licence <EOL> from ralph . supports . models import BaseObjectsSupport <EOL> class BackOfficeAssetSupport ( RalphDetailViewAdmin ) : <EOL> icon = '<STR_LIT>' <EOL> name = '<STR_LIT>' <EOL> label = _ ( '<STR_LIT>' ) <EOL> url_name = '<STR_LIT>' <EOL> class BackOfficeAssetSupportInline ( RalphTabularInline ) : <EOL> model = BaseObjectsSupport <EOL> raw_id_fields = ( '<STR_LIT>' , ) <EOL> extra = <NUM_LIT:1> <EOL> verbose_name = _ ( '<STR_LIT>' ) <EOL> ordering = [ '<STR_LIT>' ] <EOL> inlines = [ BackOfficeAssetSupportInline ] <EOL> class BackOfficeAssetLicence ( RalphDetailViewAdmin ) : <EOL> icon = '<STR_LIT:key>' <EOL> name = '<STR_LIT>' <EOL> label = _ ( '<STR_LIT>' ) <EOL> url_name = '<STR_LIT>' <EOL> class BackOfficeAssetLicenceInline ( RalphTabularInline ) : <EOL> model = BaseObjectLicence <EOL> raw_id_fields = ( '<STR_LIT>' , ) <EOL> extra = <NUM_LIT:1> <EOL> verbose_name = _ ( '<STR_LIT>' ) <EOL> inlines = [ BackOfficeAssetLicenceInline ] <EOL> class BackOfficeAssetAdminForm ( RalphAdmin . form ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> super ( ) . __init__ ( * args , ** kwargs ) <EOL> if '<STR_LIT>' in self . fields : <EOL> self . fields [ '<STR_LIT>' ] . widget . attrs [ '<STR_LIT>' ] = True <EOL> @ register ( BackOfficeAsset ) <EOL> class BackOfficeAssetAdmin ( <EOL> MulitiAddAdminMixin , <EOL> AttachmentsMixin , <EOL> BulkEditChangeListMixin , <EOL> TransitionAdminMixin , <EOL> AssetInvoiceReportMixin , <EOL> RalphAdmin <EOL> ) : <EOL> """<STR_LIT>""" <EOL> add_form_template = '<STR_LIT>' <EOL> form = BackOfficeAssetAdminForm <EOL> actions = [ '<STR_LIT>' ] <EOL> show_transition_history = True <EOL> change_views = [ <EOL> BackOfficeAssetLicence , <EOL> BackOfficeAssetSupport , <EOL> BackOfficeAssetComponents , <EOL> BackOfficeAssetSoftware , <EOL> ] <EOL> list_display = [ <EOL> '<STR_LIT:status>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:user>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> multiadd_summary_fields = list_display <EOL> search_fields = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> list_filter = [ <EOL> '<STR_LIT>' , '<STR_LIT:status>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT:location>' , '<STR_LIT>' , '<STR_LIT:user>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , LiquidatedStatusFilter , ( '<STR_LIT>' , TagsListFilter ) <EOL> ] <EOL> date_hierarchy = '<STR_LIT>' <EOL> list_select_related = [ <EOL> '<STR_LIT>' , '<STR_LIT:user>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> raw_id_fields = [ <EOL> '<STR_LIT>' , '<STR_LIT:user>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> resource_class = resources . BackOfficeAssetResource <EOL> bulk_edit_list = [ <EOL> '<STR_LIT>' , '<STR_LIT:status>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT:user>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> bulk_edit_no_fillable = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> _invoice_report_name = '<STR_LIT>' <EOL> _invoice_report_item_fields = ( <EOL> AssetInvoiceReportMixin . _invoice_report_item_fields + [ '<STR_LIT>' ] <EOL> ) <EOL> _invoice_report_select_related = ( <EOL> AssetInvoiceReportMixin . _invoice_report_select_related + [ '<STR_LIT>' ] <EOL> ) <EOL> fieldsets = ( <EOL> ( _ ( '<STR_LIT>' ) , { <EOL> '<STR_LIT>' : ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT:status>' , <EOL> '<STR_LIT>' , '<STR_LIT:location>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ) <EOL> } ) , <EOL> ( _ ( '<STR_LIT>' ) , { <EOL> '<STR_LIT>' : ( <EOL> '<STR_LIT:user>' , '<STR_LIT>' <EOL> ) <EOL> } ) , <EOL> ( _ ( '<STR_LIT>' ) , { <EOL> '<STR_LIT>' : ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ) <EOL> } ) , <EOL> ) <EOL> def licences ( self , obj ) : <EOL> return '<STR_LIT>' <EOL> licences . short_description = '<STR_LIT>' <EOL> def get_changelist_form ( self , request , ** kwargs ) : <EOL> """<STR_LIT>""" <EOL> Form = super ( ) . get_changelist_form ( request , ** kwargs ) <EOL> class BackOfficeAssetBulkForm ( Form ) : <EOL> """<STR_LIT>""" <EOL> licences = forms . ModelMultipleChoiceField ( <EOL> queryset = Licence . objects . all ( ) , label = _ ( '<STR_LIT>' ) , <EOL> required = False , <EOL> widget = AutocompleteWidget ( <EOL> field = get_model ( <EOL> '<STR_LIT>' <EOL> ) . _meta . get_field ( '<STR_LIT>' ) , <EOL> admin_site = ralph_site , <EOL> request = request , <EOL> multi = True , <EOL> ) , <EOL> ) <EOL> def __init__ ( self , * args , ** kwargs ) : <EOL> initial = kwargs . get ( '<STR_LIT>' , { } ) <EOL> initial [ '<STR_LIT>' ] = [ <EOL> str ( _id ) for _id in <EOL> kwargs [ '<STR_LIT>' ] . licences . values_list ( <EOL> '<STR_LIT>' , flat = True <EOL> ) <EOL> ] <EOL> kwargs [ '<STR_LIT>' ] = initial <EOL> super ( ) . __init__ ( * args , ** kwargs ) <EOL> def save_m2m ( self ) : <EOL> form_licences = self . cleaned_data [ '<STR_LIT>' ] <EOL> form_licences_ids = [ licence . id for licence in form_licences ] <EOL> asset_licences_ids = self . instance . licences . values_list ( <EOL> '<STR_LIT>' , flat = True ) <EOL> to_add = set ( form_licences_ids ) - set ( asset_licences_ids ) <EOL> to_remove = set ( asset_licences_ids ) - set ( form_licences_ids ) <EOL> for licence in form_licences : <EOL> if licence . id not in to_add : <EOL> continue <EOL> BaseObjectLicence . objects . get_or_create ( <EOL> base_object = self . instance , licence_id = licence . id , <EOL> ) <EOL> self . instance . licences . filter ( licence_id__in = to_remove ) . delete ( ) <EOL> return self . instance <EOL> def save ( self , commit = True ) : <EOL> instance = super ( ) . save ( commit = True ) <EOL> return instance <EOL> return BackOfficeAssetBulkForm <EOL> def get_multiadd_fields ( self , obj = None ) : <EOL> multi_add_fields = [ <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : False } , <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : False } , <EOL> ] <EOL> if obj and obj . model . category . imei_required : <EOL> multi_add_fields . append ( <EOL> { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : False } <EOL> ) <EOL> return multi_add_fields <EOL> @ register ( Warehouse ) <EOL> class WarehouseAdmin ( RalphAdmin ) : <EOL> search_fields = [ '<STR_LIT:name>' ] <EOL> @ register ( OfficeInfrastructure ) <EOL> class OfficeInfrastructureAdmin ( RalphAdmin ) : <EOL> search_fields = [ '<STR_LIT:name>' ] </s>
|
<s> from __future__ import unicode_literals <EOL> from django . db import migrations , models <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> operations = [ <EOL> migrations . AlterModelOptions ( <EOL> name = '<STR_LIT>' , <EOL> options = { '<STR_LIT>' : [ '<STR_LIT:name>' ] } , <EOL> ) , <EOL> migrations . AlterModelOptions ( <EOL> name = '<STR_LIT>' , <EOL> options = { '<STR_LIT>' : [ '<STR_LIT:name>' ] } , <EOL> ) , <EOL> ] </s>
|
<s> from django . contrib . auth import get_user_model <EOL> from django . test import TestCase <EOL> from ralph . accounts . tests . factories import UserFactory <EOL> from ralph . assets . models import BaseObject <EOL> from ralph . back_office . tests . factories import BackOfficeAssetFactory <EOL> from ralph . data_importer . fields import ThroughField <EOL> from ralph . data_importer . widgets import ( <EOL> ManyToManyThroughWidget , <EOL> UserManyToManyWidget <EOL> ) <EOL> from ralph . licences . models import BaseObjectLicence , LicenceUser <EOL> from ralph . licences . tests . factories import LicenceFactory <EOL> class DataImporterFieldsTestCase ( TestCase ) : <EOL> @ classmethod <EOL> def setUpClass ( cls ) : <EOL> super ( ) . setUpClass ( ) <EOL> cls . back_office_assets = BackOfficeAssetFactory . create_batch ( <NUM_LIT:4> ) <EOL> cls . users = [ UserFactory ( ) for i in range ( <NUM_LIT:4> ) ] <EOL> cls . delete_users = UserFactory . create_batch ( <NUM_LIT:2> ) <EOL> cls . licence = LicenceFactory ( ) <EOL> cls . licence2 = LicenceFactory ( ) <EOL> def setUp ( self ) : <EOL> LicenceUser . objects . create ( <EOL> licence = self . licence , user = self . users [ <NUM_LIT:0> ] <EOL> ) <EOL> for user in self . delete_users : <EOL> LicenceUser . objects . create ( <EOL> licence = self . licence , user = user <EOL> ) <EOL> BaseObjectLicence . objects . create ( <EOL> licence = self . licence , base_object = self . back_office_assets [ <NUM_LIT:0> ] , <EOL> ) <EOL> BaseObjectLicence . objects . create ( <EOL> licence = self . licence , base_object = self . back_office_assets [ <NUM_LIT:1> ] , <EOL> ) <EOL> LicenceUser . objects . create ( <EOL> licence = self . licence2 , user = self . users [ <NUM_LIT:0> ] <EOL> ) <EOL> LicenceUser . objects . create ( <EOL> licence = self . licence2 , user = self . users [ <NUM_LIT:3> ] <EOL> ) <EOL> LicenceUser . objects . create ( <EOL> licence = self . licence2 , user = self . delete_users [ <NUM_LIT:0> ] <EOL> ) <EOL> BaseObjectLicence . objects . create ( <EOL> licence = self . licence2 , base_object = self . back_office_assets [ <NUM_LIT:1> ] , <EOL> ) <EOL> BaseObjectLicence . objects . create ( <EOL> licence = self . licence2 , base_object = self . back_office_assets [ <NUM_LIT:2> ] , <EOL> ) <EOL> def test_users_through_field ( self ) : <EOL> field = ThroughField ( <EOL> through_model = LicenceUser , <EOL> through_from_field_name = '<STR_LIT>' , <EOL> through_to_field_name = '<STR_LIT:user>' , <EOL> attribute = '<STR_LIT>' , <EOL> column_name = '<STR_LIT>' , <EOL> widget = UserManyToManyWidget ( model = get_user_model ( ) ) <EOL> ) <EOL> self . assertEqual ( self . licence . users . all ( ) . count ( ) , <NUM_LIT:3> ) <EOL> self . assertEqual ( self . licence2 . users . all ( ) . count ( ) , <NUM_LIT:3> ) <EOL> with self . assertNumQueries ( <NUM_LIT:4> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( [ i . username for i in self . users ] ) } <EOL> ) <EOL> self . assertEqual ( self . licence . users . all ( ) . count ( ) , <NUM_LIT:4> ) <EOL> users = self . users + [ UserFactory ( ) ] <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( [ i . username for i in users ] ) } <EOL> ) <EOL> self . assertEqual ( self . licence . users . all ( ) . count ( ) , <NUM_LIT:5> ) <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( [ i . username for i in users [ : <NUM_LIT:4> ] ] ) } <EOL> ) <EOL> self . assertEqual ( self . licence . users . all ( ) . count ( ) , <NUM_LIT:4> ) <EOL> with self . assertNumQueries ( <NUM_LIT:2> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( [ i . username for i in users [ : <NUM_LIT:4> ] ] ) } <EOL> ) <EOL> self . assertEqual ( self . licence . users . all ( ) . count ( ) , <NUM_LIT:4> ) <EOL> self . assertEqual ( self . licence2 . users . all ( ) . count ( ) , <NUM_LIT:3> ) <EOL> def _get_base_objects_through_field ( self ) : <EOL> return ThroughField ( <EOL> column_name = '<STR_LIT>' , <EOL> attribute = '<STR_LIT>' , <EOL> widget = ManyToManyThroughWidget ( <EOL> model = BaseObjectLicence , <EOL> related_model = BaseObject , <EOL> through_field = '<STR_LIT>' , <EOL> ) , <EOL> through_model = BaseObjectLicence , <EOL> through_from_field_name = '<STR_LIT>' , <EOL> through_to_field_name = '<STR_LIT>' <EOL> ) <EOL> def test_through_field_only_add ( self ) : <EOL> field = self . _get_base_objects_through_field ( ) <EOL> self . assertEqual ( self . licence . base_objects . all ( ) . count ( ) , <NUM_LIT:2> ) <EOL> ids = [ i . pk for i in self . back_office_assets ] <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( map ( str , ids ) ) } <EOL> ) <EOL> self . assertEqual ( self . licence . base_objects . all ( ) . count ( ) , <NUM_LIT:4> ) <EOL> self . assertCountEqual ( <EOL> self . licence . base_objects . values_list ( '<STR_LIT>' , flat = True ) , ids <EOL> ) <EOL> self . assertEqual ( self . licence2 . base_objects . all ( ) . count ( ) , <NUM_LIT:2> ) <EOL> def test_through_field_only_remove ( self ) : <EOL> field = self . _get_base_objects_through_field ( ) <EOL> self . assertEqual ( self . licence . base_objects . all ( ) . count ( ) , <NUM_LIT:2> ) <EOL> ids = [ self . back_office_assets [ <NUM_LIT:0> ] . pk ] <EOL> with self . assertNumQueries ( <NUM_LIT:3> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( map ( str , ids ) ) } <EOL> ) <EOL> self . assertEqual ( self . licence . base_objects . all ( ) . count ( ) , <NUM_LIT:1> ) <EOL> self . assertCountEqual ( <EOL> self . licence . base_objects . values_list ( '<STR_LIT>' , flat = True ) , ids <EOL> ) <EOL> self . assertEqual ( self . licence2 . base_objects . all ( ) . count ( ) , <NUM_LIT:2> ) <EOL> def test_through_field_add_and_remove ( self ) : <EOL> field = self . _get_base_objects_through_field ( ) <EOL> self . assertEqual ( self . licence . base_objects . all ( ) . count ( ) , <NUM_LIT:2> ) <EOL> ids = [ <EOL> self . back_office_assets [ <NUM_LIT:1> ] . pk , <EOL> self . back_office_assets [ <NUM_LIT:2> ] . pk , <EOL> self . back_office_assets [ <NUM_LIT:3> ] . pk , <EOL> ] <EOL> with self . assertNumQueries ( <NUM_LIT:4> ) : <EOL> field . save ( <EOL> self . licence , <EOL> { '<STR_LIT>' : '<STR_LIT:U+002C>' . join ( map ( str , ids ) ) } <EOL> ) <EOL> self . assertEqual ( self . licence . base_objects . all ( ) . count ( ) , <NUM_LIT:3> ) <EOL> self . assertCountEqual ( <EOL> self . licence . base_objects . values_list ( '<STR_LIT>' , flat = True ) , ids <EOL> ) <EOL> self . assertEqual ( self . licence2 . base_objects . all ( ) . count ( ) , <NUM_LIT:2> ) </s>
|
<s> from django import template <EOL> register = template . Library ( ) <EOL> @ register . inclusion_tag ( '<STR_LIT>' ) <EOL> def alert ( message , css_class = '<STR_LIT:success>' , is_close = True ) : <EOL> """<STR_LIT>""" <EOL> return { '<STR_LIT:message>' : message , '<STR_LIT>' : css_class , '<STR_LIT>' : is_close } </s>
|
<s> from django . apps import AppConfig <EOL> class PolymorphicTestsConfig ( AppConfig ) : <EOL> name = '<STR_LIT>' <EOL> label = '<STR_LIT>' </s>
|
<s> from django . utils . translation import ugettext_lazy as _ <EOL> from ralph . admin import RalphAdmin , RalphTabularInline , register <EOL> from ralph . admin . filters import TagsListFilter <EOL> from ralph . admin . mixins import BulkEditChangeListMixin <EOL> from ralph . admin . views . extra import RalphDetailViewAdmin <EOL> from ralph . assets . invoice_report import InvoiceReportMixin <EOL> from ralph . attachments . admin import AttachmentsMixin <EOL> from ralph . data_importer import resources <EOL> from ralph . licences . models import ( <EOL> BaseObjectLicence , <EOL> Licence , <EOL> LicenceType , <EOL> LicenceUser , <EOL> Software <EOL> ) <EOL> class BaseObjectLicenceView ( RalphDetailViewAdmin ) : <EOL> icon = '<STR_LIT>' <EOL> name = '<STR_LIT>' <EOL> label = _ ( '<STR_LIT>' ) <EOL> url_name = '<STR_LIT>' <EOL> class BaseObjectLicenceInline ( RalphTabularInline ) : <EOL> model = BaseObjectLicence <EOL> raw_id_fields = ( '<STR_LIT>' , ) <EOL> extra = <NUM_LIT:1> <EOL> verbose_name = _ ( '<STR_LIT>' ) <EOL> verbose_name_plural = _ ( '<STR_LIT>' ) <EOL> fk_name = '<STR_LIT>' <EOL> inlines = [ BaseObjectLicenceInline ] <EOL> class LicenceUserView ( RalphDetailViewAdmin ) : <EOL> icon = '<STR_LIT:user>' <EOL> name = '<STR_LIT>' <EOL> label = _ ( '<STR_LIT>' ) <EOL> url_name = '<STR_LIT>' <EOL> class LicenceUserInline ( RalphTabularInline ) : <EOL> model = LicenceUser <EOL> raw_id_fields = ( '<STR_LIT:user>' , ) <EOL> extra = <NUM_LIT:1> <EOL> inlines = [ LicenceUserInline ] <EOL> @ register ( Licence ) <EOL> class LicenceAdmin ( <EOL> AttachmentsMixin , <EOL> BulkEditChangeListMixin , <EOL> InvoiceReportMixin , <EOL> RalphAdmin <EOL> ) : <EOL> """<STR_LIT>""" <EOL> actions = [ '<STR_LIT>' ] <EOL> change_views = [ <EOL> BaseObjectLicenceView , <EOL> LicenceUserView , <EOL> ] <EOL> search_fields = [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> list_filter = [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ( '<STR_LIT>' , TagsListFilter ) <EOL> ] <EOL> date_hierarchy = '<STR_LIT>' <EOL> list_display = [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> readonly_fields = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> list_select_related = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> raw_id_fields = [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> bulk_edit_list = [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> ] <EOL> resource_class = resources . LicenceResource <EOL> _invoice_report_name = '<STR_LIT>' <EOL> _invoice_report_select_related = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> _invoice_report_item_fields = [ <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ] <EOL> fieldsets = ( <EOL> ( _ ( '<STR_LIT>' ) , { <EOL> '<STR_LIT>' : ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> ) <EOL> } ) , <EOL> ( _ ( '<STR_LIT>' ) , { <EOL> '<STR_LIT>' : ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' <EOL> ) <EOL> } ) , <EOL> ) <EOL> _queryset_manager = '<STR_LIT>' <EOL> _export_queryset_manager = '<STR_LIT>' <EOL> @ register ( LicenceType ) <EOL> class LicenceTypeAdmin ( RalphAdmin ) : <EOL> search_fields = [ '<STR_LIT:name>' ] <EOL> @ register ( Software ) <EOL> class Software ( RalphAdmin ) : <EOL> search_fields = [ '<STR_LIT:name>' ] </s>
|
<s> from __future__ import unicode_literals <EOL> from django . db import migrations , models <EOL> class Migration ( migrations . Migration ) : <EOL> dependencies = [ <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ] <EOL> operations = [ <EOL> migrations . AddField ( <EOL> model_name = '<STR_LIT>' , <EOL> name = '<STR_LIT:default>' , <EOL> field = models . BooleanField ( default = False ) , <EOL> preserve_default = False , <EOL> ) , <EOL> ] </s>
|
<s> import json <EOL> from django . core . urlresolvers import reverse <EOL> from django . test import TestCase <EOL> from ralph . accounts . tests . factories import UserFactory <EOL> from ralph . admin . autocomplete import QUERY_PARAM <EOL> from ralph . supports . tests . factories import SupportFactory , SupportTypeFactory <EOL> from ralph . tests import RalphTestCase <EOL> from ralph . tests . mixins import ClientMixin <EOL> class SupportAutocompleteTest ( TestCase , ClientMixin ) : <EOL> def setUp ( self ) : <EOL> super ( ) . setUp ( ) <EOL> self . support = SupportFactory ( <EOL> name = '<STR_LIT>' , <EOL> support_type = SupportTypeFactory ( name = '<STR_LIT>' ) , <EOL> supplier = '<STR_LIT>' <EOL> ) <EOL> self . login_as_user ( username = '<STR_LIT:test>' ) <EOL> def test_autocomplete_json ( self ) : <EOL> client_url = reverse ( <EOL> '<STR_LIT>' , kwargs = { <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' , <EOL> '<STR_LIT>' : '<STR_LIT>' <EOL> } <EOL> ) <EOL> response = self . client . get ( client_url , { QUERY_PARAM : '<STR_LIT>' } ) <EOL> expected_html = ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' <EOL> ) . format ( <EOL> date_to = self . support . date_to , <EOL> producer = self . support . producer , <EOL> date_from = self . support . date_from , <EOL> serial_no = self . support . serial_no <EOL> ) <EOL> data = json . loads ( str ( response . content , '<STR_LIT:utf-8>' ) ) [ '<STR_LIT>' ] [ <NUM_LIT:0> ] <EOL> self . assertEqual ( <EOL> data [ '<STR_LIT:label>' ] , '<STR_LIT>' . format ( <EOL> str ( self . support . name ) , <EOL> self . support . date_to , <EOL> self . support . supplier <EOL> ) <EOL> ) <EOL> self . assertEqual ( <EOL> data [ '<STR_LIT>' ] , '<STR_LIT>' . format ( <EOL> self . support . name , self . support . date_to <EOL> ) <EOL> ) <EOL> self . assertHTMLEqual ( data [ '<STR_LIT>' ] , expected_html ) </s>
|
<s> from _ppca import PPCA </s>
|
<s> from pennyblack . models import Newsletter , Mail <EOL> from pennyblack . options import NewsletterReceiverMixin <EOL> from pennyblack . content . richtext import TextOnlyNewsletterContent <EOL> from django . db import models <EOL> from django . core . urlresolvers import reverse <EOL> import unittest <EOL> class NewsletterTestCase ( unittest . TestCase ) : <EOL> def test_is_valid ( self ) : <EOL> n = Newsletter ( ) <EOL> self . assertFalse ( n . is_valid ( ) , "<STR_LIT>" ) <EOL> n . subject = '<STR_LIT>' <EOL> self . assertTrue ( n . is_valid ( ) , "<STR_LIT>" ) <EOL> class RichtextContentTest ( unittest . TestCase ) : <EOL> content = None <EOL> job = None <EOL> class Job ( object ) : <EOL> def __init__ ( self , link ) : <EOL> self . times = <NUM_LIT:0> <EOL> self . link = link <EOL> def add_link ( self , link ) : <EOL> self . times += <NUM_LIT:1> <EOL> return '<STR_LIT>' + self . link <EOL> def setUp ( self ) : <EOL> self . content = TextOnlyNewsletterContent ( text = '<STR_LIT>' ) <EOL> self . link = reverse ( '<STR_LIT>' , kwargs = { '<STR_LIT>' : '<STR_LIT>' , '<STR_LIT>' : '<STR_LIT>' } ) . replace ( '<STR_LIT>' , '<STR_LIT:{>' ) . replace ( '<STR_LIT>' , '<STR_LIT:}>' ) <EOL> self . job = self . Job ( self . link ) <EOL> def test_replace_links ( self ) : <EOL> self . content . replace_links ( self . job ) <EOL> self . assertEqual ( self . content . text , '<STR_LIT>' % self . link ) <EOL> def test_replace_multiple_links ( self ) : <EOL> self . content . text = '<STR_LIT>' <EOL> self . content . replace_links ( self . job ) <EOL> self . assertEqual ( self . content . text , '<STR_LIT>' % ( self . link , self . link ) ) <EOL> def test_dont_replace_twice ( self ) : <EOL> self . content . text = '<STR_LIT>' <EOL> self . content . replace_links ( self . job ) <EOL> old_times = self . job . times <EOL> last_text = self . content . text [ : ] <EOL> self . content . replace_links ( self . job ) <EOL> self . assertEqual ( self . job . times , old_times ) <EOL> self . assertEqual ( self . content . text , last_text ) <EOL> def test_dont_replace_link_url_tag_urls ( self ) : <EOL> link = '<STR_LIT>' <EOL> self . content . text = link <EOL> self . content . replace_links ( self . job ) <EOL> self . assertEqual ( self . content . text , link ) <EOL> def test_quotes_in_url ( self ) : <EOL> self . content . text = '<STR_LIT>' <EOL> self . content . replace_links ( self . job ) <EOL> self . assertEqual ( self . content . text , '<STR_LIT>' % self . link ) <EOL> def test_link_style ( self ) : <EOL> self . content . text = '<STR_LIT>' <EOL> self . content . prepare_to_send ( ) <EOL> self . assertEqual ( self . content . text , '<STR_LIT>' ) <EOL> def test_multiple_link_styles ( self ) : <EOL> self . content . text = '<STR_LIT>' <EOL> self . content . prepare_to_send ( ) <EOL> self . assertEqual ( self . content . text , '<STR_LIT>' ) </s>
|
<s> from functools import wraps <EOL> from flask import g , request , redirect , url_for <EOL> def login_required ( f ) : <EOL> @ wraps ( f ) <EOL> def decorated_function ( * args , ** kwargs ) : <EOL> if g . user is None : <EOL> return redirect ( url_for ( '<STR_LIT>' , next = request . url ) ) <EOL> return f ( * args , ** kwargs ) <EOL> return decorated_function </s>
|
<s> import re <EOL> from jinja2 import evalcontextfilter , Markup <EOL> @ evalcontextfilter <EOL> def linebreaks ( eval_ctx , value ) : <EOL> value = re . sub ( r'<STR_LIT>' , '<STR_LIT:\n>' , value ) <EOL> paras = re . split ( '<STR_LIT>' , value ) <EOL> paras = [ u'<STR_LIT>' % p . replace ( '<STR_LIT:\n>' , '<STR_LIT>' ) for p in paras ] <EOL> paras = u'<STR_LIT>' . join ( paras ) <EOL> return Markup ( paras ) <EOL> @ evalcontextfilter <EOL> def linebreaksbr ( eval_ctx , value ) : <EOL> value = re . sub ( r'<STR_LIT>' , '<STR_LIT:\n>' , value ) <EOL> paras = re . split ( '<STR_LIT>' , value ) <EOL> paras = [ u'<STR_LIT:%s>' % p . replace ( '<STR_LIT:\n>' , '<STR_LIT>' ) for p in paras ] <EOL> paras = u'<STR_LIT>' . join ( paras ) <EOL> return Markup ( paras ) </s>
|
<s> from pkgutil import extend_path <EOL> __path__ = extend_path ( __path__ , __name__ ) <EOL> from dshelpers import download_url <EOL> from performanceplatform . collector . gcloud . core import ( <EOL> nuke_local_database , save_raw_data , aggregate_and_save , <EOL> push_aggregates ) <EOL> from performanceplatform . collector . gcloud . sales_parser import ( <EOL> get_latest_csv_url ) <EOL> from performanceplatform . client import DataSet <EOL> INDEX_URL = ( '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> def main ( credentials , data_set_config , query , options , start_at , end_at , <EOL> filename = None ) : <EOL> nuke_local_database ( ) <EOL> if filename is not None : <EOL> with open ( filename , '<STR_LIT:r>' ) as f : <EOL> save_raw_data ( f ) <EOL> else : <EOL> save_raw_data ( download_url ( get_latest_csv_url ( INDEX_URL ) ) ) <EOL> aggregate_and_save ( ) <EOL> data_set = DataSet . from_config ( data_set_config ) <EOL> data_set . empty_data_set ( ) <EOL> push_aggregates ( data_set ) </s>
|
<s> from performanceplatform . collector . ga . plugins . aggregate import make_aggregate , aggregate_count , aggregate_rate , AggregateKey <EOL> def test_make_aggregate_sum ( ) : <EOL> """<STR_LIT>""" <EOL> from nose . tools import assert_equal <EOL> doc1 = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT> } <EOL> doc2 = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT> } <EOL> docs = [ doc1 , doc2 ] <EOL> aggregate_doc = make_aggregate ( docs , [ aggregate_count ( "<STR_LIT>" ) ] ) <EOL> expected_aggregate = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT> } <EOL> assert_equal ( aggregate_doc , expected_aggregate ) <EOL> def test_make_aggregate_rate ( ) : <EOL> """<STR_LIT>""" <EOL> from nose . tools import assert_equal <EOL> doc1 = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT:100> , "<STR_LIT>" : <NUM_LIT> } <EOL> doc2 = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT:100> , "<STR_LIT>" : <NUM_LIT> } <EOL> docs = [ doc1 , doc2 ] <EOL> aggregate_doc = make_aggregate ( docs , [ aggregate_count ( "<STR_LIT>" ) , <EOL> aggregate_rate ( "<STR_LIT>" , "<STR_LIT>" ) ] ) <EOL> expected_aggregate = { <EOL> "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , <EOL> "<STR_LIT>" : <NUM_LIT:200> , <EOL> "<STR_LIT>" : ( <NUM_LIT> * <NUM_LIT:100> + <NUM_LIT> * <NUM_LIT:100> ) / ( <NUM_LIT:100> + <NUM_LIT:100> ) } <EOL> assert_equal ( aggregate_doc , expected_aggregate ) <EOL> def test_AggregateKeyPlugin ( ) : <EOL> """<STR_LIT>""" <EOL> from nose . tools import assert_equal <EOL> doc1 = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT:100> , "<STR_LIT>" : <NUM_LIT> } <EOL> doc2 = { "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , "<STR_LIT>" : <NUM_LIT:100> , "<STR_LIT>" : <NUM_LIT> } <EOL> docs = [ doc1 , doc2 ] <EOL> plugin = AggregateKey ( aggregate_count ( "<STR_LIT>" ) , <EOL> aggregate_rate ( "<STR_LIT>" , "<STR_LIT>" ) ) <EOL> output_docs = plugin ( docs ) <EOL> expected_aggregate = { <EOL> "<STR_LIT:a>" : <NUM_LIT:2> , "<STR_LIT:b>" : <NUM_LIT:2> , "<STR_LIT:c>" : <NUM_LIT:2> , <EOL> "<STR_LIT>" : <NUM_LIT:200> , <EOL> "<STR_LIT>" : ( <NUM_LIT> * <NUM_LIT:100> + <NUM_LIT> * <NUM_LIT:100> ) / ( <NUM_LIT:100> + <NUM_LIT:100> ) } <EOL> assert_equal ( output_docs , [ expected_aggregate ] ) </s>
|
<s> import numpy as np <EOL> from scipy . cluster . vq import kmeans , vq <EOL> from scipy . spatial . distance import cdist <EOL> import matplotlib . pyplot as plt <EOL> def load_data ( fName = '<STR_LIT>' ) : <EOL> fp = open ( fName ) <EOL> XX = np . loadtxt ( fp ) <EOL> fp . close ( ) <EOL> return XX <EOL> def run_kmeans ( X , n = <NUM_LIT:10> ) : <EOL> _K = range ( <NUM_LIT:1> , n ) <EOL> _KM = [ kmeans ( X , k ) for k in _K ] <EOL> _centroids = [ cent for ( cent , var ) in _KM ] <EOL> _D_k = [ cdist ( X , cent , '<STR_LIT>' ) for cent in _centroids ] <EOL> _cIdx = [ np . argmin ( D , axis = <NUM_LIT:1> ) for D in _D_k ] <EOL> _dist = [ np . min ( D , axis = <NUM_LIT:1> ) for D in _D_k ] <EOL> _avgWithinSS = [ sum ( d ) / X . shape [ <NUM_LIT:0> ] for d in _dist ] <EOL> return ( _K , _KM , _centroids , _D_k , _cIdx , _dist , _avgWithinSS ) <EOL> def plot_elbow_curve ( kIdx , K , avgWithinSS ) : <EOL> fig = plt . figure ( ) <EOL> ax = fig . add_subplot ( <NUM_LIT> ) <EOL> ax . plot ( K , avgWithinSS , '<STR_LIT>' ) <EOL> ax . plot ( K [ kIdx ] , avgWithinSS [ kIdx ] , marker = '<STR_LIT:o>' , markersize = <NUM_LIT:12> , <EOL> markeredgewidth = <NUM_LIT:2> , markeredgecolor = '<STR_LIT:r>' , markerfacecolor = '<STR_LIT:None>' ) <EOL> plt . grid ( True ) <EOL> plt . xlabel ( '<STR_LIT>' ) <EOL> plt . ylabel ( '<STR_LIT>' ) <EOL> tt = plt . title ( '<STR_LIT>' ) <EOL> return ( fig , ax ) <EOL> def plot_clusters ( orig , pred , nx , ny , legend = True ) : <EOL> data = orig <EOL> import matplotlib . pyplot as plt <EOL> ylabels = { <NUM_LIT:0> : '<STR_LIT>' , <NUM_LIT:1> : '<STR_LIT>' , <NUM_LIT:2> : '<STR_LIT>' } <EOL> p0 = plt . plot ( data [ pred == <NUM_LIT:0> , nx ] , data [ pred == <NUM_LIT:0> , ny ] , '<STR_LIT>' , label = '<STR_LIT>' ) <EOL> p2 = plt . plot ( data [ pred == <NUM_LIT:2> , nx ] , data [ pred == <NUM_LIT:2> , ny ] , '<STR_LIT>' , label = '<STR_LIT>' ) <EOL> p1 = plt . plot ( data [ pred == <NUM_LIT:1> , nx ] , data [ pred == <NUM_LIT:1> , ny ] , '<STR_LIT>' , label = '<STR_LIT>' ) <EOL> lx = p1 [ <NUM_LIT:0> ] . axes . set_xlabel ( '<STR_LIT>' ) <EOL> ly = p1 [ <NUM_LIT:0> ] . axes . set_ylabel ( ylabels [ ny ] ) <EOL> tt = plt . title ( '<STR_LIT>' ) <EOL> if legend : <EOL> ll = plt . legend ( ) <EOL> return ( p0 , p1 , p2 ) </s>
|
<s> from thrift . Thrift import TType , TMessageType , TException , TApplicationException <EOL> from ttypes import * </s>
|
<s> '''<STR_LIT>''' <EOL> import os , sys , thread , re <EOL> from subprocess import Popen , PIPE <EOL> def process_sentence ( proc , sent ) : <EOL> if ( len ( sent ) ) > <NUM_LIT:0> : <EOL> if sent [ <NUM_LIT:0> ] [ <NUM_LIT:2> ] == "<STR_LIT>" : <EOL> sent . pop ( <NUM_LIT:0> ) <EOL> if sent [ - <NUM_LIT:1> ] [ <NUM_LIT:2> ] == "<STR_LIT>" : <EOL> sent . pop ( ) <EOL> text = "<STR_LIT>" + "<STR_LIT:U+0020>" . join ( [ ww [ <NUM_LIT:2> ] for ww in sent ] ) + "<STR_LIT>" <EOL> proc . stdin . write ( text ) <EOL> proc . stdin . flush ( ) <EOL> text = proc . stdout . readline ( ) <EOL> words = text . split ( ) [ <NUM_LIT:1> : - <NUM_LIT:1> ] <EOL> if len ( words ) == <NUM_LIT:0> : <EOL> return <EOL> if words [ <NUM_LIT:0> ] in [ "<STR_LIT>" , "<STR_LIT>" ] : <EOL> words = words [ <NUM_LIT:1> : ] <EOL> if words [ - <NUM_LIT:1> ] in [ "<STR_LIT>" , "<STR_LIT>" ] : <EOL> words = words [ <NUM_LIT:0> : - <NUM_LIT:1> ] <EOL> i_orig = <NUM_LIT:0> <EOL> i_new = <NUM_LIT:0> <EOL> result = [ ] <EOL> while i_new < len ( words ) : <EOL> new_word = words [ i_new ] <EOL> new_start = sent [ i_orig ] [ <NUM_LIT:0> ] <EOL> new_dur = sent [ i_orig ] [ <NUM_LIT:1> ] <EOL> new_id = sent [ i_orig ] [ <NUM_LIT:3> ] <EOL> while ( i_new + <NUM_LIT:1> < len ( words ) ) and ( words [ i_new + <NUM_LIT:1> ] in [ "<STR_LIT>" , "<STR_LIT>" ] or words [ i_new + <NUM_LIT:1> ] . startswith ( "<STR_LIT:_>" ) ) : <EOL> if ( words [ i_new + <NUM_LIT:1> ] == "<STR_LIT>" ) : <EOL> new_word = new_word + "<STR_LIT:+>" + words [ i_new + <NUM_LIT:2> ] <EOL> i_new += <NUM_LIT:2> <EOL> i_orig += <NUM_LIT:1> <EOL> elif ( words [ i_new + <NUM_LIT:1> ] == "<STR_LIT>" ) : <EOL> new_word = new_word + "<STR_LIT:->" + words [ i_new + <NUM_LIT:2> ] <EOL> i_new += <NUM_LIT:2> <EOL> i_orig += <NUM_LIT:1> <EOL> else : <EOL> new_word += words [ i_new + <NUM_LIT:1> ] [ <NUM_LIT:1> : ] <EOL> i_new += <NUM_LIT:1> <EOL> i_orig += <NUM_LIT:1> <EOL> new_dur = sent [ i_orig ] [ <NUM_LIT:0> ] + sent [ i_orig ] [ <NUM_LIT:1> ] - new_start <EOL> i_new += <NUM_LIT:1> <EOL> i_orig += <NUM_LIT:1> <EOL> new_word = new_word . replace ( "<STR_LIT:_>" , "<STR_LIT>" ) <EOL> result . append ( ( new_start , new_dur , new_word , new_id ) ) <EOL> for r in result : <EOL> print r [ <NUM_LIT:3> ] . replace ( "<STR_LIT:->" , "<STR_LIT:_>" ) , "<STR_LIT:1>" , r [ <NUM_LIT:0> ] , r [ <NUM_LIT:1> ] , r [ <NUM_LIT:2> ] <EOL> if __name__ == '<STR_LIT:__main__>' : <EOL> cmd = sys . argv [ <NUM_LIT:1> ] <EOL> proc = Popen ( cmd , shell = True , stdin = PIPE , stdout = PIPE ) <EOL> sent = [ ] <EOL> last_id = "<STR_LIT>" <EOL> for l in sys . stdin : <EOL> ss = l . split ( ) <EOL> id = ss [ <NUM_LIT:0> ] <EOL> channel = ss [ <NUM_LIT:1> ] <EOL> start = float ( ss [ <NUM_LIT:2> ] ) <EOL> duration = float ( ss [ <NUM_LIT:3> ] ) <EOL> word = ss [ <NUM_LIT:4> ] <EOL> if id != last_id : <EOL> process_sentence ( proc , sent ) <EOL> sent = [ ] <EOL> if ( word == "<STR_LIT>" ) : <EOL> word = "<STR_LIT>" <EOL> if ( word == "<STR_LIT>" ) : <EOL> continue <EOL> sent . append ( ( start , duration , word , id ) ) <EOL> if ( word == "<STR_LIT>" ) : <EOL> process_sentence ( proc , sent ) <EOL> sent = [ ] <EOL> last_id = id <EOL> process_sentence ( proc , sent ) </s>
|
<s> from distutils . core import setup <EOL> setup ( <EOL> name = '<STR_LIT>' , <EOL> version = '<STR_LIT:1.0>' , <EOL> packages = [ '<STR_LIT>' , ] , <EOL> description = '<STR_LIT>' , <EOL> long_description = '<STR_LIT>' , <EOL> license = "<STR_LIT>" , <EOL> install_requires = [ '<STR_LIT>' , '<STR_LIT>' ] <EOL> ) </s>
|
<s> import numpy as np <EOL> import brnnet as rnn <EOL> import rnnetcpu as rnncp <EOL> import dataLoader as dl <EOL> layerSize = <NUM_LIT:100> <EOL> numLayers = <NUM_LIT:3> <EOL> dataDir = "<STR_LIT>" <EOL> inputDim = <NUM_LIT> * <NUM_LIT:15> <EOL> rawDim = <NUM_LIT> * <NUM_LIT:15> <EOL> outputDim = <NUM_LIT> <EOL> maxUttLen = <NUM_LIT> <EOL> loader = dl . DataLoader ( dataDir , rawDim , inputDim ) <EOL> data_dict , alis , keys , _ = loader . loadDataFileDict ( <NUM_LIT:1> ) <EOL> data , labels = data_dict [ keys [ <NUM_LIT:3> ] ] , np . array ( alis [ keys [ <NUM_LIT:3> ] ] , dtype = np . int32 ) <EOL> np . random . seed ( <NUM_LIT> ) <EOL> rnn = rnn . NNet ( inputDim , outputDim , layerSize , numLayers , maxUttLen , temporalLayer = <NUM_LIT:2> ) <EOL> rnn . initParams ( ) <EOL> cost , grad , _ = rnn . costAndGrad ( data , labels ) <EOL> print "<STR_LIT>" % cost <EOL> np . random . seed ( <NUM_LIT> ) <EOL> rnncp = rnncp . RNNet ( inputDim , outputDim , layerSize , numLayers , maxUttLen , temporalLayer = <NUM_LIT:2> ) <EOL> rnncp . initParams ( ) <EOL> cost , gradcp , _ = rnncp . costAndGrad ( data , labels ) <EOL> print "<STR_LIT>" % cost <EOL> def diff ( ga , gb ) : <EOL> ga . copy_to_host ( ) <EOL> print np . sum ( ( ga . numpy_array - gb ) ** <NUM_LIT:2> ) <EOL> for gas , gbs in zip ( grad , gradcp ) : <EOL> ga , ba = gas <EOL> gb , bb = gbs <EOL> diff ( ga , gb ) <EOL> diff ( ba , bb ) </s>
|
<s> import os <EOL> from os . path import join as pjoin <EOL> CTC_DIR = os . path . dirname ( os . path . abspath ( __file__ ) ) <EOL> RUN_DIR = '<STR_LIT>' <EOL> SWBD_EXP_DIR = '<STR_LIT>' <EOL> SWBD_EXP_DIR_DELTA = '<STR_LIT>' <EOL> TRAIN_DATA_DIR = { <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) , <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) , <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR_DELTA , '<STR_LIT>' ) <EOL> } <EOL> TRAIN_ALIS_DIR = pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) <EOL> DEV_DATA_DIR = { <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) , <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) , <EOL> } <EOL> DEV_ALIS_DIR = pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) <EOL> TEST_DATA_DIR = { <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) , <EOL> '<STR_LIT>' : pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) , <EOL> } <EOL> TEST_ALIS_DIR = pjoin ( SWBD_EXP_DIR , '<STR_LIT>' ) <EOL> FEAT_DIMS = { <EOL> '<STR_LIT>' : <NUM_LIT:15> , <EOL> '<STR_LIT>' : <NUM_LIT> <EOL> } <EOL> RAW_CONTEXTS = { <EOL> '<STR_LIT>' : <NUM_LIT> , <EOL> '<STR_LIT>' : <NUM_LIT> <EOL> } <EOL> VIEWER_DIR = '<STR_LIT>' <EOL> BROWSE_RUNS_KEYS = [ <EOL> '<STR_LIT>' , '<STR_LIT:host>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> ] </s>
|
<s> from django . conf import settings <EOL> from account . models import Account , AnonymousAccount <EOL> def account ( request ) : <EOL> if request . user . is_authenticated ( ) : <EOL> try : <EOL> account = Account . _default_manager . get ( user = request . user ) <EOL> except Account . DoesNotExist : <EOL> account = AnonymousAccount ( request ) <EOL> else : <EOL> account = AnonymousAccount ( request ) <EOL> return { <EOL> "<STR_LIT>" : account , <EOL> "<STR_LIT>" : getattr ( settings , "<STR_LIT>" , "<STR_LIT>" ) <EOL> } </s>
|
<s> from avatar . models import Avatar , avatar_file_path <EOL> from avatar . forms import PrimaryAvatarForm , DeleteAvatarForm <EOL> from django . http import HttpResponseRedirect <EOL> from django . shortcuts import render_to_response <EOL> from django . template import RequestContext <EOL> from django . contrib . auth . decorators import login_required <EOL> from django . contrib import messages <EOL> from django . utils . translation import ugettext as _ <EOL> from django . db . models import get_app <EOL> from django . core . exceptions import ImproperlyConfigured <EOL> from django . conf import settings <EOL> friends = False <EOL> if '<STR_LIT>' in settings . INSTALLED_APPS : <EOL> friends = True <EOL> from friends . models import Friendship <EOL> def _get_next ( request ) : <EOL> """<STR_LIT>""" <EOL> next = request . POST . get ( '<STR_LIT>' , request . GET . get ( '<STR_LIT>' , request . META . get ( '<STR_LIT>' , None ) ) ) <EOL> if not next : <EOL> next = request . path <EOL> return next <EOL> def change ( request , extra_context = { } , next_override = None ) : <EOL> avatars = Avatar . objects . filter ( user = request . user ) . order_by ( '<STR_LIT>' ) <EOL> if avatars . count ( ) > <NUM_LIT:0> : <EOL> avatar = avatars [ <NUM_LIT:0> ] <EOL> kwargs = { '<STR_LIT>' : { '<STR_LIT>' : avatar . id } } <EOL> else : <EOL> avatar = None <EOL> kwargs = { } <EOL> primary_avatar_form = PrimaryAvatarForm ( request . POST or None , user = request . user , ** kwargs ) <EOL> if request . method == "<STR_LIT:POST>" : <EOL> updated = False <EOL> if '<STR_LIT>' in request . FILES : <EOL> path = avatar_file_path ( user = request . user , <EOL> filename = request . FILES [ '<STR_LIT>' ] . name ) <EOL> avatar = Avatar ( <EOL> user = request . user , <EOL> primary = True , <EOL> avatar = path , <EOL> ) <EOL> new_file = avatar . avatar . storage . save ( path , request . FILES [ '<STR_LIT>' ] ) <EOL> avatar . save ( ) <EOL> updated = True <EOL> messages . success ( request , message = _ ( "<STR_LIT>" ) ) <EOL> if '<STR_LIT>' in request . POST and primary_avatar_form . is_valid ( ) : <EOL> avatar = Avatar . objects . get ( id = <EOL> primary_avatar_form . cleaned_data [ '<STR_LIT>' ] ) <EOL> avatar . primary = True <EOL> avatar . save ( ) <EOL> updated = True <EOL> messages . success ( request , <EOL> message = _ ( "<STR_LIT>" ) ) <EOL> return HttpResponseRedirect ( next_override or _get_next ( request ) ) <EOL> return render_to_response ( <EOL> '<STR_LIT>' , <EOL> extra_context , <EOL> context_instance = RequestContext ( <EOL> request , <EOL> { '<STR_LIT>' : avatar , <EOL> '<STR_LIT>' : avatars , <EOL> '<STR_LIT>' : primary_avatar_form , <EOL> '<STR_LIT>' : next_override or _get_next ( request ) , } <EOL> ) <EOL> ) <EOL> change = login_required ( change ) <EOL> def delete ( request , extra_context = { } , next_override = None ) : <EOL> avatars = Avatar . objects . filter ( user = request . user ) . order_by ( '<STR_LIT>' ) <EOL> if avatars . count ( ) > <NUM_LIT:0> : <EOL> avatar = avatars [ <NUM_LIT:0> ] <EOL> else : <EOL> avatar = None <EOL> delete_avatar_form = DeleteAvatarForm ( request . POST or None , user = request . user ) <EOL> if request . method == '<STR_LIT:POST>' : <EOL> if delete_avatar_form . is_valid ( ) : <EOL> ids = delete_avatar_form . cleaned_data [ '<STR_LIT>' ] <EOL> if unicode ( avatar . id ) in ids and avatars . count ( ) > len ( ids ) : <EOL> for a in avatars : <EOL> if unicode ( a . id ) not in ids : <EOL> a . primary = True <EOL> a . save ( ) <EOL> break <EOL> Avatar . objects . filter ( id__in = ids ) . delete ( ) <EOL> messages . success ( request , <EOL> message = _ ( "<STR_LIT>" ) ) <EOL> return HttpResponseRedirect ( next_override or _get_next ( request ) ) <EOL> return render_to_response ( <EOL> '<STR_LIT>' , <EOL> extra_context , <EOL> context_instance = RequestContext ( <EOL> request , <EOL> { '<STR_LIT>' : avatar , <EOL> '<STR_LIT>' : avatars , <EOL> '<STR_LIT>' : delete_avatar_form , <EOL> '<STR_LIT>' : next_override or _get_next ( request ) , } <EOL> ) <EOL> ) <EOL> delete = login_required ( delete ) </s>
|
<s> DEBUG = True <EOL> TEMPLATE_DEBUG = True <EOL> DATABASE_ENGINE = '<STR_LIT>' <EOL> DATABASE_NAME = '<STR_LIT>' <EOL> DATABASE_USER = '<STR_LIT>' </s>
|
<s> from friends . models import FriendshipInvitation <EOL> def invitations ( request ) : <EOL> if request . user . is_authenticated ( ) : <EOL> return { <EOL> "<STR_LIT>" : FriendshipInvitation . objects . filter ( <EOL> to_user = request . user , <EOL> status = "<STR_LIT:2>" <EOL> ) . count ( ) <EOL> } <EOL> else : <EOL> return { } </s>
|
<s> from django . core import mail <EOL> from smeuhoverride . tests import BaseTestCase <EOL> from smtplib import SMTPRecipientsRefused <EOL> from mock import patch <EOL> class TestTouites ( BaseTestCase ) : <EOL> def check_toggle_follow ( self , action ) : <EOL> self . login ( self . me . username ) <EOL> resp = self . client . post ( <EOL> '<STR_LIT>' % self . her . username , { <EOL> '<STR_LIT:action>' : action , <EOL> } , follow = True ) <EOL> self . assertEqual ( resp . status_code , <NUM_LIT:200> ) <EOL> def test_follow ( self ) : <EOL> self . check_toggle_follow ( '<STR_LIT>' ) <EOL> def test_unfollow ( self ) : <EOL> self . check_toggle_follow ( '<STR_LIT>' ) <EOL> def test_post ( self ) : <EOL> response = self . client . post ( "<STR_LIT>" , { <EOL> '<STR_LIT:text>' : '<STR_LIT>' <EOL> } , follow = True ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> def test_get_list_no_param ( self ) : <EOL> response = self . client . get ( "<STR_LIT>" ) <EOL> self . assertNotContains ( response , "<STR_LIT:None>" ) <EOL> def test_get_list_with_reply_param ( self ) : <EOL> response = self . client . get ( "<STR_LIT>" ) <EOL> self . assertContains ( response , "<STR_LIT>" ) <EOL> def test_reply_send_notification_email ( self ) : <EOL> self . her . email = "<STR_LIT>" <EOL> self . her . save ( ) <EOL> self . client . post ( "<STR_LIT>" , { <EOL> '<STR_LIT:text>' : '<STR_LIT>' <EOL> } , follow = True ) <EOL> self . assertEqual ( len ( mail . outbox ) , <NUM_LIT:1> ) <EOL> @ patch ( '<STR_LIT>' ) <EOL> def test_reply_to_user_with_invalid_email_address ( self , email_mock ) : <EOL> email_mock . return_value . send_messages . side_effect = [ <EOL> SMTPRecipientsRefused ( '<STR_LIT>' ) , <EOL> True , <EOL> ] <EOL> self . her . email = "<STR_LIT>" <EOL> self . her . save ( ) <EOL> response = self . client . post ( "<STR_LIT>" , { <EOL> '<STR_LIT:text>' : '<STR_LIT>' <EOL> } , follow = True ) <EOL> self . assertContains ( response , '<STR_LIT>' ) <EOL> self . assertEqual ( len ( mail . outbox ) , <NUM_LIT:0> ) </s>
|
<s> from django . db . models import Q <EOL> from django . core . exceptions import ObjectDoesNotExist <EOL> from django . core . urlresolvers import reverse <EOL> from django . http import Http404 , HttpResponseRedirect <EOL> from django . shortcuts import render_to_response , get_object_or_404 <EOL> from django . template import RequestContext <EOL> from django . utils . translation import ugettext , ugettext_lazy as _ <EOL> from django . contrib import messages <EOL> from django . contrib . auth . models import User <EOL> from django . contrib . auth . decorators import login_required <EOL> from photologue . models import * <EOL> from friends . models import friend_set_for <EOL> from photos . models import Image , Pool <EOL> from photos . forms import PhotoUploadForm , PhotoEditForm <EOL> from tagging . models import TaggedItem <EOL> def group_and_bridge ( request ) : <EOL> """<STR_LIT>""" <EOL> group = getattr ( request , "<STR_LIT>" , None ) <EOL> if group : <EOL> bridge = request . bridge <EOL> else : <EOL> bridge = None <EOL> return group , bridge <EOL> def group_context ( group , bridge ) : <EOL> ctx = { <EOL> "<STR_LIT>" : group , <EOL> } <EOL> if group : <EOL> ctx [ "<STR_LIT>" ] = bridge . group_base_template ( ) <EOL> return ctx <EOL> @ login_required <EOL> def upload ( request , form_class = PhotoUploadForm , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> group , bridge = group_and_bridge ( request ) <EOL> photo_form = form_class ( ) <EOL> if request . method == "<STR_LIT:POST>" : <EOL> if request . POST . get ( "<STR_LIT:action>" ) == "<STR_LIT>" : <EOL> photo_form = form_class ( request . user , request . POST , request . FILES ) <EOL> if photo_form . is_valid ( ) : <EOL> photo = photo_form . save ( commit = False ) <EOL> photo . member = request . user <EOL> photo . save ( ) <EOL> if group : <EOL> pool = Pool ( ) <EOL> pool . photo = photo <EOL> group . associate ( pool , gfk_field = "<STR_LIT>" ) <EOL> pool . save ( ) <EOL> messages . add_message ( request , messages . SUCCESS , <EOL> ugettext ( "<STR_LIT>" ) % photo . title <EOL> ) <EOL> include_kwargs = { "<STR_LIT:id>" : photo . id } <EOL> if group : <EOL> redirect_to = bridge . reverse ( "<STR_LIT>" , group , kwargs = include_kwargs ) <EOL> else : <EOL> redirect_to = reverse ( "<STR_LIT>" , kwargs = include_kwargs ) <EOL> return HttpResponseRedirect ( redirect_to ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photo_form , <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def your_photos ( request , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> group , bridge = group_and_bridge ( request ) <EOL> photos = Image . objects . filter ( member = request . user ) <EOL> if group : <EOL> photos = group . content_objects ( photos , join = "<STR_LIT>" , gfk_field = "<STR_LIT>" ) <EOL> else : <EOL> photos = photos . filter ( pool__object_id = None ) <EOL> photos = photos . order_by ( "<STR_LIT>" ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photos , <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def photos ( request , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> group , bridge = group_and_bridge ( request ) <EOL> photos = Image . objects . filter ( <EOL> Q ( is_public = True ) | Q ( member = request . user ) | <EOL> Q ( member__in = friend_set_for ( request . user ) ) <EOL> ) <EOL> if group : <EOL> photos = group . content_objects ( photos , join = "<STR_LIT>" , gfk_field = "<STR_LIT>" ) <EOL> else : <EOL> photos = photos . filter ( pool__object_id = None ) <EOL> photos = photos . order_by ( "<STR_LIT>" ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photos , <EOL> "<STR_LIT:title>" : "<STR_LIT>" <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def most_viewed ( request , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> group , bridge = group_and_bridge ( request ) <EOL> photos = Image . objects . filter ( <EOL> Q ( is_public = True ) | Q ( member = request . user ) <EOL> | Q ( member__in = friend_set_for ( request . user ) ) <EOL> ) <EOL> if group : <EOL> photos = group . content_objects ( photos , join = "<STR_LIT>" , gfk_field = "<STR_LIT>" ) <EOL> else : <EOL> photos = photos . filter ( pool__object_id = None ) <EOL> photos = photos . order_by ( "<STR_LIT>" ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photos , <EOL> "<STR_LIT:title>" : _ ( "<STR_LIT>" ) <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> def get_first_id_or_none ( objects ) : <EOL> try : <EOL> return objects [ <NUM_LIT:0> ] . id <EOL> except IndexError : <EOL> return None <EOL> def details ( request , id , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> photos = Image . objects . all ( ) <EOL> photos = photos . filter ( pool__object_id = None ) <EOL> image_filter = Q ( is_public = True ) <EOL> if request . user . is_authenticated ( ) : <EOL> image_filter = image_filter | Q ( member = request . user ) | Q ( member__in = friend_set_for ( request . user ) ) <EOL> try : <EOL> photo = photos . filter ( image_filter , id = id ) [ <NUM_LIT:0> ] <EOL> except IndexError : <EOL> raise Http404 <EOL> previous_photo_id = get_first_id_or_none ( <EOL> photos . filter ( image_filter , id__lt = photo . id ) . order_by ( '<STR_LIT>' ) <EOL> ) <EOL> next_photo_id = get_first_id_or_none ( <EOL> photos . filter ( image_filter , id__gt = photo . id ) . order_by ( '<STR_LIT:id>' ) <EOL> ) <EOL> ctx = { <EOL> "<STR_LIT>" : photo , <EOL> "<STR_LIT>" : request . build_absolute_uri ( photo . get_display_url ( ) ) , <EOL> "<STR_LIT:url>" : request . build_absolute_uri ( ) , <EOL> "<STR_LIT>" : photo . member == request . user , <EOL> "<STR_LIT>" : previous_photo_id , <EOL> "<STR_LIT>" : next_photo_id , <EOL> } <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def user_photos ( request , username , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> user = get_object_or_404 ( User , username = username ) <EOL> image_filter = Q ( is_public = True ) <EOL> if request . user . is_authenticated ( ) : <EOL> image_filter = image_filter | Q ( member = request . user ) | Q ( member__in = friend_set_for ( request . user ) ) <EOL> photos = Image . objects . filter ( <EOL> image_filter , <EOL> member = user <EOL> ) <EOL> photos = photos . order_by ( "<STR_LIT>" ) <EOL> group , bridge = group_and_bridge ( request ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photos , <EOL> "<STR_LIT:username>" : username <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def tagged_photos ( request , tagname , template_name = "<STR_LIT>" ) : <EOL> """<STR_LIT>""" <EOL> image_filter = Q ( is_public = True ) <EOL> if request . user . is_authenticated ( ) : <EOL> image_filter = image_filter | Q ( member = request . user ) | Q ( member__in = friend_set_for ( request . user ) ) <EOL> photos = TaggedItem . objects . get_by_model ( Image , tagname ) . filter ( image_filter ) . order_by ( "<STR_LIT>" ) <EOL> group , bridge = group_and_bridge ( request ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photos , <EOL> "<STR_LIT>" : tagname <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def edit ( request , id , form_class = PhotoEditForm , template_name = "<STR_LIT>" ) : <EOL> group , bridge = group_and_bridge ( request ) <EOL> photos = Image . objects . all ( ) <EOL> if group : <EOL> photos = group . content_objects ( photos , join = "<STR_LIT>" , gfk_field = "<STR_LIT>" ) <EOL> else : <EOL> photos = photos . filter ( pool__object_id = None ) <EOL> photo = get_object_or_404 ( photos , id = id ) <EOL> photo_url = photo . get_display_url ( ) <EOL> if request . method == "<STR_LIT:POST>" : <EOL> if photo . member != request . user : <EOL> message . add_message ( request , messages . ERROR , <EOL> ugettext ( "<STR_LIT>" ) <EOL> ) <EOL> include_kwargs = { "<STR_LIT:id>" : photo . id } <EOL> if group : <EOL> redirect_to = bridge . reverse ( "<STR_LIT>" , group , kwargs = include_kwargs ) <EOL> else : <EOL> redirect_to = reverse ( "<STR_LIT>" , kwargs = include_kwargs ) <EOL> return HttpResponseRedirect ( reverse ( '<STR_LIT>' , args = ( photo . id , ) ) ) <EOL> if request . POST [ "<STR_LIT:action>" ] == "<STR_LIT>" : <EOL> photo_form = form_class ( request . user , request . POST , instance = photo ) <EOL> if photo_form . is_valid ( ) : <EOL> photoobj = photo_form . save ( commit = False ) <EOL> photoobj . save ( ) <EOL> messages . add_message ( request , messages . SUCCESS , <EOL> ugettext ( "<STR_LIT>" ) % photo . title <EOL> ) <EOL> include_kwargs = { "<STR_LIT:id>" : photo . id } <EOL> if group : <EOL> redirect_to = bridge . reverse ( "<STR_LIT>" , group , kwargs = include_kwargs ) <EOL> else : <EOL> redirect_to = reverse ( "<STR_LIT>" , kwargs = include_kwargs ) <EOL> return HttpResponseRedirect ( redirect_to ) <EOL> else : <EOL> photo_form = form_class ( instance = photo ) <EOL> else : <EOL> photo_form = form_class ( instance = photo ) <EOL> ctx = group_context ( group , bridge ) <EOL> ctx . update ( { <EOL> "<STR_LIT>" : photo_form , <EOL> "<STR_LIT>" : photo , <EOL> "<STR_LIT>" : photo_url , <EOL> } ) <EOL> return render_to_response ( template_name , RequestContext ( request , ctx ) ) <EOL> @ login_required <EOL> def destroy ( request , id ) : <EOL> group , bridge = group_and_bridge ( request ) <EOL> photos = Image . objects . all ( ) <EOL> if group : <EOL> photos = group . content_objects ( photos , join = "<STR_LIT>" , gfk_field = "<STR_LIT>" ) <EOL> else : <EOL> photos = photos . filter ( pool__object_id = None ) <EOL> photo = get_object_or_404 ( photos , id = id ) <EOL> title = photo . title <EOL> if group : <EOL> redirect_to = bridge . reverse ( "<STR_LIT>" , group ) <EOL> else : <EOL> redirect_to = reverse ( "<STR_LIT>" ) <EOL> if photo . member != request . user : <EOL> message . add_message ( request , messages . ERROR , <EOL> ugettext ( "<STR_LIT>" ) <EOL> ) <EOL> return HttpResponseRedirect ( redirect_to ) <EOL> if request . method == "<STR_LIT:POST>" and request . POST [ "<STR_LIT:action>" ] == "<STR_LIT>" : <EOL> photo . delete ( ) <EOL> messages . add_message ( request , messages . SUCCESS , <EOL> ugettext ( "<STR_LIT>" ) % title <EOL> ) <EOL> return HttpResponseRedirect ( redirect_to ) <EOL> @ login_required <EOL> def random ( request ) : <EOL> image_filter = Q ( is_public = True ) <EOL> if request . user . is_authenticated ( ) : <EOL> image_filter = image_filter | Q ( member = request . user ) | Q ( member__in = friend_set_for ( request . user ) ) <EOL> photo = Image . objects . filter ( image_filter ) . order_by ( '<STR_LIT:?>' ) [ <NUM_LIT:0> ] <EOL> return HttpResponseRedirect ( reverse ( '<STR_LIT>' , args = ( photo . id , ) ) ) </s>
|
<s> from django . contrib import admin <EOL> from django . utils . translation import ugettext_lazy as _ <EOL> from threadedcomments . models import ThreadedComment , FreeThreadedComment <EOL> class ThreadedCommentAdmin ( admin . ModelAdmin ) : <EOL> fieldsets = ( <EOL> ( None , { '<STR_LIT>' : ( '<STR_LIT>' , '<STR_LIT>' ) } ) , <EOL> ( _ ( '<STR_LIT>' ) , { '<STR_LIT>' : ( '<STR_LIT>' , ) } ) , <EOL> ( _ ( '<STR_LIT>' ) , { '<STR_LIT>' : ( '<STR_LIT:user>' , '<STR_LIT>' ) } ) , <EOL> ( _ ( '<STR_LIT:Meta>' ) , { '<STR_LIT>' : ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' ) } ) , <EOL> ) <EOL> list_display = ( '<STR_LIT:user>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> list_filter = ( '<STR_LIT>' , ) <EOL> date_hierarchy = '<STR_LIT>' <EOL> search_fields = ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> class FreeThreadedCommentAdmin ( admin . ModelAdmin ) : <EOL> fieldsets = ( <EOL> ( None , { '<STR_LIT>' : ( '<STR_LIT>' , '<STR_LIT>' ) } ) , <EOL> ( _ ( '<STR_LIT>' ) , { '<STR_LIT>' : ( '<STR_LIT>' , ) } ) , <EOL> ( _ ( '<STR_LIT>' ) , { '<STR_LIT>' : ( '<STR_LIT:name>' , '<STR_LIT>' , '<STR_LIT:email>' , '<STR_LIT>' ) } ) , <EOL> ( _ ( '<STR_LIT:Meta>' ) , { '<STR_LIT>' : ( <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' ) } ) , <EOL> ) <EOL> list_display = ( '<STR_LIT:name>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ) <EOL> list_filter = ( '<STR_LIT>' , ) <EOL> date_hierarchy = '<STR_LIT>' <EOL> search_fields = ( '<STR_LIT>' , '<STR_LIT:name>' , '<STR_LIT:email>' , '<STR_LIT>' ) <EOL> admin . site . register ( ThreadedComment , ThreadedCommentAdmin ) <EOL> admin . site . register ( FreeThreadedComment , FreeThreadedCommentAdmin ) </s>
|
<s> from south . utils import datetime_utils as datetime <EOL> from south . db import db <EOL> from south . v2 import SchemaMigration <EOL> from django . db import models <EOL> class Migration ( SchemaMigration ) : <EOL> depends_on = ( <EOL> ( '<STR_LIT>' , '<STR_LIT>' ) , <EOL> ) <EOL> def forwards ( self , orm ) : <EOL> db . create_table ( u'<STR_LIT>' , ( <EOL> ( u'<STR_LIT:id>' , self . gf ( '<STR_LIT>' ) ( primary_key = True ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] ) ) , <EOL> ( '<STR_LIT:source>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] , null = True ) ) , <EOL> ) ) <EOL> db . send_create_signal ( u'<STR_LIT>' , [ '<STR_LIT>' ] ) <EOL> db . create_table ( u'<STR_LIT>' , ( <EOL> ( u'<STR_LIT:id>' , self . gf ( '<STR_LIT>' ) ( primary_key = True ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] ) ) , <EOL> ( '<STR_LIT:source>' , self . gf ( '<STR_LIT>' ) ( to = orm [ '<STR_LIT>' ] ) ) , <EOL> ) ) <EOL> db . send_create_signal ( u'<STR_LIT>' , [ '<STR_LIT>' ] ) <EOL> db . create_table ( u'<STR_LIT>' , ( <EOL> ( u'<STR_LIT:id>' , self . gf ( '<STR_LIT>' ) ( primary_key = True ) ) , <EOL> ( '<STR_LIT:name>' , self . gf ( '<STR_LIT>' ) ( unique = True , max_length = <NUM_LIT:64> ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( max_length = <NUM_LIT:64> ) ) , <EOL> ( '<STR_LIT:description>' , self . gf ( '<STR_LIT>' ) ( ) ) , <EOL> ) ) <EOL> db . send_create_signal ( u'<STR_LIT>' , [ '<STR_LIT>' ] ) <EOL> db . create_table ( u'<STR_LIT>' , ( <EOL> ( u'<STR_LIT:id>' , self . gf ( '<STR_LIT>' ) ( primary_key = True ) ) , <EOL> ( '<STR_LIT:name>' , self . gf ( '<STR_LIT>' ) ( unique = True , max_length = <NUM_LIT:64> ) ) , <EOL> ( '<STR_LIT>' , self . gf ( '<STR_LIT>' ) ( max_length = <NUM_LIT:64> ) ) , <EOL> ( '<STR_LIT:description>' , self . gf ( '<STR_LIT>' ) ( ) ) , <EOL> ) ) <EOL> db . send_create_signal ( u'<STR_LIT>' , [ '<STR_LIT>' ] ) <EOL> def backwards ( self , orm ) : <EOL> db . delete_table ( u'<STR_LIT>' ) <EOL> db . delete_table ( u'<STR_LIT>' ) <EOL> db . delete_table ( u'<STR_LIT>' ) <EOL> db . delete_table ( u'<STR_LIT>' ) <EOL> models = { <EOL> u'<STR_LIT>' : { <EOL> '<STR_LIT:Meta>' : { '<STR_LIT>' : "<STR_LIT>" , '<STR_LIT>' : "<STR_LIT>" , '<STR_LIT:object_name>' : '<STR_LIT>' , '<STR_LIT>' : "<STR_LIT>" } , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:max_length>' : '<STR_LIT:100>' } ) , <EOL> u'<STR_LIT:id>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:primary_key>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:max_length>' : '<STR_LIT:100>' } ) , <EOL> '<STR_LIT:name>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:max_length>' : '<STR_LIT:100>' } ) <EOL> } , <EOL> u'<STR_LIT>' : { <EOL> '<STR_LIT:Meta>' : { '<STR_LIT:object_name>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:null>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) , <EOL> u'<STR_LIT:id>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:primary_key>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:default>' : '<STR_LIT:True>' } ) <EOL> } , <EOL> u'<STR_LIT>' : { <EOL> '<STR_LIT:Meta>' : { '<STR_LIT:object_name>' : '<STR_LIT>' } , <EOL> '<STR_LIT:description>' : ( '<STR_LIT>' , [ ] , { } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:max_length>' : '<STR_LIT>' } ) , <EOL> u'<STR_LIT:id>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:primary_key>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT:name>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT>' : '<STR_LIT:True>' , '<STR_LIT:max_length>' : '<STR_LIT>' } ) <EOL> } , <EOL> u'<STR_LIT>' : { <EOL> '<STR_LIT:Meta>' : { '<STR_LIT:object_name>' : '<STR_LIT>' } , <EOL> '<STR_LIT:description>' : ( '<STR_LIT>' , [ ] , { } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:max_length>' : '<STR_LIT>' } ) , <EOL> u'<STR_LIT:id>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:primary_key>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT:name>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT>' : '<STR_LIT:True>' , '<STR_LIT:max_length>' : '<STR_LIT>' } ) <EOL> } , <EOL> u'<STR_LIT>' : { <EOL> '<STR_LIT:Meta>' : { '<STR_LIT:object_name>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) , <EOL> u'<STR_LIT:id>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:primary_key>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) , <EOL> '<STR_LIT:source>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" , '<STR_LIT:null>' : '<STR_LIT:True>' } ) <EOL> } , <EOL> u'<STR_LIT>' : { <EOL> '<STR_LIT:Meta>' : { '<STR_LIT:object_name>' : '<STR_LIT>' } , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) , <EOL> u'<STR_LIT:id>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:primary_key>' : '<STR_LIT:True>' } ) , <EOL> '<STR_LIT>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) , <EOL> '<STR_LIT:source>' : ( '<STR_LIT>' , [ ] , { '<STR_LIT:to>' : u"<STR_LIT>" } ) <EOL> } <EOL> } <EOL> complete_apps = [ '<STR_LIT>' ] </s>
|
<s> from querybuilder . query import Query <EOL> from querybuilder . tests . query_tests import QueryTestCase , get_comparison_str <EOL> class LimitTest ( QueryTestCase ) : <EOL> def test_limit ( self ) : <EOL> query = Query ( ) . from_table ( <EOL> table = '<STR_LIT>' <EOL> ) . limit ( <NUM_LIT:10> ) <EOL> query_str = query . get_sql ( ) <EOL> expected_query = '<STR_LIT>' <EOL> self . assertEqual ( query_str , expected_query , get_comparison_str ( query_str , expected_query ) ) <EOL> def test_offset ( self ) : <EOL> query = Query ( ) . from_table ( <EOL> table = '<STR_LIT>' <EOL> ) . limit ( <EOL> offset = <NUM_LIT:10> <EOL> ) <EOL> query_str = query . get_sql ( ) <EOL> expected_query = '<STR_LIT>' <EOL> self . assertEqual ( query_str , expected_query , get_comparison_str ( query_str , expected_query ) ) <EOL> def test_limit_with_offset ( self ) : <EOL> query = Query ( ) . from_table ( <EOL> table = '<STR_LIT>' <EOL> ) . limit ( <EOL> limit = <NUM_LIT:5> , <EOL> offset = <NUM_LIT:20> <EOL> ) <EOL> query_str = query . get_sql ( ) <EOL> expected_query = '<STR_LIT>' <EOL> self . assertEqual ( query_str , expected_query , get_comparison_str ( query_str , expected_query ) ) </s>
|
<s> from django . conf import settings <EOL> def anchor_to_text ( attrs ) : <EOL> text = attrs . get ( '<STR_LIT>' ) . strip ( ) <EOL> title = attrs . get ( '<STR_LIT:title>' , attrs . get ( '<STR_LIT:text>' , '<STR_LIT>' ) ) . strip ( ) <EOL> if text == title or not title : <EOL> return text <EOL> return '<STR_LIT>' % ( title , text ) <EOL> def image_to_text ( attrs ) : <EOL> text = attrs . get ( '<STR_LIT:src>' ) . strip ( ) <EOL> title = attrs . get ( '<STR_LIT:title>' , attrs . get ( '<STR_LIT>' , '<STR_LIT>' ) ) . strip ( ) <EOL> if not title : <EOL> return text <EOL> return '<STR_LIT>' % ( title , text ) <EOL> FIRSTCLASS_TEXT_ANCHOR = getattr ( settings , '<STR_LIT>' , anchor_to_text ) <EOL> FIRSTCLASS_TEXT_IMAGE = getattr ( settings , '<STR_LIT>' , image_to_text ) <EOL> FIRSTCLASS_PLAINTEXT_RULES = getattr ( settings , '<STR_LIT>' , { <EOL> '<STR_LIT:a>' : FIRSTCLASS_TEXT_ANCHOR , <EOL> '<STR_LIT>' : FIRSTCLASS_TEXT_IMAGE , <EOL> } ) </s>
|
<s> from django . contrib . auth . decorators import login_required <EOL> from django_stripe . views import BaseCardTokenFormView <EOL> class AccountBillingFormView ( BaseCardTokenFormView ) : <EOL> def get_last4 ( self ) : <EOL> user_profile = self . request . user . get_profile ( ) <EOL> return user_profile . card_last4 <EOL> def form_valid ( self , form ) : <EOL> customer = form . save ( self . request . user ) <EOL> user_profile = self . request . user . get_profile ( ) <EOL> user_profile . customer_id = customer . id <EOL> user_profile . card_last4 = customer . active_card . last4 <EOL> user_profile . save ( ) <EOL> return super ( AccountBillingFormView , self ) . form_valid ( form ) <EOL> account_billing_form = login_required ( AccountBillingFormView . as_view ( ) ) </s>
|
<s> from django import template <EOL> import cgi , urllib <EOL> register = template . Library ( ) <EOL> @ register . inclusion_tag ( '<STR_LIT>' , takes_context = True ) <EOL> def paginator ( context , adjacent_pages = <NUM_LIT:2> ) : <EOL> """<STR_LIT>""" <EOL> page_numbers = [ <EOL> n <EOL> for n in range ( <EOL> context [ '<STR_LIT>' ] - adjacent_pages , <EOL> context [ '<STR_LIT>' ] + adjacent_pages + <NUM_LIT:1> <EOL> ) <EOL> if n > <NUM_LIT:0> and n <= context [ '<STR_LIT>' ] <EOL> ] <EOL> path = context . get ( "<STR_LIT>" , context [ "<STR_LIT>" ] . path ) <EOL> querystring = context [ "<STR_LIT>" ] . META . get ( "<STR_LIT>" ) <EOL> if not querystring : querystring = "<STR_LIT>" <EOL> query_dict = dict ( cgi . parse_qsl ( querystring ) ) <EOL> if "<STR_LIT>" in query_dict : del query_dict [ "<STR_LIT>" ] <EOL> querystring = urllib . urlencode ( query_dict ) <EOL> if querystring : <EOL> path = "<STR_LIT>" % ( path , querystring ) <EOL> else : <EOL> path = "<STR_LIT>" % path <EOL> return { <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : page_numbers , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] , <EOL> '<STR_LIT>' : <NUM_LIT:1> not in page_numbers , <EOL> '<STR_LIT>' : context [ '<STR_LIT>' ] not in page_numbers , <EOL> '<STR_LIT:path>' : path , <EOL> } </s>
|
<s> from importd import d <EOL> @ d <EOL> def index2 ( request ) : <EOL> return d . HttpResponse ( "<STR_LIT>" ) </s>
|
<s> """<STR_LIT>""" </s>
|
<s> from depot . io import utils <EOL> from depot . manager import DepotManager <EOL> from . . upload import UploadedFile <EOL> from depot . io . interfaces import FileStorage <EOL> from PIL import Image <EOL> from depot . io . utils import INMEMORY_FILESIZE <EOL> from tempfile import SpooledTemporaryFile <EOL> class UploadedImageWithThumb ( UploadedFile ) : <EOL> """<STR_LIT>""" <EOL> max_size = <NUM_LIT> <EOL> thumbnail_format = '<STR_LIT>' <EOL> thumbnail_size = ( <NUM_LIT> , <NUM_LIT> ) <EOL> def process_content ( self , content , filename = None , content_type = None ) : <EOL> orig_content = content <EOL> content = utils . file_from_content ( content ) <EOL> __ , filename , content_type = FileStorage . fileinfo ( orig_content ) <EOL> uploaded_image = Image . open ( content ) <EOL> if max ( uploaded_image . size ) >= self . max_size : <EOL> uploaded_image . thumbnail ( ( self . max_size , self . max_size ) , Image . BILINEAR ) <EOL> content = SpooledTemporaryFile ( INMEMORY_FILESIZE ) <EOL> uploaded_image . save ( content , uploaded_image . format ) <EOL> content . seek ( <NUM_LIT:0> ) <EOL> super ( UploadedImageWithThumb , self ) . process_content ( content , filename , content_type ) <EOL> thumbnail = uploaded_image . copy ( ) <EOL> thumbnail . thumbnail ( self . thumbnail_size , Image . ANTIALIAS ) <EOL> thumbnail = thumbnail . convert ( '<STR_LIT>' ) <EOL> thumbnail . format = self . thumbnail_format <EOL> output = SpooledTemporaryFile ( INMEMORY_FILESIZE ) <EOL> thumbnail . save ( output , self . thumbnail_format ) <EOL> output . seek ( <NUM_LIT:0> ) <EOL> thumb_path , thumb_id = self . store_content ( output , <EOL> '<STR_LIT>' % self . thumbnail_format . lower ( ) ) <EOL> self [ '<STR_LIT>' ] = thumb_id <EOL> self [ '<STR_LIT>' ] = thumb_path <EOL> thumbnail_file = self . thumb_file <EOL> self [ '<STR_LIT>' ] = thumbnail_file . public_url <EOL> @ property <EOL> def thumb_file ( self ) : <EOL> return self . depot . get ( self . thumb_id ) <EOL> @ property <EOL> def thumb_url ( self ) : <EOL> public_url = self [ '<STR_LIT>' ] <EOL> if public_url : <EOL> return public_url <EOL> return DepotManager . get_middleware ( ) . url_for ( self [ '<STR_LIT>' ] ) </s>
|
<s> """<STR_LIT>""" <EOL> from sqlalchemy import Column <EOL> from sqlalchemy . types import Integer , Unicode <EOL> from depot . fields . sqlalchemy import UploadedFileField <EOL> from depotexample . model import DeclarativeBase , metadata , DBSession <EOL> class UploadedImage ( DeclarativeBase ) : <EOL> __tablename__ = '<STR_LIT>' <EOL> uid = Column ( Integer , primary_key = True ) <EOL> title = Column ( Unicode ( <NUM_LIT:255> ) , nullable = False ) <EOL> file = Column ( UploadedFileField ( ) ) </s>
|
<s> from sample_app import app <EOL> app . html = u"<STR_LIT>" <EOL> app . template = ( "<STR_LIT>" , { "<STR_LIT>" : "<STR_LIT:value>" } ) <EOL> app . evaluate_javascript ( "<STR_LIT>" ) </s>
|
<s> from __future__ import absolute_import <EOL> from . role import RoleType , clone , instance , adapter </s>
|
<s> from os . path import join , abspath , dirname <EOL> from mailtools import SMTPMailer , ThreadedMailer <EOL> from jinja2 import Environment , FileSystemLoader <EOL> from tornado import escape <EOL> from amonone . mail . models import email_model <EOL> from amonone . utils . dates import dateformat_local <EOL> def send_mail ( recepients = None , subject = None , template = None , template_data = None ) : <EOL> connection_details = email_model . get_email_details ( ) <EOL> port = int ( connection_details [ '<STR_LIT:port>' ] ) <EOL> security = connection_details [ '<STR_LIT>' ] if connection_details [ '<STR_LIT>' ] != '<STR_LIT:None>' else None <EOL> mailer = ThreadedMailer ( SMTPMailer ( connection_details [ '<STR_LIT:address>' ] , port , <EOL> username = connection_details [ '<STR_LIT:username>' ] , <EOL> password = connection_details [ '<STR_LIT:password>' ] , <EOL> transport_args = { '<STR_LIT>' : security } , <EOL> log_file = '<STR_LIT>' , <EOL> log_messages = False ) ) <EOL> EMAIL_ROOT = abspath ( dirname ( __file__ ) ) <EOL> TEMPLATES_DIR = join ( EMAIL_ROOT , '<STR_LIT>' ) <EOL> env = Environment ( loader = FileSystemLoader ( TEMPLATES_DIR ) ) <EOL> env . filters [ '<STR_LIT>' ] = dateformat_local <EOL> template_file = env . get_template ( "<STR_LIT>" . format ( template ) ) <EOL> rendered_template = template_file . render ( template_data = template_data ) <EOL> message = escape . to_unicode ( rendered_template ) <EOL> subject = escape . to_unicode ( subject ) <EOL> email_recepients = [ x [ '<STR_LIT:email>' ] for x in recepients ] <EOL> try : <EOL> mailer . send_html ( connection_details [ '<STR_LIT>' ] , email_recepients , subject , message ) <EOL> except Exception , e : <EOL> print e <EOL> raise e </s>
|
<s> from amonone . web . apps . core . baseview import BaseView <EOL> from tornado . web import authenticated <EOL> from datetime import timedelta <EOL> from amonone . web . apps . core . models import server_model <EOL> from amonone . web . apps . processes . models import process_model <EOL> from amonone . utils . dates import ( <EOL> utc_now_to_localtime , <EOL> datestring_to_utc_datetime , <EOL> utc_unixtime_to_localtime , <EOL> localtime_utc_timedelta , <EOL> datetime_to_unixtime <EOL> ) <EOL> class ProcessesView ( BaseView ) : <EOL> def initialize ( self ) : <EOL> self . current_page = '<STR_LIT>' <EOL> super ( ProcessesView , self ) . initialize ( ) <EOL> @ authenticated <EOL> def get ( self ) : <EOL> date_from = self . get_argument ( '<STR_LIT>' , None ) <EOL> date_to = self . get_argument ( '<STR_LIT>' , None ) <EOL> daterange = self . get_argument ( '<STR_LIT>' , None ) <EOL> processes = self . get_arguments ( '<STR_LIT>' , None ) <EOL> day = timedelta ( hours = <NUM_LIT> ) <EOL> default_to = self . now <EOL> default_from = default_to - day <EOL> if date_from : <EOL> date_from = datestring_to_utc_datetime ( date_from ) <EOL> else : <EOL> date_from = default_from <EOL> if date_to : <EOL> date_to = datestring_to_utc_datetime ( date_to ) <EOL> else : <EOL> date_to = default_to <EOL> date_from = datetime_to_unixtime ( date_from ) <EOL> date_to = datetime_to_unixtime ( date_to ) <EOL> default_from = datetime_to_unixtime ( default_from ) <EOL> default_to = datetime_to_unixtime ( default_to ) <EOL> process_data = process_model . get_process_data ( processes , date_from , date_to ) <EOL> date_from = utc_unixtime_to_localtime ( date_from ) <EOL> date_to = utc_unixtime_to_localtime ( date_to ) <EOL> default_from = utc_unixtime_to_localtime ( default_from ) <EOL> default_to = utc_unixtime_to_localtime ( default_to ) <EOL> zone_difference = localtime_utc_timedelta ( ) <EOL> max_date = utc_now_to_localtime ( ) <EOL> server = server_model . get_one ( ) <EOL> self . render ( '<STR_LIT>' , <EOL> current_page = self . current_page , <EOL> processes = processes , <EOL> process_data = process_data , <EOL> date_from = date_from , <EOL> date_to = date_to , <EOL> default_from = default_from , <EOL> default_to = default_to , <EOL> zone_difference = zone_difference , <EOL> max_date = max_date , <EOL> daterange = daterange , <EOL> server = server <EOL> ) </s>
|
<s> from cherrypy import log <EOL> from braubuddy . envcontroller import DeviceError <EOL> from braubuddy . envcontroller import IEnvController <EOL> from braubuddy . envcontroller import Tosr0xEnvController <EOL> from braubuddy . envcontroller import DummyEnvController <EOL> class AutoEnvController ( IEnvController ) : <EOL> """<STR_LIT>""" <EOL> def __new__ ( self ) : <EOL> """<STR_LIT>""" <EOL> log ( '<STR_LIT>' ) <EOL> try : <EOL> envcontroller = Tosr0xEnvController ( ) <EOL> log ( '<STR_LIT>' ) <EOL> return envcontroller <EOL> except DeviceError : <EOL> log ( '<STR_LIT>' ) <EOL> log . error ( <EOL> '<STR_LIT>' <EOL> '<STR_LIT>' ) <EOL> return ( DummyEnvController ( ) ) </s>
|
<s> """<STR_LIT>""" <EOL> import os <EOL> import tempfile <EOL> import shutil <EOL> from datetime import datetime , timedelta <EOL> import xdg <EOL> from mock import patch , MagicMock <EOL> from braubuddy . tests import BraubuddyTestCase <EOL> from braubuddy . output import OutputError <EOL> from braubuddy . output import twitterapi <EOL> class TwitterAPIOutputAuth ( BraubuddyTestCase ) : <EOL> @ patch ( '<STR_LIT>' ) <EOL> def test_create_get_credentials_ ( self , mk_get_create_creds ) : <EOL> """<STR_LIT>""" <EOL> creds_file = os . path . join ( <EOL> os . path . join ( xdg . BaseDirectory . xdg_config_home , twitterapi . APP ) , <EOL> twitterapi . CREDS_FILE ) <EOL> tapi = twitterapi . TwitterAPIOutput ( ) <EOL> mk_get_create_creds . assert_called_once_with ( creds_file ) <EOL> @ patch ( '<STR_LIT>' ) <EOL> def test_auth_with_creds_file ( self , mk_OAuth ) : <EOL> """<STR_LIT>""" <EOL> fake_token = '<STR_LIT>' <EOL> fake_secret = '<STR_LIT>' <EOL> fake_creds_file = tempfile . mkstemp ( ) <EOL> os . write ( <EOL> fake_creds_file [ <NUM_LIT:0> ] , '<STR_LIT>' . format ( fake_token , fake_secret ) ) <EOL> mk_creds = fake_creds_file [ <NUM_LIT:1> ] <EOL> with patch ( '<STR_LIT>' , new = mk_creds ) : <EOL> test_output = twitterapi . TwitterAPIOutput ( ) <EOL> mk_OAuth . assert_called_once_with ( <EOL> fake_token , <EOL> fake_secret , <EOL> twitterapi . TCK , <EOL> twitterapi . TCS ) <EOL> os . close ( fake_creds_file [ <NUM_LIT:0> ] ) <EOL> os . remove ( fake_creds_file [ <NUM_LIT:1> ] ) <EOL> @ patch ( '<STR_LIT>' ) <EOL> def test_auth_without_creds_file ( self , mk_twitter ) : <EOL> """<STR_LIT>""" <EOL> fake_token = '<STR_LIT>' <EOL> fake_secret = '<STR_LIT>' <EOL> fake_creds_dir = tempfile . mkdtemp ( ) <EOL> fake_creds_file = os . path . join ( <EOL> fake_creds_dir , twitterapi . CREDS_FILENAME ) <EOL> mk_twitter . read_token_file . return_value = ( fake_token , fake_secret ) <EOL> with patch ( '<STR_LIT>' , <EOL> new = fake_creds_file ) : <EOL> test_output = twitterapi . TwitterAPIOutput ( ) <EOL> mk_twitter . oauth_dance . assert_called_once_with ( <EOL> twitterapi . APP , <EOL> twitterapi . TCK , <EOL> twitterapi . TCS , <EOL> fake_creds_file ) <EOL> shutil . rmtree ( fake_creds_dir ) <EOL> class TwitterAPIOutputPost ( BraubuddyTestCase ) : <EOL> @ patch ( '<STR_LIT>' ) <EOL> def setUp ( self , mk_OAuth ) : <EOL> fake_token = '<STR_LIT>' <EOL> fake_secret = '<STR_LIT>' <EOL> fake_creds_file = tempfile . mkstemp ( ) <EOL> os . write ( <EOL> fake_creds_file [ <NUM_LIT:0> ] , '<STR_LIT>' . format ( fake_token , fake_secret ) ) <EOL> mk_creds = fake_creds_file [ <NUM_LIT:1> ] <EOL> with patch ( '<STR_LIT>' , new = mk_creds ) : <EOL> self . test_output = twitterapi . TwitterAPIOutput ( ) <EOL> self . test_output . _api = MagicMock ( ) <EOL> os . close ( fake_creds_file [ <NUM_LIT:0> ] ) <EOL> os . remove ( fake_creds_file [ <NUM_LIT:1> ] ) <EOL> def test_post_tweet_unsuccessful ( self ) : <EOL> """<STR_LIT>""" <EOL> self . test_output . _last_published = datetime . now ( ) - timedelta ( <EOL> seconds = ( self . test_output . _frequency + <NUM_LIT:1> ) ) <EOL> self . test_output . _api . statuses . update . side_effect = Exception ( <EOL> '<STR_LIT>' ) <EOL> with self . assertRaises ( OutputError ) : <EOL> self . test_output . publish_status ( <NUM_LIT:20> , <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT:100> ) <EOL> def test_post_tweet_successful ( self ) : <EOL> """<STR_LIT>""" <EOL> self . test_output . _last_published = datetime . now ( ) - timedelta ( <EOL> seconds = ( self . test_output . _frequency + <NUM_LIT:1> ) ) <EOL> units = self . test_output . units <EOL> temp = <NUM_LIT> <EOL> target = <NUM_LIT:20> <EOL> heat = <NUM_LIT:0> <EOL> cool = <NUM_LIT:100> <EOL> expected_message = self . test_output . _message . format ( <EOL> units = units , temp = temp , target = target , heat = heat , cool = cool ) <EOL> self . test_output . publish_status ( <NUM_LIT:20> , <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT:100> ) <EOL> self . test_output . _api . statuses . update . assert_called_once_with ( <EOL> status = expected_message ) <EOL> def test_post_skipped_within_interval ( self ) : <EOL> """<STR_LIT>""" <EOL> self . test_output . _last_published = datetime . now ( ) - timedelta ( <EOL> seconds = ( self . test_output . _frequency - <NUM_LIT:1> ) ) <EOL> self . test_output . publish_status ( <NUM_LIT:20> , <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT:100> ) <EOL> self . assertFalse ( <EOL> self . test_output . _api . statuses . update . called ) </s>
|
<s> import argparse <EOL> import copy <EOL> import datetime <EOL> import errno <EOL> import json <EOL> import logging <EOL> import os <EOL> import os . path <EOL> import Queue <EOL> import socket <EOL> import time <EOL> from watchdog import events , observers <EOL> from cassback import cassandra , dt_util , file_util <EOL> from cassback . subcommands import subcommands <EOL> class BackupSubCommand ( subcommands . SubCommand ) : <EOL> log = logging . getLogger ( "<STR_LIT>" % ( __name__ , "<STR_LIT>" ) ) <EOL> command_name = "<STR_LIT>" <EOL> command_help = "<STR_LIT>" <EOL> command_description = "<STR_LIT>" <EOL> def __init__ ( self , args ) : <EOL> self . args = args <EOL> return <EOL> @ classmethod <EOL> def add_sub_parser ( cls , sub_parsers ) : <EOL> """<STR_LIT:U+0020>""" <EOL> sub_parser = super ( BackupSubCommand , cls ) . add_sub_parser ( sub_parsers ) <EOL> sub_parser . add_argument ( "<STR_LIT>" , type = int , default = <NUM_LIT:4> , <EOL> help = '<STR_LIT>' ) <EOL> sub_parser . add_argument ( "<STR_LIT>" , type = int , default = <NUM_LIT:5> , <EOL> dest = "<STR_LIT>" , <EOL> help = '<STR_LIT>' ) <EOL> sub_parser . add_argument ( '<STR_LIT>' , action = '<STR_LIT:store_true>' , <EOL> default = False , <EOL> help = '<STR_LIT>' ) <EOL> sub_parser . add_argument ( '<STR_LIT>' , <EOL> dest = '<STR_LIT>' , nargs = "<STR_LIT:*>" , <EOL> help = "<STR_LIT>" ) <EOL> sub_parser . add_argument ( '<STR_LIT>' , default = False , <EOL> dest = '<STR_LIT>' , action = "<STR_LIT:store_true>" , <EOL> help = "<STR_LIT>" ) <EOL> sub_parser . add_argument ( '<STR_LIT>' , default = False , <EOL> dest = '<STR_LIT>' , action = "<STR_LIT:store_true>" , <EOL> help = "<STR_LIT>" ) <EOL> sub_parser . add_argument ( '<STR_LIT>' , default = False , <EOL> dest = '<STR_LIT>' , action = "<STR_LIT:store_true>" , <EOL> help = "<STR_LIT>" ) <EOL> sub_parser . add_argument ( "<STR_LIT>" , <EOL> default = "<STR_LIT>" , <EOL> help = "<STR_LIT>" ) <EOL> sub_parser . add_argument ( "<STR_LIT>" , <EOL> default = socket . getfqdn ( ) , <EOL> help = "<STR_LIT>" ) <EOL> return sub_parser <EOL> def __call__ ( self ) : <EOL> self . log . info ( "<STR_LIT>" , self . command_name ) <EOL> file_q = Queue . Queue ( ) <EOL> watcher = WatchdogWatcher ( self . args . cassandra_data_dir , file_q , <EOL> self . args . ignore_existing , self . args . ignore_changes , <EOL> self . args . exclude_keyspaces , self . args . include_system_keyspace ) <EOL> self . workers = [ <EOL> self . _create_worker_thread ( i , file_q ) <EOL> for i in range ( self . args . threads ) <EOL> ] <EOL> for worker in self . workers : <EOL> worker . start ( ) <EOL> if self . args . report_interval_secs > <NUM_LIT:0> : <EOL> reporter = SnapReporterThread ( file_q , <EOL> self . args . report_interval_secs ) <EOL> reporter . start ( ) <EOL> else : <EOL> self . log . info ( "<STR_LIT>" ) <EOL> watcher . start ( ) <EOL> self . log . info ( "<STR_LIT>" , self . command_name ) <EOL> return ( <NUM_LIT:0> , "<STR_LIT>" ) <EOL> def _create_worker_thread ( self , i , file_queue ) : <EOL> """<STR_LIT>""" <EOL> return SnapWorkerThread ( i , file_queue , copy . copy ( self . args ) ) <EOL> class SnapWorkerThread ( subcommands . SubCommandWorkerThread ) : <EOL> log = logging . getLogger ( "<STR_LIT>" % ( __name__ , "<STR_LIT>" ) ) <EOL> def __init__ ( self , thread_id , file_q , args ) : <EOL> super ( SnapWorkerThread , self ) . __init__ ( "<STR_LIT>" , thread_id ) <EOL> self . file_q = file_q <EOL> self . args = args <EOL> def _do_run ( self ) : <EOL> """<STR_LIT>""" <EOL> endpoint = self . _endpoint ( self . args ) <EOL> while True : <EOL> backup_msg = self . file_q . get ( ) <EOL> if backup_msg . file_ref : <EOL> with backup_msg . file_ref : <EOL> self . _run_internal ( endpoint , backup_msg . ks_manifest , <EOL> backup_msg . component ) <EOL> else : <EOL> self . _run_internal ( endpoint , backup_msg . ks_manifest , <EOL> backup_msg . component ) <EOL> self . file_q . task_done ( ) <EOL> return <EOL> def _run_internal ( self , endpoint , ks_manifest , component ) : <EOL> """<STR_LIT>""" <EOL> self . log . info ( "<STR_LIT>" , component ) <EOL> if component . is_deleted : <EOL> endpoint . backup_keyspace ( ks_manifest ) <EOL> self . log . info ( "<STR_LIT>" , <EOL> ks_manifest . backup_path , component ) <EOL> return <EOL> backup_file = cassandra . BackupFile ( component . file_path , <EOL> host = self . args . host , component = component ) <EOL> if endpoint . exists ( backup_file . backup_path ) : <EOL> if endpoint . validate_checksum ( backup_file . backup_path , <EOL> backup_file . md5 ) : <EOL> self . log . info ( "<STR_LIT>" "<STR_LIT>" , backup_file ) <EOL> else : <EOL> self . log . warn ( "<STR_LIT>" "<STR_LIT>" , backup_file ) <EOL> return False <EOL> uploaded_path = endpoint . backup_file ( backup_file ) <EOL> endpoint . backup_keyspace ( ks_manifest ) <EOL> self . log . info ( "<STR_LIT>" , backup_file . file_path , <EOL> uploaded_path ) <EOL> return True <EOL> class SnapReporterThread ( subcommands . SubCommandWorkerThread ) : <EOL> """<STR_LIT>""" <EOL> log = logging . getLogger ( "<STR_LIT>" % ( __name__ , "<STR_LIT>" ) ) <EOL> def __init__ ( self , file_q , interval ) : <EOL> super ( SnapReporterThread , self ) . __init__ ( "<STR_LIT>" , <NUM_LIT:0> ) <EOL> self . interval = interval <EOL> self . file_q = file_q <EOL> def _do_run ( self ) : <EOL> last_size = <NUM_LIT:0> <EOL> while True : <EOL> size = self . file_q . qsize ( ) <EOL> if size > <NUM_LIT:0> or ( size != last_size ) : <EOL> self . log . info ( "<STR_LIT>" "<STR_LIT>" , size ) <EOL> last_size = size <EOL> time . sleep ( self . interval ) <EOL> return <EOL> class WatchdogWatcher ( events . FileSystemEventHandler ) : <EOL> """<STR_LIT>""" <EOL> log = logging . getLogger ( "<STR_LIT>" % ( __name__ , "<STR_LIT>" ) ) <EOL> def __init__ ( self , data_dir , file_queue , ignore_existing , ignore_changes , <EOL> exclude_keyspaces , include_system_keyspace ) : <EOL> self . data_dir = data_dir <EOL> self . file_queue = file_queue <EOL> self . ignore_existing = ignore_existing <EOL> self . ignore_changes = ignore_changes <EOL> self . exclude_keyspaces = frozenset ( exclude_keyspaces or [ ] ) <EOL> self . include_system_keyspace = include_system_keyspace <EOL> self . keyspaces = { } <EOL> def start ( self ) : <EOL> self . log . info ( "<STR_LIT>" ) <EOL> for root , dirs , files in os . walk ( self . data_dir ) : <EOL> for filename in files : <EOL> self . _maybe_queue_file ( os . path . join ( root , filename ) , <EOL> enqueue = not ( self . ignore_existing ) ) <EOL> if self . ignore_changes : <EOL> return <EOL> observer = observers . Observer ( ) <EOL> observer . schedule ( self , path = self . data_dir , recursive = True ) <EOL> self . log . info ( "<STR_LIT>" , self . data_dir ) <EOL> observer . start ( ) <EOL> try : <EOL> while True : <EOL> time . sleep ( <NUM_LIT:1> ) <EOL> except KeyboardInterrupt : <EOL> observer . stop ( ) <EOL> observer . join ( timeout = <NUM_LIT:30> ) <EOL> if observer . isAlive ( ) : <EOL> self . log . error ( "<STR_LIT>" ) <EOL> os . kill ( os . getpid ( ) , signal . SIGKILL ) <EOL> return <EOL> def _get_ks_manifest ( self , keyspace ) : <EOL> try : <EOL> ks_manifest = self . keyspaces [ keyspace ] <EOL> except ( KeyError ) : <EOL> ks_manifest = cassandra . KeyspaceBackup ( keyspace ) <EOL> self . keyspaces [ keyspace ] = ks_manifest <EOL> return ks_manifest <EOL> def _maybe_queue_file ( self , file_path , enqueue = True ) : <EOL> with file_util . FileReferenceContext ( file_path ) as file_ref : <EOL> if file_ref is None : <EOL> self . log . info ( "<STR_LIT>" , file_path ) <EOL> return False <EOL> if cassandra . is_snapshot_path ( file_ref . stable_path ) : <EOL> self . log . info ( "<STR_LIT>" , file_ref . stable_path ) <EOL> return False <EOL> try : <EOL> component = cassandra . SSTableComponent ( file_ref . stable_path ) <EOL> except ( ValueError ) : <EOL> self . log . info ( "<STR_LIT>" , <EOL> file_ref . stable_path ) <EOL> return False <EOL> if component . temporary : <EOL> self . log . info ( "<STR_LIT>" , file_ref . stable_path ) <EOL> return False <EOL> if component . keyspace in self . exclude_keyspaces : <EOL> self . log . info ( "<STR_LIT>" "<STR_LIT>" , file_ref . stable_path , component . keyspace ) <EOL> return False <EOL> if ( component . keyspace . lower ( ) == "<STR_LIT>" ) and ( <EOL> not self . include_system_keyspace ) : <EOL> self . log . info ( "<STR_LIT>" , <EOL> file_ref . stable_path ) <EOL> return False <EOL> ks_manifest = self . _get_ks_manifest ( component . keyspace ) <EOL> ks_manifest . add_component ( component ) <EOL> if enqueue : <EOL> self . log . info ( "<STR_LIT>" , file_ref . stable_path ) <EOL> self . file_queue . put ( <EOL> BackupMessage ( file_ref , ks_manifest . snapshot ( ) , component ) ) <EOL> file_ref . ignore_next_exit = True <EOL> return True <EOL> def on_created ( self , event ) : <EOL> self . _maybe_queue_file ( event . src_path ) <EOL> return <EOL> def on_moved ( self , event ) : <EOL> self . _maybe_queue_file ( event . dest_path ) <EOL> return <EOL> def on_deleted ( self , event ) : <EOL> file_path = event . src_path <EOL> if cassandra . is_snapshot_path ( file_path ) : <EOL> self . log . info ( "<STR_LIT>" , file_path ) <EOL> return <EOL> try : <EOL> component = cassandra . SSTableComponent ( file_path , is_deleted = True ) <EOL> except ( ValueError ) : <EOL> self . log . info ( "<STR_LIT>" , file_path ) <EOL> return <EOL> if component . component != cassandra . Components . DATA : <EOL> self . log . info ( "<STR_LIT>" , <EOL> cassandra . Components . DATA , file_path ) <EOL> return <EOL> ks_manifest = self . _get_ks_manifest ( component . keyspace ) <EOL> ks_manifest . remove_sstable ( component ) <EOL> self . log . info ( "<STR_LIT>" , file_path ) <EOL> self . file_queue . put ( <EOL> BackupMessage ( None , ks_manifest . snapshot ( ) , component ) ) <EOL> return <EOL> class BackupMessage ( object ) : <EOL> def __init__ ( self , file_ref , ks_manifest , component ) : <EOL> self . file_ref = file_ref <EOL> self . ks_manifest = ks_manifest <EOL> self . component = component </s>
|
<s> import os <EOL> import sys <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> os . environ . setdefault ( "<STR_LIT>" , "<STR_LIT>" ) <EOL> from django . core . management import execute_from_command_line <EOL> execute_from_command_line ( sys . argv ) </s>
|
<s> """<STR_LIT>""" <EOL> from weakref import ref <EOL> from contextlib import contextmanager <EOL> __all__ = [ "<STR_LIT>" ] <EOL> class _localimpl : <EOL> """<STR_LIT>""" <EOL> __slots__ = '<STR_LIT:key>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' <EOL> def __init__ ( self ) : <EOL> self . key = '<STR_LIT>' + str ( id ( self ) ) <EOL> self . dicts = { } <EOL> def get_dict ( self ) : <EOL> """<STR_LIT>""" <EOL> thread = current_thread ( ) <EOL> return self . dicts [ id ( thread ) ] [ <NUM_LIT:1> ] <EOL> def create_dict ( self ) : <EOL> """<STR_LIT>""" <EOL> localdict = { } <EOL> key = self . key <EOL> thread = current_thread ( ) <EOL> idt = id ( thread ) <EOL> def local_deleted ( _ , key = key ) : <EOL> thread = wrthread ( ) <EOL> if thread is not None : <EOL> del thread . __dict__ [ key ] <EOL> def thread_deleted ( _ , idt = idt ) : <EOL> local = wrlocal ( ) <EOL> if local is not None : <EOL> dct = local . dicts . pop ( idt ) <EOL> wrlocal = ref ( self , local_deleted ) <EOL> wrthread = ref ( thread , thread_deleted ) <EOL> thread . __dict__ [ key ] = wrlocal <EOL> self . dicts [ idt ] = wrthread , localdict <EOL> return localdict <EOL> @ contextmanager <EOL> def _patch ( self ) : <EOL> impl = object . __getattribute__ ( self , '<STR_LIT>' ) <EOL> try : <EOL> dct = impl . get_dict ( ) <EOL> except KeyError : <EOL> dct = impl . create_dict ( ) <EOL> args , kw = impl . localargs <EOL> self . __init__ ( * args , ** kw ) <EOL> with impl . locallock : <EOL> object . __setattr__ ( self , '<STR_LIT>' , dct ) <EOL> yield <EOL> class local : <EOL> __slots__ = '<STR_LIT>' , '<STR_LIT>' <EOL> def __new__ ( cls , * args , ** kw ) : <EOL> if ( args or kw ) and ( cls . __init__ is object . __init__ ) : <EOL> raise TypeError ( "<STR_LIT>" ) <EOL> self = object . __new__ ( cls ) <EOL> impl = _localimpl ( ) <EOL> impl . localargs = ( args , kw ) <EOL> impl . locallock = RLock ( ) <EOL> object . __setattr__ ( self , '<STR_LIT>' , impl ) <EOL> impl . create_dict ( ) <EOL> return self <EOL> def __getattribute__ ( self , name ) : <EOL> with _patch ( self ) : <EOL> return object . __getattribute__ ( self , name ) <EOL> def __setattr__ ( self , name , value ) : <EOL> if name == '<STR_LIT>' : <EOL> raise AttributeError ( <EOL> "<STR_LIT>" <EOL> % self . __class__ . __name__ ) <EOL> with _patch ( self ) : <EOL> return object . __setattr__ ( self , name , value ) <EOL> def __delattr__ ( self , name ) : <EOL> if name == '<STR_LIT>' : <EOL> raise AttributeError ( <EOL> "<STR_LIT>" <EOL> % self . __class__ . __name__ ) <EOL> with _patch ( self ) : <EOL> return object . __delattr__ ( self , name ) <EOL> from threading import current_thread , RLock </s>
|
<s> """<STR_LIT>""" <EOL> import types <EOL> import weakref <EOL> from copyreg import dispatch_table <EOL> import builtins <EOL> class Error ( Exception ) : <EOL> pass <EOL> error = Error <EOL> PyStringMap = None <EOL> __all__ = [ "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] <EOL> def copy ( x ) : <EOL> """<STR_LIT>""" <EOL> cls = type ( x ) <EOL> copier = _copy_dispatch . get ( cls ) <EOL> if copier : <EOL> return copier ( x ) <EOL> copier = getattr ( cls , "<STR_LIT>" , None ) <EOL> if copier : <EOL> return copier ( x ) <EOL> reductor = dispatch_table . get ( cls ) <EOL> if reductor : <EOL> rv = reductor ( x ) <EOL> else : <EOL> reductor = getattr ( x , "<STR_LIT>" , None ) <EOL> if reductor : <EOL> rv = reductor ( <NUM_LIT:2> ) <EOL> else : <EOL> reductor = getattr ( x , "<STR_LIT>" , None ) <EOL> if reductor : <EOL> rv = reductor ( ) <EOL> else : <EOL> raise Error ( "<STR_LIT>" % cls ) <EOL> return _reconstruct ( x , rv , <NUM_LIT:0> ) <EOL> _copy_dispatch = d = { } <EOL> def _copy_immutable ( x ) : <EOL> return x <EOL> for t in ( type ( None ) , int , float , bool , str , tuple , <EOL> frozenset , type , range , <EOL> types . BuiltinFunctionType , type ( Ellipsis ) , <EOL> types . FunctionType , weakref . ref ) : <EOL> d [ t ] = _copy_immutable <EOL> t = getattr ( types , "<STR_LIT>" , None ) <EOL> if t is not None : <EOL> d [ t ] = _copy_immutable <EOL> for name in ( "<STR_LIT>" , "<STR_LIT>" ) : <EOL> t = getattr ( builtins , name , None ) <EOL> if t is not None : <EOL> d [ t ] = _copy_immutable <EOL> def _copy_with_constructor ( x ) : <EOL> return type ( x ) ( x ) <EOL> for t in ( list , dict , set ) : <EOL> d [ t ] = _copy_with_constructor <EOL> def _copy_with_copy_method ( x ) : <EOL> return x . copy ( ) <EOL> if PyStringMap is not None : <EOL> d [ PyStringMap ] = _copy_with_copy_method <EOL> del d <EOL> def deepcopy ( x , memo = None , _nil = [ ] ) : <EOL> """<STR_LIT>""" <EOL> if memo is None : <EOL> memo = { } <EOL> d = id ( x ) <EOL> y = memo . get ( d , _nil ) <EOL> if y is not _nil : <EOL> return y <EOL> cls = type ( x ) <EOL> copier = _deepcopy_dispatch . get ( cls ) <EOL> if copier : <EOL> y = copier ( x , memo ) <EOL> else : <EOL> try : <EOL> issc = issubclass ( cls , type ) <EOL> except TypeError : <EOL> issc = <NUM_LIT:0> <EOL> if issc : <EOL> y = _deepcopy_atomic ( x , memo ) <EOL> else : <EOL> copier = getattr ( x , "<STR_LIT>" , None ) <EOL> if copier : <EOL> y = copier ( memo ) <EOL> else : <EOL> reductor = dispatch_table . get ( cls ) <EOL> if reductor : <EOL> rv = reductor ( x ) <EOL> else : <EOL> reductor = getattr ( x , "<STR_LIT>" , None ) <EOL> if reductor : <EOL> rv = reductor ( <NUM_LIT:2> ) <EOL> else : <EOL> reductor = getattr ( x , "<STR_LIT>" , None ) <EOL> if reductor : <EOL> rv = reductor ( ) <EOL> else : <EOL> raise Error ( <EOL> "<STR_LIT>" % cls ) <EOL> y = _reconstruct ( x , rv , <NUM_LIT:1> , memo ) <EOL> if y is not x : <EOL> memo [ d ] = y <EOL> _keep_alive ( x , memo ) <EOL> return y <EOL> _deepcopy_dispatch = d = { } <EOL> def _deepcopy_atomic ( x , memo ) : <EOL> return x <EOL> d [ type ( None ) ] = _deepcopy_atomic <EOL> d [ type ( Ellipsis ) ] = _deepcopy_atomic <EOL> d [ int ] = _deepcopy_atomic <EOL> d [ float ] = _deepcopy_atomic <EOL> d [ bool ] = _deepcopy_atomic <EOL> try : <EOL> d [ complex ] = _deepcopy_atomic <EOL> except NameError : <EOL> pass <EOL> d [ bytes ] = _deepcopy_atomic <EOL> d [ str ] = _deepcopy_atomic <EOL> try : <EOL> d [ types . CodeType ] = _deepcopy_atomic <EOL> except AttributeError : <EOL> pass <EOL> d [ type ] = _deepcopy_atomic <EOL> d [ range ] = _deepcopy_atomic <EOL> d [ types . BuiltinFunctionType ] = _deepcopy_atomic <EOL> d [ types . FunctionType ] = _deepcopy_atomic <EOL> d [ weakref . ref ] = _deepcopy_atomic <EOL> def _deepcopy_list ( x , memo ) : <EOL> y = [ ] <EOL> memo [ id ( x ) ] = y <EOL> for a in x : <EOL> y . append ( deepcopy ( a , memo ) ) <EOL> return y <EOL> d [ list ] = _deepcopy_list <EOL> def _deepcopy_tuple ( x , memo ) : <EOL> y = [ ] <EOL> for a in x : <EOL> y . append ( deepcopy ( a , memo ) ) <EOL> try : <EOL> return memo [ id ( x ) ] <EOL> except KeyError : <EOL> pass <EOL> for i in range ( len ( x ) ) : <EOL> if x [ i ] is not y [ i ] : <EOL> y = tuple ( y ) <EOL> break <EOL> else : <EOL> y = x <EOL> return y <EOL> d [ tuple ] = _deepcopy_tuple <EOL> def _deepcopy_dict ( x , memo ) : <EOL> y = { } <EOL> memo [ id ( x ) ] = y <EOL> for key , value in x . items ( ) : <EOL> y [ deepcopy ( key , memo ) ] = deepcopy ( value , memo ) <EOL> return y <EOL> d [ dict ] = _deepcopy_dict <EOL> if PyStringMap is not None : <EOL> d [ PyStringMap ] = _deepcopy_dict <EOL> def _deepcopy_method ( x , memo ) : <EOL> return type ( x ) ( x . __func__ , deepcopy ( x . __self__ , memo ) ) <EOL> _deepcopy_dispatch [ types . MethodType ] = _deepcopy_method <EOL> def _keep_alive ( x , memo ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> memo [ id ( memo ) ] . append ( x ) <EOL> except KeyError : <EOL> memo [ id ( memo ) ] = [ x ] <EOL> def _reconstruct ( x , info , deep , memo = None ) : <EOL> if isinstance ( info , str ) : <EOL> return x <EOL> assert isinstance ( info , tuple ) <EOL> if memo is None : <EOL> memo = { } <EOL> n = len ( info ) <EOL> assert n in ( <NUM_LIT:2> , <NUM_LIT:3> , <NUM_LIT:4> , <NUM_LIT:5> ) <EOL> callable , args = info [ : <NUM_LIT:2> ] <EOL> if n > <NUM_LIT:2> : <EOL> state = info [ <NUM_LIT:2> ] <EOL> else : <EOL> state = { } <EOL> if n > <NUM_LIT:3> : <EOL> listiter = info [ <NUM_LIT:3> ] <EOL> else : <EOL> listiter = None <EOL> if n > <NUM_LIT:4> : <EOL> dictiter = info [ <NUM_LIT:4> ] <EOL> else : <EOL> dictiter = None <EOL> if deep : <EOL> args = deepcopy ( args , memo ) <EOL> y = callable ( * args ) <EOL> memo [ id ( x ) ] = y <EOL> if state : <EOL> if deep : <EOL> state = deepcopy ( state , memo ) <EOL> if hasattr ( y , '<STR_LIT>' ) : <EOL> y . __setstate__ ( state ) <EOL> else : <EOL> if isinstance ( state , tuple ) and len ( state ) == <NUM_LIT:2> : <EOL> state , slotstate = state <EOL> else : <EOL> slotstate = None <EOL> if state is not None : <EOL> y . __dict__ . update ( state ) <EOL> if slotstate is not None : <EOL> for key , value in slotstate . items ( ) : <EOL> setattr ( y , key , value ) <EOL> if listiter is not None : <EOL> for item in listiter : <EOL> if deep : <EOL> item = deepcopy ( item , memo ) <EOL> y . append ( item ) <EOL> if dictiter is not None : <EOL> for key , value in dictiter : <EOL> if deep : <EOL> key = deepcopy ( key , memo ) <EOL> value = deepcopy ( value , memo ) <EOL> y [ key ] = value <EOL> return y <EOL> del d <EOL> del types <EOL> class _EmptyClass : <EOL> pass </s>
|
<s> """<STR_LIT>""" <EOL> import os <EOL> import stat <EOL> __all__ = [ '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' , <EOL> '<STR_LIT>' , '<STR_LIT>' , '<STR_LIT>' ] <EOL> def exists ( path ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> os . stat ( path ) <EOL> except os . error : <EOL> return False <EOL> return True <EOL> def isfile ( path ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> st = os . stat ( path ) <EOL> except os . error : <EOL> return False <EOL> return stat . S_ISREG ( st . st_mode ) <EOL> def isdir ( s ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> st = os . stat ( s ) <EOL> except os . error : <EOL> return False <EOL> return stat . S_ISDIR ( st . st_mode ) <EOL> def getsize ( filename ) : <EOL> """<STR_LIT>""" <EOL> return os . stat ( filename ) . st_size <EOL> def getmtime ( filename ) : <EOL> """<STR_LIT>""" <EOL> return os . stat ( filename ) . st_mtime <EOL> def getatime ( filename ) : <EOL> """<STR_LIT>""" <EOL> return os . stat ( filename ) . st_atime <EOL> def getctime ( filename ) : <EOL> """<STR_LIT>""" <EOL> return os . stat ( filename ) . st_ctime <EOL> def commonprefix ( m ) : <EOL> "<STR_LIT>" <EOL> if not m : return '<STR_LIT>' <EOL> s1 = min ( m ) <EOL> s2 = max ( m ) <EOL> for i , c in enumerate ( s1 ) : <EOL> if c != s2 [ i ] : <EOL> return s1 [ : i ] <EOL> return s1 <EOL> def _splitext ( p , sep , altsep , extsep ) : <EOL> """<STR_LIT>""" <EOL> sepIndex = p . rfind ( sep ) <EOL> if altsep : <EOL> altsepIndex = p . rfind ( altsep ) <EOL> sepIndex = max ( sepIndex , altsepIndex ) <EOL> dotIndex = p . rfind ( extsep ) <EOL> if dotIndex > sepIndex : <EOL> filenameIndex = sepIndex + <NUM_LIT:1> <EOL> while filenameIndex < dotIndex : <EOL> if p [ filenameIndex : filenameIndex + <NUM_LIT:1> ] != extsep : <EOL> return p [ : dotIndex ] , p [ dotIndex : ] <EOL> filenameIndex += <NUM_LIT:1> <EOL> return p , p [ : <NUM_LIT:0> ] </s>
|
<s> __all__ = [ '<STR_LIT>' ] <EOL> import threading <EOL> import queue <EOL> import itertools <EOL> import collections <EOL> import time <EOL> from multiprocessing import Process , cpu_count , TimeoutError <EOL> from multiprocessing . util import Finalize , debug <EOL> RUN = <NUM_LIT:0> <EOL> CLOSE = <NUM_LIT:1> <EOL> TERMINATE = <NUM_LIT:2> <EOL> job_counter = itertools . count ( ) <EOL> def mapstar ( args ) : <EOL> return list ( map ( * args ) ) <EOL> def starmapstar ( args ) : <EOL> return list ( itertools . starmap ( args [ <NUM_LIT:0> ] , args [ <NUM_LIT:1> ] ) ) <EOL> class MaybeEncodingError ( Exception ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , exc , value ) : <EOL> self . exc = repr ( exc ) <EOL> self . value = repr ( value ) <EOL> super ( MaybeEncodingError , self ) . __init__ ( self . exc , self . value ) <EOL> def __str__ ( self ) : <EOL> return "<STR_LIT>" % ( self . value , <EOL> self . exc ) <EOL> def __repr__ ( self ) : <EOL> return "<STR_LIT>" % str ( self ) <EOL> def worker ( inqueue , outqueue , initializer = None , initargs = ( ) , maxtasks = None ) : <EOL> assert maxtasks is None or ( type ( maxtasks ) == int and maxtasks > <NUM_LIT:0> ) <EOL> put = outqueue . put <EOL> get = inqueue . get <EOL> if hasattr ( inqueue , '<STR_LIT>' ) : <EOL> inqueue . _writer . close ( ) <EOL> outqueue . _reader . close ( ) <EOL> if initializer is not None : <EOL> initializer ( * initargs ) <EOL> completed = <NUM_LIT:0> <EOL> while maxtasks is None or ( maxtasks and completed < maxtasks ) : <EOL> try : <EOL> task = get ( ) <EOL> except ( EOFError , IOError ) : <EOL> debug ( '<STR_LIT>' ) <EOL> break <EOL> if task is None : <EOL> debug ( '<STR_LIT>' ) <EOL> break <EOL> job , i , func , args , kwds = task <EOL> try : <EOL> result = ( True , func ( * args , ** kwds ) ) <EOL> except Exception as e : <EOL> result = ( False , e ) <EOL> try : <EOL> put ( ( job , i , result ) ) <EOL> except Exception as e : <EOL> wrapped = MaybeEncodingError ( e , result [ <NUM_LIT:1> ] ) <EOL> debug ( "<STR_LIT>" % ( <EOL> wrapped ) ) <EOL> put ( ( job , i , ( False , wrapped ) ) ) <EOL> completed += <NUM_LIT:1> <EOL> debug ( '<STR_LIT>' % completed ) <EOL> class Pool ( object ) : <EOL> '''<STR_LIT>''' <EOL> Process = Process <EOL> def __init__ ( self , processes = None , initializer = None , initargs = ( ) , <EOL> maxtasksperchild = None ) : <EOL> self . _setup_queues ( ) <EOL> self . _taskqueue = queue . Queue ( ) <EOL> self . _cache = { } <EOL> self . _state = RUN <EOL> self . _maxtasksperchild = maxtasksperchild <EOL> self . _initializer = initializer <EOL> self . _initargs = initargs <EOL> if processes is None : <EOL> try : <EOL> processes = cpu_count ( ) <EOL> except NotImplementedError : <EOL> processes = <NUM_LIT:1> <EOL> if processes < <NUM_LIT:1> : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if initializer is not None and not callable ( initializer ) : <EOL> raise TypeError ( '<STR_LIT>' ) <EOL> self . _processes = processes <EOL> self . _pool = [ ] <EOL> self . _repopulate_pool ( ) <EOL> self . _worker_handler = threading . Thread ( <EOL> target = Pool . _handle_workers , <EOL> args = ( self , ) <EOL> ) <EOL> self . _worker_handler . daemon = True <EOL> self . _worker_handler . _state = RUN <EOL> self . _worker_handler . start ( ) <EOL> self . _task_handler = threading . Thread ( <EOL> target = Pool . _handle_tasks , <EOL> args = ( self . _taskqueue , self . _quick_put , self . _outqueue , self . _pool ) <EOL> ) <EOL> self . _task_handler . daemon = True <EOL> self . _task_handler . _state = RUN <EOL> self . _task_handler . start ( ) <EOL> self . _result_handler = threading . Thread ( <EOL> target = Pool . _handle_results , <EOL> args = ( self . _outqueue , self . _quick_get , self . _cache ) <EOL> ) <EOL> self . _result_handler . daemon = True <EOL> self . _result_handler . _state = RUN <EOL> self . _result_handler . start ( ) <EOL> self . _terminate = Finalize ( <EOL> self , self . _terminate_pool , <EOL> args = ( self . _taskqueue , self . _inqueue , self . _outqueue , self . _pool , <EOL> self . _worker_handler , self . _task_handler , <EOL> self . _result_handler , self . _cache ) , <EOL> exitpriority = <NUM_LIT:15> <EOL> ) <EOL> def _join_exited_workers ( self ) : <EOL> """<STR_LIT>""" <EOL> cleaned = False <EOL> for i in reversed ( range ( len ( self . _pool ) ) ) : <EOL> worker = self . _pool [ i ] <EOL> if worker . exitcode is not None : <EOL> debug ( '<STR_LIT>' % i ) <EOL> worker . join ( ) <EOL> cleaned = True <EOL> del self . _pool [ i ] <EOL> return cleaned <EOL> def _repopulate_pool ( self ) : <EOL> """<STR_LIT>""" <EOL> for i in range ( self . _processes - len ( self . _pool ) ) : <EOL> w = self . Process ( target = worker , <EOL> args = ( self . _inqueue , self . _outqueue , <EOL> self . _initializer , <EOL> self . _initargs , self . _maxtasksperchild ) <EOL> ) <EOL> self . _pool . append ( w ) <EOL> w . name = w . name . replace ( '<STR_LIT>' , '<STR_LIT>' ) <EOL> w . daemon = True <EOL> w . start ( ) <EOL> debug ( '<STR_LIT>' ) <EOL> def _maintain_pool ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _join_exited_workers ( ) : <EOL> self . _repopulate_pool ( ) <EOL> def _setup_queues ( self ) : <EOL> from . queues import SimpleQueue <EOL> self . _inqueue = SimpleQueue ( ) <EOL> self . _outqueue = SimpleQueue ( ) <EOL> self . _quick_put = self . _inqueue . _writer . send <EOL> self . _quick_get = self . _outqueue . _reader . recv <EOL> def apply ( self , func , args = ( ) , kwds = { } ) : <EOL> '''<STR_LIT>''' <EOL> assert self . _state == RUN <EOL> return self . apply_async ( func , args , kwds ) . get ( ) <EOL> def map ( self , func , iterable , chunksize = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . _map_async ( func , iterable , mapstar , chunksize ) . get ( ) <EOL> def starmap ( self , func , iterable , chunksize = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . _map_async ( func , iterable , starmapstar , chunksize ) . get ( ) <EOL> def starmap_async ( self , func , iterable , chunksize = None , callback = None , <EOL> error_callback = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . _map_async ( func , iterable , starmapstar , chunksize , <EOL> callback , error_callback ) <EOL> def imap ( self , func , iterable , chunksize = <NUM_LIT:1> ) : <EOL> '''<STR_LIT>''' <EOL> if self . _state != RUN : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if chunksize == <NUM_LIT:1> : <EOL> result = IMapIterator ( self . _cache ) <EOL> self . _taskqueue . put ( ( ( ( result . _job , i , func , ( x , ) , { } ) <EOL> for i , x in enumerate ( iterable ) ) , result . _set_length ) ) <EOL> return result <EOL> else : <EOL> assert chunksize > <NUM_LIT:1> <EOL> task_batches = Pool . _get_tasks ( func , iterable , chunksize ) <EOL> result = IMapIterator ( self . _cache ) <EOL> self . _taskqueue . put ( ( ( ( result . _job , i , mapstar , ( x , ) , { } ) <EOL> for i , x in enumerate ( task_batches ) ) , result . _set_length ) ) <EOL> return ( item for chunk in result for item in chunk ) <EOL> def imap_unordered ( self , func , iterable , chunksize = <NUM_LIT:1> ) : <EOL> '''<STR_LIT>''' <EOL> if self . _state != RUN : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if chunksize == <NUM_LIT:1> : <EOL> result = IMapUnorderedIterator ( self . _cache ) <EOL> self . _taskqueue . put ( ( ( ( result . _job , i , func , ( x , ) , { } ) <EOL> for i , x in enumerate ( iterable ) ) , result . _set_length ) ) <EOL> return result <EOL> else : <EOL> assert chunksize > <NUM_LIT:1> <EOL> task_batches = Pool . _get_tasks ( func , iterable , chunksize ) <EOL> result = IMapUnorderedIterator ( self . _cache ) <EOL> self . _taskqueue . put ( ( ( ( result . _job , i , mapstar , ( x , ) , { } ) <EOL> for i , x in enumerate ( task_batches ) ) , result . _set_length ) ) <EOL> return ( item for chunk in result for item in chunk ) <EOL> def apply_async ( self , func , args = ( ) , kwds = { } , callback = None , <EOL> error_callback = None ) : <EOL> '''<STR_LIT>''' <EOL> if self . _state != RUN : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> result = ApplyResult ( self . _cache , callback , error_callback ) <EOL> self . _taskqueue . put ( ( [ ( result . _job , None , func , args , kwds ) ] , None ) ) <EOL> return result <EOL> def map_async ( self , func , iterable , chunksize = None , callback = None , <EOL> error_callback = None ) : <EOL> '''<STR_LIT>''' <EOL> return self . _map_async ( func , iterable , mapstar , chunksize , callback , <EOL> error_callback ) <EOL> def _map_async ( self , func , iterable , mapper , chunksize = None , callback = None , <EOL> error_callback = None ) : <EOL> '''<STR_LIT>''' <EOL> if self . _state != RUN : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if not hasattr ( iterable , '<STR_LIT>' ) : <EOL> iterable = list ( iterable ) <EOL> if chunksize is None : <EOL> chunksize , extra = divmod ( len ( iterable ) , len ( self . _pool ) * <NUM_LIT:4> ) <EOL> if extra : <EOL> chunksize += <NUM_LIT:1> <EOL> if len ( iterable ) == <NUM_LIT:0> : <EOL> chunksize = <NUM_LIT:0> <EOL> task_batches = Pool . _get_tasks ( func , iterable , chunksize ) <EOL> result = MapResult ( self . _cache , chunksize , len ( iterable ) , callback , <EOL> error_callback = error_callback ) <EOL> self . _taskqueue . put ( ( ( ( result . _job , i , mapper , ( x , ) , { } ) <EOL> for i , x in enumerate ( task_batches ) ) , None ) ) <EOL> return result <EOL> @ staticmethod <EOL> def _handle_workers ( pool ) : <EOL> thread = threading . current_thread ( ) <EOL> while thread . _state == RUN or ( pool . _cache and thread . _state != TERMINATE ) : <EOL> pool . _maintain_pool ( ) <EOL> time . sleep ( <NUM_LIT:0.1> ) <EOL> pool . _taskqueue . put ( None ) <EOL> debug ( '<STR_LIT>' ) <EOL> @ staticmethod <EOL> def _handle_tasks ( taskqueue , put , outqueue , pool ) : <EOL> thread = threading . current_thread ( ) <EOL> for taskseq , set_length in iter ( taskqueue . get , None ) : <EOL> i = - <NUM_LIT:1> <EOL> for i , task in enumerate ( taskseq ) : <EOL> if thread . _state : <EOL> debug ( '<STR_LIT>' ) <EOL> break <EOL> try : <EOL> put ( task ) <EOL> except IOError : <EOL> debug ( '<STR_LIT>' ) <EOL> break <EOL> else : <EOL> if set_length : <EOL> debug ( '<STR_LIT>' ) <EOL> set_length ( i + <NUM_LIT:1> ) <EOL> continue <EOL> break <EOL> else : <EOL> debug ( '<STR_LIT>' ) <EOL> try : <EOL> debug ( '<STR_LIT>' ) <EOL> outqueue . put ( None ) <EOL> debug ( '<STR_LIT>' ) <EOL> for p in pool : <EOL> put ( None ) <EOL> except IOError : <EOL> debug ( '<STR_LIT>' ) <EOL> debug ( '<STR_LIT>' ) <EOL> @ staticmethod <EOL> def _handle_results ( outqueue , get , cache ) : <EOL> thread = threading . current_thread ( ) <EOL> while <NUM_LIT:1> : <EOL> try : <EOL> task = get ( ) <EOL> except ( IOError , EOFError ) : <EOL> debug ( '<STR_LIT>' ) <EOL> return <EOL> if thread . _state : <EOL> assert thread . _state == TERMINATE <EOL> debug ( '<STR_LIT>' ) <EOL> break <EOL> if task is None : <EOL> debug ( '<STR_LIT>' ) <EOL> break <EOL> job , i , obj = task <EOL> try : <EOL> cache [ job ] . _set ( i , obj ) <EOL> except KeyError : <EOL> pass <EOL> while cache and thread . _state != TERMINATE : <EOL> try : <EOL> task = get ( ) <EOL> except ( IOError , EOFError ) : <EOL> debug ( '<STR_LIT>' ) <EOL> return <EOL> if task is None : <EOL> debug ( '<STR_LIT>' ) <EOL> continue <EOL> job , i , obj = task <EOL> try : <EOL> cache [ job ] . _set ( i , obj ) <EOL> except KeyError : <EOL> pass <EOL> if hasattr ( outqueue , '<STR_LIT>' ) : <EOL> debug ( '<STR_LIT>' ) <EOL> try : <EOL> for i in range ( <NUM_LIT:10> ) : <EOL> if not outqueue . _reader . poll ( ) : <EOL> break <EOL> get ( ) <EOL> except ( IOError , EOFError ) : <EOL> pass <EOL> debug ( '<STR_LIT>' , <EOL> len ( cache ) , thread . _state ) <EOL> @ staticmethod <EOL> def _get_tasks ( func , it , size ) : <EOL> it = iter ( it ) <EOL> while <NUM_LIT:1> : <EOL> x = tuple ( itertools . islice ( it , size ) ) <EOL> if not x : <EOL> return <EOL> yield ( func , x ) <EOL> def __reduce__ ( self ) : <EOL> raise NotImplementedError ( <EOL> '<STR_LIT>' <EOL> ) <EOL> def close ( self ) : <EOL> debug ( '<STR_LIT>' ) <EOL> if self . _state == RUN : <EOL> self . _state = CLOSE <EOL> self . _worker_handler . _state = CLOSE <EOL> def terminate ( self ) : <EOL> debug ( '<STR_LIT>' ) <EOL> self . _state = TERMINATE <EOL> self . _worker_handler . _state = TERMINATE <EOL> self . _terminate ( ) <EOL> def join ( self ) : <EOL> debug ( '<STR_LIT>' ) <EOL> assert self . _state in ( CLOSE , TERMINATE ) <EOL> self . _worker_handler . join ( ) <EOL> self . _task_handler . join ( ) <EOL> self . _result_handler . join ( ) <EOL> for p in self . _pool : <EOL> p . join ( ) <EOL> @ staticmethod <EOL> def _help_stuff_finish ( inqueue , task_handler , size ) : <EOL> debug ( '<STR_LIT>' ) <EOL> inqueue . _rlock . acquire ( ) <EOL> while task_handler . is_alive ( ) and inqueue . _reader . poll ( ) : <EOL> inqueue . _reader . recv ( ) <EOL> time . sleep ( <NUM_LIT:0> ) <EOL> @ classmethod <EOL> def _terminate_pool ( cls , taskqueue , inqueue , outqueue , pool , <EOL> worker_handler , task_handler , result_handler , cache ) : <EOL> debug ( '<STR_LIT>' ) <EOL> worker_handler . _state = TERMINATE <EOL> task_handler . _state = TERMINATE <EOL> debug ( '<STR_LIT>' ) <EOL> cls . _help_stuff_finish ( inqueue , task_handler , len ( pool ) ) <EOL> assert result_handler . is_alive ( ) or len ( cache ) == <NUM_LIT:0> <EOL> result_handler . _state = TERMINATE <EOL> outqueue . put ( None ) <EOL> debug ( '<STR_LIT>' ) <EOL> if threading . current_thread ( ) is not worker_handler : <EOL> worker_handler . join ( ) <EOL> if pool and hasattr ( pool [ <NUM_LIT:0> ] , '<STR_LIT>' ) : <EOL> debug ( '<STR_LIT>' ) <EOL> for p in pool : <EOL> if p . exitcode is None : <EOL> p . terminate ( ) <EOL> debug ( '<STR_LIT>' ) <EOL> if threading . current_thread ( ) is not task_handler : <EOL> task_handler . join ( ) <EOL> debug ( '<STR_LIT>' ) <EOL> if threading . current_thread ( ) is not result_handler : <EOL> result_handler . join ( ) <EOL> if pool and hasattr ( pool [ <NUM_LIT:0> ] , '<STR_LIT>' ) : <EOL> debug ( '<STR_LIT>' ) <EOL> for p in pool : <EOL> if p . is_alive ( ) : <EOL> debug ( '<STR_LIT>' % p . pid ) <EOL> p . join ( ) <EOL> def __enter__ ( self ) : <EOL> return self <EOL> def __exit__ ( self , exc_type , exc_val , exc_tb ) : <EOL> self . terminate ( ) <EOL> class ApplyResult ( object ) : <EOL> def __init__ ( self , cache , callback , error_callback ) : <EOL> self . _event = threading . Event ( ) <EOL> self . _job = next ( job_counter ) <EOL> self . _cache = cache <EOL> self . _callback = callback <EOL> self . _error_callback = error_callback <EOL> cache [ self . _job ] = self <EOL> def ready ( self ) : <EOL> return self . _event . is_set ( ) <EOL> def successful ( self ) : <EOL> assert self . ready ( ) <EOL> return self . _success <EOL> def wait ( self , timeout = None ) : <EOL> self . _event . wait ( timeout ) <EOL> def get ( self , timeout = None ) : <EOL> self . wait ( timeout ) <EOL> if not self . ready ( ) : <EOL> raise TimeoutError <EOL> if self . _success : <EOL> return self . _value <EOL> else : <EOL> raise self . _value <EOL> def _set ( self , i , obj ) : <EOL> self . _success , self . _value = obj <EOL> if self . _callback and self . _success : <EOL> self . _callback ( self . _value ) <EOL> if self . _error_callback and not self . _success : <EOL> self . _error_callback ( self . _value ) <EOL> self . _event . set ( ) <EOL> del self . _cache [ self . _job ] <EOL> AsyncResult = ApplyResult <EOL> class MapResult ( ApplyResult ) : <EOL> def __init__ ( self , cache , chunksize , length , callback , error_callback ) : <EOL> ApplyResult . __init__ ( self , cache , callback , <EOL> error_callback = error_callback ) <EOL> self . _success = True <EOL> self . _value = [ None ] * length <EOL> self . _chunksize = chunksize <EOL> if chunksize <= <NUM_LIT:0> : <EOL> self . _number_left = <NUM_LIT:0> <EOL> self . _event . set ( ) <EOL> del cache [ self . _job ] <EOL> else : <EOL> self . _number_left = length // chunksize + bool ( length % chunksize ) <EOL> def _set ( self , i , success_result ) : <EOL> success , result = success_result <EOL> if success : <EOL> self . _value [ i * self . _chunksize : ( i + <NUM_LIT:1> ) * self . _chunksize ] = result <EOL> self . _number_left -= <NUM_LIT:1> <EOL> if self . _number_left == <NUM_LIT:0> : <EOL> if self . _callback : <EOL> self . _callback ( self . _value ) <EOL> del self . _cache [ self . _job ] <EOL> self . _event . set ( ) <EOL> else : <EOL> self . _success = False <EOL> self . _value = result <EOL> if self . _error_callback : <EOL> self . _error_callback ( self . _value ) <EOL> del self . _cache [ self . _job ] <EOL> self . _event . set ( ) <EOL> class IMapIterator ( object ) : <EOL> def __init__ ( self , cache ) : <EOL> self . _cond = threading . Condition ( threading . Lock ( ) ) <EOL> self . _job = next ( job_counter ) <EOL> self . _cache = cache <EOL> self . _items = collections . deque ( ) <EOL> self . _index = <NUM_LIT:0> <EOL> self . _length = None <EOL> self . _unsorted = { } <EOL> cache [ self . _job ] = self <EOL> def __iter__ ( self ) : <EOL> return self <EOL> def next ( self , timeout = None ) : <EOL> self . _cond . acquire ( ) <EOL> try : <EOL> try : <EOL> item = self . _items . popleft ( ) <EOL> except IndexError : <EOL> if self . _index == self . _length : <EOL> raise StopIteration <EOL> self . _cond . wait ( timeout ) <EOL> try : <EOL> item = self . _items . popleft ( ) <EOL> except IndexError : <EOL> if self . _index == self . _length : <EOL> raise StopIteration <EOL> raise TimeoutError <EOL> finally : <EOL> self . _cond . release ( ) <EOL> success , value = item <EOL> if success : <EOL> return value <EOL> raise value <EOL> __next__ = next <EOL> def _set ( self , i , obj ) : <EOL> self . _cond . acquire ( ) <EOL> try : <EOL> if self . _index == i : <EOL> self . _items . append ( obj ) <EOL> self . _index += <NUM_LIT:1> <EOL> while self . _index in self . _unsorted : <EOL> obj = self . _unsorted . pop ( self . _index ) <EOL> self . _items . append ( obj ) <EOL> self . _index += <NUM_LIT:1> <EOL> self . _cond . notify ( ) <EOL> else : <EOL> self . _unsorted [ i ] = obj <EOL> if self . _index == self . _length : <EOL> del self . _cache [ self . _job ] <EOL> finally : <EOL> self . _cond . release ( ) <EOL> def _set_length ( self , length ) : <EOL> self . _cond . acquire ( ) <EOL> try : <EOL> self . _length = length <EOL> if self . _index == self . _length : <EOL> self . _cond . notify ( ) <EOL> del self . _cache [ self . _job ] <EOL> finally : <EOL> self . _cond . release ( ) <EOL> class IMapUnorderedIterator ( IMapIterator ) : <EOL> def _set ( self , i , obj ) : <EOL> self . _cond . acquire ( ) <EOL> try : <EOL> self . _items . append ( obj ) <EOL> self . _index += <NUM_LIT:1> <EOL> self . _cond . notify ( ) <EOL> if self . _index == self . _length : <EOL> del self . _cache [ self . _job ] <EOL> finally : <EOL> self . _cond . release ( ) <EOL> class ThreadPool ( Pool ) : <EOL> from . dummy import Process <EOL> def __init__ ( self , processes = None , initializer = None , initargs = ( ) ) : <EOL> Pool . __init__ ( self , processes , initializer , initargs ) <EOL> def _setup_queues ( self ) : <EOL> self . _inqueue = queue . Queue ( ) <EOL> self . _outqueue = queue . Queue ( ) <EOL> self . _quick_put = self . _inqueue . put <EOL> self . _quick_get = self . _outqueue . get <EOL> @ staticmethod <EOL> def _help_stuff_finish ( inqueue , task_handler , size ) : <EOL> inqueue . not_empty . acquire ( ) <EOL> try : <EOL> inqueue . queue . clear ( ) <EOL> inqueue . queue . extend ( [ None ] * size ) <EOL> inqueue . not_empty . notify_all ( ) <EOL> finally : <EOL> inqueue . not_empty . release ( ) </s>
|
<s> import sys </s>
|
<s> """<STR_LIT>""" <EOL> from __future__ import nested_scopes , braces <EOL> def f ( x ) : <EOL> def g ( y ) : <EOL> return x + y <EOL> return g <EOL> print ( f ( <NUM_LIT:2> ) ( <NUM_LIT:4> ) ) </s>
|
<s> """<STR_LIT>""" <EOL> import sys <EOL> import time <EOL> from _thread import start_new_thread , TIMEOUT_MAX <EOL> import threading <EOL> import unittest <EOL> from test import support <EOL> def _wait ( ) : <EOL> time . sleep ( <NUM_LIT> ) <EOL> class Bunch ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , f , n , wait_before_exit = False ) : <EOL> """<STR_LIT>""" <EOL> self . f = f <EOL> self . n = n <EOL> self . started = [ ] <EOL> self . finished = [ ] <EOL> self . _can_exit = not wait_before_exit <EOL> def task ( ) : <EOL> tid = threading . get_ident ( ) <EOL> self . started . append ( tid ) <EOL> try : <EOL> f ( ) <EOL> finally : <EOL> self . finished . append ( tid ) <EOL> while not self . _can_exit : <EOL> _wait ( ) <EOL> for i in range ( n ) : <EOL> start_new_thread ( task , ( ) ) <EOL> def wait_for_started ( self ) : <EOL> while len ( self . started ) < self . n : <EOL> _wait ( ) <EOL> def wait_for_finished ( self ) : <EOL> while len ( self . finished ) < self . n : <EOL> _wait ( ) <EOL> def do_finish ( self ) : <EOL> self . _can_exit = True <EOL> class BaseTestCase ( unittest . TestCase ) : <EOL> def setUp ( self ) : <EOL> self . _threads = support . threading_setup ( ) <EOL> def tearDown ( self ) : <EOL> support . threading_cleanup ( * self . _threads ) <EOL> support . reap_children ( ) <EOL> def assertTimeout ( self , actual , expected ) : <EOL> self . assertGreaterEqual ( actual , expected * <NUM_LIT> ) <EOL> self . assertLess ( actual , expected * <NUM_LIT> ) <EOL> class BaseLockTests ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_constructor ( self ) : <EOL> lock = self . locktype ( ) <EOL> del lock <EOL> def test_acquire_destroy ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> del lock <EOL> def test_acquire_release ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> del lock <EOL> def test_try_acquire ( self ) : <EOL> lock = self . locktype ( ) <EOL> self . assertTrue ( lock . acquire ( False ) ) <EOL> lock . release ( ) <EOL> def test_try_acquire_contended ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> result = [ ] <EOL> def f ( ) : <EOL> result . append ( lock . acquire ( False ) ) <EOL> Bunch ( f , <NUM_LIT:1> ) . wait_for_finished ( ) <EOL> self . assertFalse ( result [ <NUM_LIT:0> ] ) <EOL> lock . release ( ) <EOL> def test_acquire_contended ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> N = <NUM_LIT:5> <EOL> def f ( ) : <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> b = Bunch ( f , N ) <EOL> b . wait_for_started ( ) <EOL> _wait ( ) <EOL> self . assertEqual ( len ( b . finished ) , <NUM_LIT:0> ) <EOL> lock . release ( ) <EOL> b . wait_for_finished ( ) <EOL> self . assertEqual ( len ( b . finished ) , N ) <EOL> def test_with ( self ) : <EOL> lock = self . locktype ( ) <EOL> def f ( ) : <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> def _with ( err = None ) : <EOL> with lock : <EOL> if err is not None : <EOL> raise err <EOL> _with ( ) <EOL> Bunch ( f , <NUM_LIT:1> ) . wait_for_finished ( ) <EOL> self . assertRaises ( TypeError , _with , TypeError ) <EOL> Bunch ( f , <NUM_LIT:1> ) . wait_for_finished ( ) <EOL> def test_thread_leak ( self ) : <EOL> lock = self . locktype ( ) <EOL> def f ( ) : <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> n = len ( threading . enumerate ( ) ) <EOL> Bunch ( f , <NUM_LIT:15> ) . wait_for_finished ( ) <EOL> if len ( threading . enumerate ( ) ) != n : <EOL> time . sleep ( <NUM_LIT> ) <EOL> self . assertEqual ( n , len ( threading . enumerate ( ) ) ) <EOL> def test_timeout ( self ) : <EOL> lock = self . locktype ( ) <EOL> self . assertRaises ( ValueError , lock . acquire , <NUM_LIT:0> , <NUM_LIT:1> ) <EOL> self . assertRaises ( ValueError , lock . acquire , timeout = - <NUM_LIT:100> ) <EOL> self . assertRaises ( OverflowError , lock . acquire , timeout = <NUM_LIT> ) <EOL> self . assertRaises ( OverflowError , lock . acquire , timeout = TIMEOUT_MAX + <NUM_LIT:1> ) <EOL> lock . acquire ( timeout = TIMEOUT_MAX ) <EOL> lock . release ( ) <EOL> t1 = time . time ( ) <EOL> self . assertTrue ( lock . acquire ( timeout = <NUM_LIT:5> ) ) <EOL> t2 = time . time ( ) <EOL> self . assertLess ( t2 - t1 , <NUM_LIT:5> ) <EOL> results = [ ] <EOL> def f ( ) : <EOL> t1 = time . time ( ) <EOL> results . append ( lock . acquire ( timeout = <NUM_LIT:0.5> ) ) <EOL> t2 = time . time ( ) <EOL> results . append ( t2 - t1 ) <EOL> Bunch ( f , <NUM_LIT:1> ) . wait_for_finished ( ) <EOL> self . assertFalse ( results [ <NUM_LIT:0> ] ) <EOL> self . assertTimeout ( results [ <NUM_LIT:1> ] , <NUM_LIT:0.5> ) <EOL> class LockTests ( BaseLockTests ) : <EOL> """<STR_LIT>""" <EOL> def test_reacquire ( self ) : <EOL> lock = self . locktype ( ) <EOL> phase = [ ] <EOL> def f ( ) : <EOL> lock . acquire ( ) <EOL> phase . append ( None ) <EOL> lock . acquire ( ) <EOL> phase . append ( None ) <EOL> start_new_thread ( f , ( ) ) <EOL> while len ( phase ) == <NUM_LIT:0> : <EOL> _wait ( ) <EOL> _wait ( ) <EOL> self . assertEqual ( len ( phase ) , <NUM_LIT:1> ) <EOL> lock . release ( ) <EOL> while len ( phase ) == <NUM_LIT:1> : <EOL> _wait ( ) <EOL> self . assertEqual ( len ( phase ) , <NUM_LIT:2> ) <EOL> def test_different_thread ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> def f ( ) : <EOL> lock . release ( ) <EOL> b = Bunch ( f , <NUM_LIT:1> ) <EOL> b . wait_for_finished ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> def test_state_after_timeout ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> self . assertFalse ( lock . acquire ( timeout = <NUM_LIT> ) ) <EOL> lock . release ( ) <EOL> self . assertFalse ( lock . locked ( ) ) <EOL> self . assertTrue ( lock . acquire ( blocking = False ) ) <EOL> class RLockTests ( BaseLockTests ) : <EOL> """<STR_LIT>""" <EOL> def test_reacquire ( self ) : <EOL> lock = self . locktype ( ) <EOL> lock . acquire ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> lock . release ( ) <EOL> def test_release_unacquired ( self ) : <EOL> lock = self . locktype ( ) <EOL> self . assertRaises ( RuntimeError , lock . release ) <EOL> lock . acquire ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> lock . release ( ) <EOL> self . assertRaises ( RuntimeError , lock . release ) <EOL> def test_release_save_unacquired ( self ) : <EOL> lock = self . locktype ( ) <EOL> self . assertRaises ( RuntimeError , lock . _release_save ) <EOL> lock . acquire ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> lock . acquire ( ) <EOL> lock . release ( ) <EOL> lock . release ( ) <EOL> self . assertRaises ( RuntimeError , lock . _release_save ) <EOL> def test_different_thread ( self ) : <EOL> lock = self . locktype ( ) <EOL> def f ( ) : <EOL> lock . acquire ( ) <EOL> b = Bunch ( f , <NUM_LIT:1> , True ) <EOL> try : <EOL> self . assertRaises ( RuntimeError , lock . release ) <EOL> finally : <EOL> b . do_finish ( ) <EOL> def test__is_owned ( self ) : <EOL> lock = self . locktype ( ) <EOL> self . assertFalse ( lock . _is_owned ( ) ) <EOL> lock . acquire ( ) <EOL> self . assertTrue ( lock . _is_owned ( ) ) <EOL> lock . acquire ( ) <EOL> self . assertTrue ( lock . _is_owned ( ) ) <EOL> result = [ ] <EOL> def f ( ) : <EOL> result . append ( lock . _is_owned ( ) ) <EOL> Bunch ( f , <NUM_LIT:1> ) . wait_for_finished ( ) <EOL> self . assertFalse ( result [ <NUM_LIT:0> ] ) <EOL> lock . release ( ) <EOL> self . assertTrue ( lock . _is_owned ( ) ) <EOL> lock . release ( ) <EOL> self . assertFalse ( lock . _is_owned ( ) ) <EOL> class EventTests ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_is_set ( self ) : <EOL> evt = self . eventtype ( ) <EOL> self . assertFalse ( evt . is_set ( ) ) <EOL> evt . set ( ) <EOL> self . assertTrue ( evt . is_set ( ) ) <EOL> evt . set ( ) <EOL> self . assertTrue ( evt . is_set ( ) ) <EOL> evt . clear ( ) <EOL> self . assertFalse ( evt . is_set ( ) ) <EOL> evt . clear ( ) <EOL> self . assertFalse ( evt . is_set ( ) ) <EOL> def _check_notify ( self , evt ) : <EOL> N = <NUM_LIT:5> <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> def f ( ) : <EOL> results1 . append ( evt . wait ( ) ) <EOL> results2 . append ( evt . wait ( ) ) <EOL> b = Bunch ( f , N ) <EOL> b . wait_for_started ( ) <EOL> _wait ( ) <EOL> self . assertEqual ( len ( results1 ) , <NUM_LIT:0> ) <EOL> evt . set ( ) <EOL> b . wait_for_finished ( ) <EOL> self . assertEqual ( results1 , [ True ] * N ) <EOL> self . assertEqual ( results2 , [ True ] * N ) <EOL> def test_notify ( self ) : <EOL> evt = self . eventtype ( ) <EOL> self . _check_notify ( evt ) <EOL> evt . set ( ) <EOL> evt . clear ( ) <EOL> self . _check_notify ( evt ) <EOL> def test_timeout ( self ) : <EOL> evt = self . eventtype ( ) <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> N = <NUM_LIT:5> <EOL> def f ( ) : <EOL> results1 . append ( evt . wait ( <NUM_LIT:0.0> ) ) <EOL> t1 = time . time ( ) <EOL> r = evt . wait ( <NUM_LIT:0.5> ) <EOL> t2 = time . time ( ) <EOL> results2 . append ( ( r , t2 - t1 ) ) <EOL> Bunch ( f , N ) . wait_for_finished ( ) <EOL> self . assertEqual ( results1 , [ False ] * N ) <EOL> for r , dt in results2 : <EOL> self . assertFalse ( r ) <EOL> self . assertTimeout ( dt , <NUM_LIT:0.5> ) <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> evt . set ( ) <EOL> Bunch ( f , N ) . wait_for_finished ( ) <EOL> self . assertEqual ( results1 , [ True ] * N ) <EOL> for r , dt in results2 : <EOL> self . assertTrue ( r ) <EOL> def test_set_and_clear ( self ) : <EOL> evt = self . eventtype ( ) <EOL> results = [ ] <EOL> N = <NUM_LIT:5> <EOL> def f ( ) : <EOL> results . append ( evt . wait ( <NUM_LIT:1> ) ) <EOL> b = Bunch ( f , N ) <EOL> b . wait_for_started ( ) <EOL> time . sleep ( <NUM_LIT:0.5> ) <EOL> evt . set ( ) <EOL> evt . clear ( ) <EOL> b . wait_for_finished ( ) <EOL> self . assertEqual ( results , [ True ] * N ) <EOL> class ConditionTests ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_acquire ( self ) : <EOL> cond = self . condtype ( ) <EOL> cond . acquire ( ) <EOL> cond . acquire ( ) <EOL> cond . release ( ) <EOL> cond . release ( ) <EOL> lock = threading . Lock ( ) <EOL> cond = self . condtype ( lock ) <EOL> cond . acquire ( ) <EOL> self . assertFalse ( lock . acquire ( False ) ) <EOL> cond . release ( ) <EOL> self . assertTrue ( lock . acquire ( False ) ) <EOL> self . assertFalse ( cond . acquire ( False ) ) <EOL> lock . release ( ) <EOL> with cond : <EOL> self . assertFalse ( lock . acquire ( False ) ) <EOL> def test_unacquired_wait ( self ) : <EOL> cond = self . condtype ( ) <EOL> self . assertRaises ( RuntimeError , cond . wait ) <EOL> def test_unacquired_notify ( self ) : <EOL> cond = self . condtype ( ) <EOL> self . assertRaises ( RuntimeError , cond . notify ) <EOL> def _check_notify ( self , cond ) : <EOL> N = <NUM_LIT:5> <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> phase_num = <NUM_LIT:0> <EOL> def f ( ) : <EOL> cond . acquire ( ) <EOL> result = cond . wait ( ) <EOL> cond . release ( ) <EOL> results1 . append ( ( result , phase_num ) ) <EOL> cond . acquire ( ) <EOL> result = cond . wait ( ) <EOL> cond . release ( ) <EOL> results2 . append ( ( result , phase_num ) ) <EOL> b = Bunch ( f , N ) <EOL> b . wait_for_started ( ) <EOL> _wait ( ) <EOL> self . assertEqual ( results1 , [ ] ) <EOL> cond . acquire ( ) <EOL> cond . notify ( <NUM_LIT:3> ) <EOL> _wait ( ) <EOL> phase_num = <NUM_LIT:1> <EOL> cond . release ( ) <EOL> while len ( results1 ) < <NUM_LIT:3> : <EOL> _wait ( ) <EOL> self . assertEqual ( results1 , [ ( True , <NUM_LIT:1> ) ] * <NUM_LIT:3> ) <EOL> self . assertEqual ( results2 , [ ] ) <EOL> cond . acquire ( ) <EOL> cond . notify ( <NUM_LIT:5> ) <EOL> _wait ( ) <EOL> phase_num = <NUM_LIT:2> <EOL> cond . release ( ) <EOL> while len ( results1 ) + len ( results2 ) < <NUM_LIT:8> : <EOL> _wait ( ) <EOL> self . assertEqual ( results1 , [ ( True , <NUM_LIT:1> ) ] * <NUM_LIT:3> + [ ( True , <NUM_LIT:2> ) ] * <NUM_LIT:2> ) <EOL> self . assertEqual ( results2 , [ ( True , <NUM_LIT:2> ) ] * <NUM_LIT:3> ) <EOL> cond . acquire ( ) <EOL> cond . notify_all ( ) <EOL> _wait ( ) <EOL> phase_num = <NUM_LIT:3> <EOL> cond . release ( ) <EOL> while len ( results2 ) < <NUM_LIT:5> : <EOL> _wait ( ) <EOL> self . assertEqual ( results1 , [ ( True , <NUM_LIT:1> ) ] * <NUM_LIT:3> + [ ( True , <NUM_LIT:2> ) ] * <NUM_LIT:2> ) <EOL> self . assertEqual ( results2 , [ ( True , <NUM_LIT:2> ) ] * <NUM_LIT:3> + [ ( True , <NUM_LIT:3> ) ] * <NUM_LIT:2> ) <EOL> b . wait_for_finished ( ) <EOL> def test_notify ( self ) : <EOL> cond = self . condtype ( ) <EOL> self . _check_notify ( cond ) <EOL> self . _check_notify ( cond ) <EOL> def test_timeout ( self ) : <EOL> cond = self . condtype ( ) <EOL> results = [ ] <EOL> N = <NUM_LIT:5> <EOL> def f ( ) : <EOL> cond . acquire ( ) <EOL> t1 = time . time ( ) <EOL> result = cond . wait ( <NUM_LIT:0.5> ) <EOL> t2 = time . time ( ) <EOL> cond . release ( ) <EOL> results . append ( ( t2 - t1 , result ) ) <EOL> Bunch ( f , N ) . wait_for_finished ( ) <EOL> self . assertEqual ( len ( results ) , N ) <EOL> for dt , result in results : <EOL> self . assertTimeout ( dt , <NUM_LIT:0.5> ) <EOL> self . assertFalse ( result ) <EOL> def test_waitfor ( self ) : <EOL> cond = self . condtype ( ) <EOL> state = <NUM_LIT:0> <EOL> def f ( ) : <EOL> with cond : <EOL> result = cond . wait_for ( lambda : state == <NUM_LIT:4> ) <EOL> self . assertTrue ( result ) <EOL> self . assertEqual ( state , <NUM_LIT:4> ) <EOL> b = Bunch ( f , <NUM_LIT:1> ) <EOL> b . wait_for_started ( ) <EOL> for i in range ( <NUM_LIT:4> ) : <EOL> time . sleep ( <NUM_LIT> ) <EOL> with cond : <EOL> state += <NUM_LIT:1> <EOL> cond . notify ( ) <EOL> b . wait_for_finished ( ) <EOL> def test_waitfor_timeout ( self ) : <EOL> cond = self . condtype ( ) <EOL> state = <NUM_LIT:0> <EOL> success = [ ] <EOL> def f ( ) : <EOL> with cond : <EOL> dt = time . time ( ) <EOL> result = cond . wait_for ( lambda : state == <NUM_LIT:4> , timeout = <NUM_LIT:0.1> ) <EOL> dt = time . time ( ) - dt <EOL> self . assertFalse ( result ) <EOL> self . assertTimeout ( dt , <NUM_LIT:0.1> ) <EOL> success . append ( None ) <EOL> b = Bunch ( f , <NUM_LIT:1> ) <EOL> b . wait_for_started ( ) <EOL> for i in range ( <NUM_LIT:3> ) : <EOL> time . sleep ( <NUM_LIT> ) <EOL> with cond : <EOL> state += <NUM_LIT:1> <EOL> cond . notify ( ) <EOL> b . wait_for_finished ( ) <EOL> self . assertEqual ( len ( success ) , <NUM_LIT:1> ) <EOL> class BaseSemaphoreTests ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> def test_constructor ( self ) : <EOL> self . assertRaises ( ValueError , self . semtype , value = - <NUM_LIT:1> ) <EOL> self . assertRaises ( ValueError , self . semtype , value = - sys . maxsize ) <EOL> def test_acquire ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:1> ) <EOL> sem . acquire ( ) <EOL> sem . release ( ) <EOL> sem = self . semtype ( <NUM_LIT:2> ) <EOL> sem . acquire ( ) <EOL> sem . acquire ( ) <EOL> sem . release ( ) <EOL> sem . release ( ) <EOL> def test_acquire_destroy ( self ) : <EOL> sem = self . semtype ( ) <EOL> sem . acquire ( ) <EOL> del sem <EOL> def test_acquire_contended ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:7> ) <EOL> sem . acquire ( ) <EOL> N = <NUM_LIT:10> <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> phase_num = <NUM_LIT:0> <EOL> def f ( ) : <EOL> sem . acquire ( ) <EOL> results1 . append ( phase_num ) <EOL> sem . acquire ( ) <EOL> results2 . append ( phase_num ) <EOL> b = Bunch ( f , <NUM_LIT:10> ) <EOL> b . wait_for_started ( ) <EOL> while len ( results1 ) + len ( results2 ) < <NUM_LIT:6> : <EOL> _wait ( ) <EOL> self . assertEqual ( results1 + results2 , [ <NUM_LIT:0> ] * <NUM_LIT:6> ) <EOL> phase_num = <NUM_LIT:1> <EOL> for i in range ( <NUM_LIT:7> ) : <EOL> sem . release ( ) <EOL> while len ( results1 ) + len ( results2 ) < <NUM_LIT> : <EOL> _wait ( ) <EOL> self . assertEqual ( sorted ( results1 + results2 ) , [ <NUM_LIT:0> ] * <NUM_LIT:6> + [ <NUM_LIT:1> ] * <NUM_LIT:7> ) <EOL> phase_num = <NUM_LIT:2> <EOL> for i in range ( <NUM_LIT:6> ) : <EOL> sem . release ( ) <EOL> while len ( results1 ) + len ( results2 ) < <NUM_LIT> : <EOL> _wait ( ) <EOL> self . assertEqual ( sorted ( results1 + results2 ) , [ <NUM_LIT:0> ] * <NUM_LIT:6> + [ <NUM_LIT:1> ] * <NUM_LIT:7> + [ <NUM_LIT:2> ] * <NUM_LIT:6> ) <EOL> self . assertFalse ( sem . acquire ( False ) ) <EOL> sem . release ( ) <EOL> b . wait_for_finished ( ) <EOL> def test_try_acquire ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:2> ) <EOL> self . assertTrue ( sem . acquire ( False ) ) <EOL> self . assertTrue ( sem . acquire ( False ) ) <EOL> self . assertFalse ( sem . acquire ( False ) ) <EOL> sem . release ( ) <EOL> self . assertTrue ( sem . acquire ( False ) ) <EOL> def test_try_acquire_contended ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:4> ) <EOL> sem . acquire ( ) <EOL> results = [ ] <EOL> def f ( ) : <EOL> results . append ( sem . acquire ( False ) ) <EOL> results . append ( sem . acquire ( False ) ) <EOL> Bunch ( f , <NUM_LIT:5> ) . wait_for_finished ( ) <EOL> self . assertEqual ( sorted ( results ) , [ False ] * <NUM_LIT:7> + [ True ] * <NUM_LIT:3> ) <EOL> def test_acquire_timeout ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:2> ) <EOL> self . assertRaises ( ValueError , sem . acquire , False , timeout = <NUM_LIT:1.0> ) <EOL> self . assertTrue ( sem . acquire ( timeout = <NUM_LIT> ) ) <EOL> self . assertTrue ( sem . acquire ( timeout = <NUM_LIT> ) ) <EOL> self . assertFalse ( sem . acquire ( timeout = <NUM_LIT> ) ) <EOL> sem . release ( ) <EOL> self . assertTrue ( sem . acquire ( timeout = <NUM_LIT> ) ) <EOL> t = time . time ( ) <EOL> self . assertFalse ( sem . acquire ( timeout = <NUM_LIT:0.5> ) ) <EOL> dt = time . time ( ) - t <EOL> self . assertTimeout ( dt , <NUM_LIT:0.5> ) <EOL> def test_default_value ( self ) : <EOL> sem = self . semtype ( ) <EOL> sem . acquire ( ) <EOL> def f ( ) : <EOL> sem . acquire ( ) <EOL> sem . release ( ) <EOL> b = Bunch ( f , <NUM_LIT:1> ) <EOL> b . wait_for_started ( ) <EOL> _wait ( ) <EOL> self . assertFalse ( b . finished ) <EOL> sem . release ( ) <EOL> b . wait_for_finished ( ) <EOL> def test_with ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:2> ) <EOL> def _with ( err = None ) : <EOL> with sem : <EOL> self . assertTrue ( sem . acquire ( False ) ) <EOL> sem . release ( ) <EOL> with sem : <EOL> self . assertFalse ( sem . acquire ( False ) ) <EOL> if err : <EOL> raise err <EOL> _with ( ) <EOL> self . assertTrue ( sem . acquire ( False ) ) <EOL> sem . release ( ) <EOL> self . assertRaises ( TypeError , _with , TypeError ) <EOL> self . assertTrue ( sem . acquire ( False ) ) <EOL> sem . release ( ) <EOL> class SemaphoreTests ( BaseSemaphoreTests ) : <EOL> """<STR_LIT>""" <EOL> def test_release_unacquired ( self ) : <EOL> sem = self . semtype ( <NUM_LIT:1> ) <EOL> sem . release ( ) <EOL> sem . acquire ( ) <EOL> sem . acquire ( ) <EOL> sem . release ( ) <EOL> class BoundedSemaphoreTests ( BaseSemaphoreTests ) : <EOL> """<STR_LIT>""" <EOL> def test_release_unacquired ( self ) : <EOL> sem = self . semtype ( ) <EOL> self . assertRaises ( ValueError , sem . release ) <EOL> sem . acquire ( ) <EOL> sem . release ( ) <EOL> self . assertRaises ( ValueError , sem . release ) <EOL> class BarrierTests ( BaseTestCase ) : <EOL> """<STR_LIT>""" <EOL> N = <NUM_LIT:5> <EOL> defaultTimeout = <NUM_LIT> <EOL> def setUp ( self ) : <EOL> self . barrier = self . barriertype ( self . N , timeout = self . defaultTimeout ) <EOL> def tearDown ( self ) : <EOL> self . barrier . abort ( ) <EOL> def run_threads ( self , f ) : <EOL> b = Bunch ( f , self . N - <NUM_LIT:1> ) <EOL> f ( ) <EOL> b . wait_for_finished ( ) <EOL> def multipass ( self , results , n ) : <EOL> m = self . barrier . parties <EOL> self . assertEqual ( m , self . N ) <EOL> for i in range ( n ) : <EOL> results [ <NUM_LIT:0> ] . append ( True ) <EOL> self . assertEqual ( len ( results [ <NUM_LIT:1> ] ) , i * m ) <EOL> self . barrier . wait ( ) <EOL> results [ <NUM_LIT:1> ] . append ( True ) <EOL> self . assertEqual ( len ( results [ <NUM_LIT:0> ] ) , ( i + <NUM_LIT:1> ) * m ) <EOL> self . barrier . wait ( ) <EOL> self . assertEqual ( self . barrier . n_waiting , <NUM_LIT:0> ) <EOL> self . assertFalse ( self . barrier . broken ) <EOL> def test_barrier ( self , passes = <NUM_LIT:1> ) : <EOL> """<STR_LIT>""" <EOL> results = [ [ ] , [ ] ] <EOL> def f ( ) : <EOL> self . multipass ( results , passes ) <EOL> self . run_threads ( f ) <EOL> def test_barrier_10 ( self ) : <EOL> """<STR_LIT>""" <EOL> return self . test_barrier ( <NUM_LIT:10> ) <EOL> def test_wait_return ( self ) : <EOL> """<STR_LIT>""" <EOL> results = [ ] <EOL> def f ( ) : <EOL> r = self . barrier . wait ( ) <EOL> results . append ( r ) <EOL> self . run_threads ( f ) <EOL> self . assertEqual ( sum ( results ) , sum ( range ( self . N ) ) ) <EOL> def test_action ( self ) : <EOL> """<STR_LIT>""" <EOL> results = [ ] <EOL> def action ( ) : <EOL> results . append ( True ) <EOL> barrier = self . barriertype ( self . N , action ) <EOL> def f ( ) : <EOL> barrier . wait ( ) <EOL> self . assertEqual ( len ( results ) , <NUM_LIT:1> ) <EOL> self . run_threads ( f ) <EOL> def test_abort ( self ) : <EOL> """<STR_LIT>""" <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> def f ( ) : <EOL> try : <EOL> i = self . barrier . wait ( ) <EOL> if i == self . N // <NUM_LIT:2> : <EOL> raise RuntimeError <EOL> self . barrier . wait ( ) <EOL> results1 . append ( True ) <EOL> except threading . BrokenBarrierError : <EOL> results2 . append ( True ) <EOL> except RuntimeError : <EOL> self . barrier . abort ( ) <EOL> pass <EOL> self . run_threads ( f ) <EOL> self . assertEqual ( len ( results1 ) , <NUM_LIT:0> ) <EOL> self . assertEqual ( len ( results2 ) , self . N - <NUM_LIT:1> ) <EOL> self . assertTrue ( self . barrier . broken ) <EOL> def test_reset ( self ) : <EOL> """<STR_LIT>""" <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> results3 = [ ] <EOL> def f ( ) : <EOL> i = self . barrier . wait ( ) <EOL> if i == self . N // <NUM_LIT:2> : <EOL> while self . barrier . n_waiting < self . N - <NUM_LIT:1> : <EOL> time . sleep ( <NUM_LIT> ) <EOL> self . barrier . reset ( ) <EOL> else : <EOL> try : <EOL> self . barrier . wait ( ) <EOL> results1 . append ( True ) <EOL> except threading . BrokenBarrierError : <EOL> results2 . append ( True ) <EOL> self . barrier . wait ( ) <EOL> results3 . append ( True ) <EOL> self . run_threads ( f ) <EOL> self . assertEqual ( len ( results1 ) , <NUM_LIT:0> ) <EOL> self . assertEqual ( len ( results2 ) , self . N - <NUM_LIT:1> ) <EOL> self . assertEqual ( len ( results3 ) , self . N ) <EOL> def test_abort_and_reset ( self ) : <EOL> """<STR_LIT>""" <EOL> results1 = [ ] <EOL> results2 = [ ] <EOL> results3 = [ ] <EOL> barrier2 = self . barriertype ( self . N ) <EOL> def f ( ) : <EOL> try : <EOL> i = self . barrier . wait ( ) <EOL> if i == self . N // <NUM_LIT:2> : <EOL> raise RuntimeError <EOL> self . barrier . wait ( ) <EOL> results1 . append ( True ) <EOL> except threading . BrokenBarrierError : <EOL> results2 . append ( True ) <EOL> except RuntimeError : <EOL> self . barrier . abort ( ) <EOL> pass <EOL> if barrier2 . wait ( ) == self . N // <NUM_LIT:2> : <EOL> self . barrier . reset ( ) <EOL> barrier2 . wait ( ) <EOL> self . barrier . wait ( ) <EOL> results3 . append ( True ) <EOL> self . run_threads ( f ) <EOL> self . assertEqual ( len ( results1 ) , <NUM_LIT:0> ) <EOL> self . assertEqual ( len ( results2 ) , self . N - <NUM_LIT:1> ) <EOL> self . assertEqual ( len ( results3 ) , self . N ) <EOL> def test_timeout ( self ) : <EOL> """<STR_LIT>""" <EOL> def f ( ) : <EOL> i = self . barrier . wait ( ) <EOL> if i == self . N // <NUM_LIT:2> : <EOL> time . sleep ( <NUM_LIT:1.0> ) <EOL> self . assertRaises ( threading . BrokenBarrierError , <EOL> self . barrier . wait , <NUM_LIT:0.5> ) <EOL> self . run_threads ( f ) <EOL> def test_default_timeout ( self ) : <EOL> """<STR_LIT>""" <EOL> barrier = self . barriertype ( self . N , timeout = <NUM_LIT> ) <EOL> def f ( ) : <EOL> i = barrier . wait ( ) <EOL> if i == self . N // <NUM_LIT:2> : <EOL> time . sleep ( <NUM_LIT:1.0> ) <EOL> self . assertRaises ( threading . BrokenBarrierError , barrier . wait ) <EOL> self . run_threads ( f ) <EOL> def test_single_thread ( self ) : <EOL> b = self . barriertype ( <NUM_LIT:1> ) <EOL> b . wait ( ) <EOL> b . wait ( ) </s>
|
<s> """<STR_LIT>""" <EOL> import unittest <EOL> import weakref <EOL> import _testcapi <EOL> def consts ( t ) : <EOL> """<STR_LIT>""" <EOL> for elt in t : <EOL> r = repr ( elt ) <EOL> if r . startswith ( "<STR_LIT>" ) : <EOL> yield "<STR_LIT>" % elt . co_name <EOL> else : <EOL> yield r <EOL> def dump ( co ) : <EOL> """<STR_LIT>""" <EOL> for attr in [ "<STR_LIT:name>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , <EOL> "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" ] : <EOL> print ( "<STR_LIT>" % ( attr , getattr ( co , "<STR_LIT>" + attr ) ) ) <EOL> print ( "<STR_LIT>" , tuple ( consts ( co . co_consts ) ) ) <EOL> class CodeTest ( unittest . TestCase ) : <EOL> def test_newempty ( self ) : <EOL> co = _testcapi . code_newempty ( "<STR_LIT:filename>" , "<STR_LIT>" , <NUM_LIT:15> ) <EOL> self . assertEqual ( co . co_filename , "<STR_LIT:filename>" ) <EOL> self . assertEqual ( co . co_name , "<STR_LIT>" ) <EOL> self . assertEqual ( co . co_firstlineno , <NUM_LIT:15> ) <EOL> class CodeWeakRefTest ( unittest . TestCase ) : <EOL> def test_basic ( self ) : <EOL> namespace = { } <EOL> exec ( "<STR_LIT>" , globals ( ) , namespace ) <EOL> f = namespace [ "<STR_LIT:f>" ] <EOL> del namespace <EOL> self . called = False <EOL> def callback ( code ) : <EOL> self . called = True <EOL> coderef = weakref . ref ( f . __code__ , callback ) <EOL> self . assertTrue ( bool ( coderef ( ) ) ) <EOL> del f <EOL> self . assertFalse ( bool ( coderef ( ) ) ) <EOL> self . assertTrue ( self . called ) <EOL> def test_main ( verbose = None ) : <EOL> from test . support import run_doctest , run_unittest <EOL> from test import test_code <EOL> run_doctest ( test_code , verbose ) <EOL> run_unittest ( CodeTest , CodeWeakRefTest ) <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> test_main ( ) </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.