idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
19,900
def rabin_karp_factor ( s , t , k ) : last_pos = pow ( DOMAIN , k - 1 ) % PRIME pos = { } assert k > 0 if len ( s ) < k or len ( t ) < k : return None hash_t = 0 for j in range ( k ) : hash_t = ( DOMAIN * hash_t + ord ( t [ j ] ) ) % PRIME for j in range ( len ( t ) - k + 1 ) : if hash_t in pos : pos [ hash_t ] . append ( j ) else : pos [ hash_t ] = [ j ] if j < len ( t ) - k : hash_t = roll_hash ( hash_t , ord ( t [ j ] ) , ord ( t [ j + k ] ) , last_pos ) hash_s = 0 for i in range ( k ) : hash_s = ( DOMAIN * hash_s + ord ( s [ i ] ) ) % PRIME for i in range ( len ( s ) - k + 1 ) : if hash_s in pos : for j in pos [ hash_s ] : if matches ( s , t , i , j , k ) : return ( i , j ) if i < len ( s ) - k : hash_s = roll_hash ( hash_s , ord ( s [ i ] ) , ord ( s [ i + k ] ) , last_pos ) return None
Find a common factor by Rabin - Karp
19,901
def rectangles_from_histogram ( H ) : best = ( float ( '-inf' ) , 0 , 0 , 0 ) S = [ ] H2 = H + [ float ( '-inf' ) ] for right in range ( len ( H2 ) ) : x = H2 [ right ] left = right while len ( S ) > 0 and S [ - 1 ] [ 1 ] >= x : left , height = S . pop ( ) rect = ( height * ( right - left ) , left , height , right ) if rect > best : best = rect S . append ( ( left , x ) ) return best
Largest Rectangular Area in a Histogram
19,902
def topological_order_dfs ( graph ) : n = len ( graph ) order = [ ] times_seen = [ - 1 ] * n for start in range ( n ) : if times_seen [ start ] == - 1 : times_seen [ start ] = 0 to_visit = [ start ] while to_visit : node = to_visit [ - 1 ] children = graph [ node ] if times_seen [ node ] == len ( children ) : to_visit . pop ( ) order . append ( node ) else : child = children [ times_seen [ node ] ] times_seen [ node ] += 1 if times_seen [ child ] == - 1 : times_seen [ child ] = 0 to_visit . append ( child ) return order [ : : - 1 ]
Topological sorting by depth first search
19,903
def topological_order ( graph ) : V = range ( len ( graph ) ) indeg = [ 0 for _ in V ] for node in V : for neighbor in graph [ node ] : indeg [ neighbor ] += 1 Q = [ node for node in V if indeg [ node ] == 0 ] order = [ ] while Q : node = Q . pop ( ) order . append ( node ) for neighbor in graph [ node ] : indeg [ neighbor ] -= 1 if indeg [ neighbor ] == 0 : Q . append ( neighbor ) return order
Topological sorting by maintaining indegree
19,904
def getkth ( self , k ) : "starts from 0" if k >= len ( self ) : raise IndexError k += 1 h = len ( self . next ) - 1 x = self while k : while x . next [ h ] is None or x . count [ h ] > k : h -= 1 k -= x . count [ h ] x = x . next [ h ] return x . key
starts from 0
19,905
def pop ( self ) : try : x = next ( iter ( self ) ) self . remove ( x ) return x except StopIteration : raise KeyError ( 'pop from an empty set' )
Pops the first element
19,906
def merge ( x , y ) : z = [ ] i = 0 j = 0 while i < len ( x ) or j < len ( y ) : if j == len ( y ) or i < len ( x ) and x [ i ] <= y [ j ] : z . append ( x [ i ] ) i += 1 else : z . append ( y [ j ] ) j += 1 return z
Merge two ordered lists
19,907
def consecutive_ones_property ( sets , universe = None ) : if universe is None : universe = set ( ) for S in sets : universe |= set ( S ) tree = PQ_tree ( universe ) try : for S in sets : tree . reduce ( S ) return tree . border ( ) except IsNotC1P : return None
Check the consecutive ones property .
19,908
def add ( self , node ) : self . sons . append ( node ) node . parent = self
Add one node as descendant
19,909
def add_group ( self , L ) : if len ( L ) == 1 : self . add ( L [ 0 ] ) elif len ( L ) >= 2 : x = PQ_node ( P_shape ) x . add_all ( L ) self . add ( x )
Add elements of L as descendants of the node . If there are several elements in L group them in a P - node first
19,910
def border ( self , L ) : if self . shape == L_shape : L . append ( self . value ) else : for x in self . sons : x . border ( L )
Append to L the border of the subtree .
19,911
def maximum_border_length ( w ) : n = len ( w ) f = [ 0 ] * n k = 0 for i in range ( 1 , n ) : while w [ k ] != w [ i ] and k > 0 : k = f [ k - 1 ] if w [ k ] == w [ i ] : k += 1 f [ i ] = k return f
Maximum string borders by Knuth - Morris - Pratt
19,912
def knuth_morris_pratt ( s , t ) : sep = '\x00' assert sep not in t and sep not in s f = maximum_border_length ( t + sep + s ) n = len ( t ) for i , fi in enumerate ( f ) : if fi == n : return i - 2 * n return - 1
Find a substring by Knuth - Morris - Pratt
19,913
def powerstring_by_border ( u ) : f = maximum_border_length ( u ) n = len ( u ) if n % ( n - f [ - 1 ] ) == 0 : return n // ( n - f [ - 1 ] ) return 1
Power string by Knuth - Morris - Pratt
19,914
def matrix_mult_opt_order ( M ) : n = len ( M ) r = [ len ( Mi ) for Mi in M ] c = [ len ( Mi [ 0 ] ) for Mi in M ] opt = [ [ 0 for j in range ( n ) ] for i in range ( n ) ] arg = [ [ None for j in range ( n ) ] for i in range ( n ) ] for j_i in range ( 1 , n ) : for i in range ( n - j_i ) : j = i + j_i opt [ i ] [ j ] = float ( 'inf' ) for k in range ( i , j ) : alt = opt [ i ] [ k ] + opt [ k + 1 ] [ j ] + r [ i ] * c [ k ] * c [ j ] if opt [ i ] [ j ] > alt : opt [ i ] [ j ] = alt arg [ i ] [ j ] = k return opt , arg
Matrix chain multiplication optimal order
19,915
def matrix_chain_mult ( M ) : opt , arg = matrix_mult_opt_order ( M ) return _apply_order ( M , arg , 0 , len ( M ) - 1 )
Matrix chain multiplication
19,916
def levenshtein ( x , y ) : n = len ( x ) m = len ( y ) A = [ [ i + j for j in range ( m + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n ) : for j in range ( m ) : A [ i + 1 ] [ j + 1 ] = min ( A [ i ] [ j + 1 ] + 1 , A [ i + 1 ] [ j ] + 1 , A [ i ] [ j ] + int ( x [ i ] != y [ j ] ) ) return A [ n ] [ m ]
Levenshtein edit distance
19,917
def gale_shapley ( men , women ) : n = len ( men ) assert n == len ( women ) current_suitor = [ 0 ] * n spouse = [ None ] * n rank = [ [ 0 ] * n for j in range ( n ) ] for j in range ( n ) : for r in range ( n ) : rank [ j ] [ women [ j ] [ r ] ] = r singles = deque ( range ( n ) ) while singles : i = singles . popleft ( ) j = men [ i ] [ current_suitor [ i ] ] current_suitor [ i ] += 1 if spouse [ j ] is None : spouse [ j ] = i elif rank [ j ] [ spouse [ j ] ] < rank [ j ] [ i ] : singles . append ( i ) else : singles . put ( spouse [ j ] ) spouse [ j ] = i return spouse
Stable matching by Gale - Shapley
19,918
def eulerian_tour_directed ( graph ) : P = [ ] Q = [ 0 ] R = [ ] succ = [ 0 ] * len ( graph ) while Q : node = Q . pop ( ) P . append ( node ) while succ [ node ] < len ( graph [ node ] ) : neighbor = graph [ node ] [ succ [ node ] ] succ [ node ] += 1 R . append ( neighbor ) node = neighbor while R : Q . append ( R . pop ( ) ) return P
Eulerian tour on a directed graph
19,919
def write_cycle ( filename , graph , cycle , directed ) : n = len ( graph ) weight = [ [ float ( 'inf' ) ] * n for _ in range ( n ) ] for r in range ( 1 , len ( cycle ) ) : weight [ cycle [ r - 1 ] ] [ cycle [ r ] ] = r if not directed : weight [ cycle [ r ] ] [ cycle [ r - 1 ] ] = r write_graph ( filename , graph , arc_label = weight , directed = directed )
Write an eulerian tour in DOT format
19,920
def random_eulerien_graph ( n ) : graphe = [ [ ] for _ in range ( n ) ] for v in range ( n - 1 ) : noeuds = random . sample ( range ( v + 1 , n ) , random . choice ( range ( 0 if len ( graphe [ v ] ) % 2 == 0 else 1 , ( n - v ) , 2 ) ) ) graphe [ v ] . extend ( noeuds ) for w in graphe [ v ] : if w > v : graphe [ w ] . append ( v ) return graphe
Generates some random eulerian graph
19,921
def longest_common_subsequence ( x , y ) : n = len ( x ) m = len ( y ) A = [ [ 0 for j in range ( m + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n ) : for j in range ( m ) : if x [ i ] == y [ j ] : A [ i + 1 ] [ j + 1 ] = A [ i ] [ j ] + 1 else : A [ i + 1 ] [ j + 1 ] = max ( A [ i ] [ j + 1 ] , A [ i + 1 ] [ j ] ) sol = [ ] i , j = n , m while A [ i ] [ j ] > 0 : if A [ i ] [ j ] == A [ i - 1 ] [ j ] : i -= 1 elif A [ i ] [ j ] == A [ i ] [ j - 1 ] : j -= 1 else : i -= 1 j -= 1 sol . append ( x [ i ] ) return '' . join ( sol [ : : - 1 ] )
Longest common subsequence
19,922
def kuhn_munkres ( G ) : assert len ( G ) == len ( G [ 0 ] ) n = len ( G ) mu = [ None ] * n mv = [ None ] * n lu = [ max ( row ) for row in G ] lv = [ 0 ] * n for u0 in range ( n ) : if mu [ u0 ] is None : while True : au = [ False ] * n av = [ False ] * n if improve_matching ( G , u0 , mu , mv , au , av , lu , lv ) : break improve_labels ( G , au , av , lu , lv ) return ( mu , sum ( lu ) + sum ( lv ) )
Maximum profit perfect matching
19,923
def kuhn_munkres ( G , TOLERANCE = 1e-6 ) : nU = len ( G ) U = range ( nU ) nV = len ( G [ 0 ] ) V = range ( nV ) assert nU <= nV mu = [ None ] * nU mv = [ None ] * nV lu = [ max ( row ) for row in G ] lv = [ 0 ] * nV for root in U : au = [ False ] * nU au [ root ] = True Av = [ None ] * nV slack = [ ( lu [ root ] + lv [ v ] - G [ root ] [ v ] , root ) for v in V ] while True : ( ( delta , u ) , v ) = min ( ( slack [ v ] , v ) for v in V if Av [ v ] is None ) assert au [ u ] if delta > TOLERANCE : for u0 in U : if au [ u0 ] : lu [ u0 ] -= delta for v0 in V : if Av [ v0 ] is not None : lv [ v0 ] += delta else : ( val , arg ) = slack [ v0 ] slack [ v0 ] = ( val - delta , arg ) assert abs ( lu [ u ] + lv [ v ] - G [ u ] [ v ] ) <= TOLERANCE Av [ v ] = u if mv [ v ] is None : break u1 = mv [ v ] assert not au [ u1 ] au [ u1 ] = True for v1 in V : if Av [ v1 ] is None : alt = ( lu [ u1 ] + lv [ v1 ] - G [ u1 ] [ v1 ] , u1 ) if slack [ v1 ] > alt : slack [ v1 ] = alt while v is not None : u = Av [ v ] prec = mu [ u ] mv [ v ] = u mu [ u ] = v v = prec return ( mu , sum ( lu ) + sum ( lv ) )
Maximum profit bipartite matching by Kuhn - Munkres
19,924
def interval_cover ( I ) : S = [ ] for start , end in sorted ( I , key = lambda v : v [ 1 ] ) : if not S or S [ - 1 ] < start : S . append ( end ) return S
Minimum interval cover
19,925
def dist01 ( graph , weight , source = 0 , target = None ) : n = len ( graph ) dist = [ float ( 'inf' ) ] * n prec = [ None ] * n black = [ False ] * n dist [ source ] = 0 gray = deque ( [ source ] ) while gray : node = gray . pop ( ) if black [ node ] : continue black [ node ] = True if node == target : break for neighbor in graph [ node ] : ell = dist [ node ] + weight [ node ] [ neighbor ] if black [ neighbor ] or dist [ neighbor ] <= ell : continue dist [ neighbor ] = ell prec [ neighbor ] = node if weight [ node ] [ neighbor ] == 0 : gray . append ( neighbor ) else : gray . appendleft ( neighbor ) return dist , prec
Shortest path in a 0 1 weighted graph
19,926
def max_interval_intersec ( S ) : B = ( [ ( left , + 1 ) for left , right in S ] + [ ( right , - 1 ) for left , right in S ] ) B . sort ( ) c = 0 best = ( c , None ) for x , d in B : c += d if best [ 0 ] < c : best = ( c , x ) return best
determine a value that is contained in a largest number of given intervals
19,927
def dist_grid ( grid , source , target = None ) : rows = len ( grid ) cols = len ( grid [ 0 ] ) dirs = [ ( 0 , + 1 , '>' ) , ( 0 , - 1 , '<' ) , ( + 1 , 0 , 'v' ) , ( - 1 , 0 , '^' ) ] i , j = source grid [ i ] [ j ] = 's' Q = deque ( ) Q . append ( source ) while Q : i1 , j1 = Q . popleft ( ) for di , dj , symbol in dirs : i2 = i1 + di j2 = j1 + dj if not ( 0 <= i2 and i2 < rows and 0 <= j2 and j2 < cols ) : continue if grid [ i2 ] [ j2 ] != ' ' : continue grid [ i2 ] [ j2 ] = symbol if ( i2 , j2 ) == target : grid [ i2 ] [ j2 ] = 't' return Q . append ( ( i2 , j2 ) )
Distances in a grid by BFS
19,928
def _range_min ( self , p , start , span , i , k ) : if start + span <= i or k <= start : return self . INF if i <= start and start + span <= k : return self . s [ p ] left = self . _range_min ( 2 * p , start , span // 2 , i , k ) right = self . _range_min ( 2 * p + 1 , start + span // 2 , span // 2 , i , k ) return min ( left , right )
returns the minimum in t in the indexes [ i k ) intersected with [ start start + span ) . p is the node associated to the later interval .
19,929
def _clear ( self , node , left , right ) : if self . lazyset [ node ] is not None : val = self . lazyset [ node ] self . minval [ node ] = val self . maxval [ node ] = val self . sumval [ node ] = val * ( right - left ) self . lazyset [ node ] = None if left < right - 1 : self . lazyset [ 2 * node ] = val self . lazyadd [ 2 * node ] = 0 self . lazyset [ 2 * node + 1 ] = val self . lazyadd [ 2 * node + 1 ] = 0 if self . lazyadd [ node ] != 0 : val = self . lazyadd [ node ] self . minval [ node ] += val self . maxval [ node ] += val self . sumval [ node ] += val * ( right - left ) self . lazyadd [ node ] = 0 if left < right - 1 : self . lazyadd [ 2 * node ] += val self . lazyadd [ 2 * node + 1 ] += val
propagates the lazy updates for this node to the subtrees . as a result the maxval minval sumval values for the node are up to date .
19,930
def left_right_inversions ( tab ) : n = len ( tab ) left = [ 0 ] * n right = [ 0 ] * n tmp = [ None ] * n rank = list ( range ( n ) ) _merge_sort ( tab , tmp , rank , left , right , 0 , n ) return left , right
Compute left and right inversions of each element of a table .
19,931
def interval_tree ( intervals ) : if intervals == [ ] : return None center = intervals [ len ( intervals ) // 2 ] [ 0 ] L = [ ] R = [ ] C = [ ] for I in intervals : if I [ 1 ] <= center : L . append ( I ) elif center < I [ 0 ] : R . append ( I ) else : C . append ( I ) by_low = sorted ( ( I [ 0 ] , I ) for I in C ) by_high = sorted ( ( I [ 1 ] , I ) for I in C ) IL = interval_tree ( L ) IR = interval_tree ( R ) return _Node ( center , by_low , by_high , IL , IR )
Construct an interval tree
19,932
def intervals_containing ( t , p ) : INF = float ( 'inf' ) if t is None : return [ ] if p < t . center : retval = intervals_containing ( t . left , p ) j = bisect_right ( t . by_low , ( p , ( INF , INF ) ) ) for i in range ( j ) : retval . append ( t . by_low [ i ] [ 1 ] ) else : retval = intervals_containing ( t . right , p ) i = bisect_right ( t . by_high , ( p , ( INF , INF ) ) ) for j in range ( i , len ( t . by_high ) ) : retval . append ( t . by_high [ j ] [ 1 ] ) return retval
Query the interval tree
19,933
def andrew ( S ) : S . sort ( ) top = [ ] bot = [ ] for p in S : while len ( top ) >= 2 and not left_turn ( p , top [ - 1 ] , top [ - 2 ] ) : top . pop ( ) top . append ( p ) while len ( bot ) >= 2 and not left_turn ( bot [ - 2 ] , bot [ - 1 ] , p ) : bot . pop ( ) bot . append ( p ) return bot [ : - 1 ] + top [ : 0 : - 1 ]
Convex hull by Andrew
19,934
def discrete_binary_search ( tab , lo , hi ) : while lo < hi : mid = lo + ( hi - lo ) // 2 if tab [ mid ] : hi = mid else : lo = mid + 1 return lo
Binary search in a table
19,935
def continuous_binary_search ( f , lo , hi , gap = 1e-4 ) : while hi - lo > gap : mid = ( lo + hi ) / 2. if f ( mid ) : hi = mid else : lo = mid return lo
Binary search for a function
19,936
def ternary_search ( f , lo , hi , gap = 1e-10 ) : while hi - lo > gap : step = ( hi - lo ) / 3. if f ( lo + step ) < f ( lo + 2 * step ) : lo += step else : hi -= step return lo
Ternary maximum search for a bitonic function
19,937
def anagrams ( w ) : w = list ( set ( w ) ) d = { } for i in range ( len ( w ) ) : s = '' . join ( sorted ( w [ i ] ) ) if s in d : d [ s ] . append ( i ) else : d [ s ] = [ i ] answer = [ ] for s in d : if len ( d [ s ] ) > 1 : answer . append ( [ w [ i ] for i in d [ s ] ] ) return answer
group a list of words into anagrams
19,938
def subset_sum ( x , R ) : k = len ( x ) // 2 Y = [ v for v in part_sum ( x [ : k ] ) ] Z = [ R - v for v in part_sum ( x [ k : ] ) ] Y . sort ( ) Z . sort ( ) i = 0 j = 0 while i < len ( Y ) and j < len ( Z ) : if Y [ i ] == Z [ j ] : return True elif Y [ i ] < Z [ j ] : i += 1 else : j += 1 return False
Subsetsum by splitting
19,939
def tarjan_recursif ( graph ) : global sccp , waiting , dfs_time , dfs_num sccp = [ ] waiting = [ ] waits = [ False ] * len ( graph ) dfs_time = 0 dfs_num = [ None ] * len ( graph ) def dfs ( node ) : global sccp , waiting , dfs_time , dfs_num waiting . append ( node ) waits [ node ] = True dfs_num [ node ] = dfs_time dfs_time += 1 dfs_min = dfs_num [ node ] for neighbor in graph [ node ] : if dfs_num [ neighbor ] is None : dfs_min = min ( dfs_min , dfs ( neighbor ) ) elif waits [ neighbor ] and dfs_min > dfs_num [ neighbor ] : dfs_min = dfs_num [ neighbor ] if dfs_min == dfs_num [ node ] : sccp . append ( [ ] ) while True : u = waiting . pop ( ) waits [ u ] = False sccp [ - 1 ] . append ( u ) if u == node : break return dfs_min for node in range ( len ( graph ) ) : if dfs_num [ node ] is None : dfs ( node ) return sccp
Strongly connected components by Tarjan recursive implementation
19,940
def tarjan ( graph ) : n = len ( graph ) dfs_num = [ None ] * n dfs_min = [ n ] * n waiting = [ ] waits = [ False ] * n sccp = [ ] dfs_time = 0 times_seen = [ - 1 ] * n for start in range ( n ) : if times_seen [ start ] == - 1 : times_seen [ start ] = 0 to_visit = [ start ] while to_visit : node = to_visit [ - 1 ] if times_seen [ node ] == 0 : dfs_num [ node ] = dfs_time dfs_min [ node ] = dfs_time dfs_time += 1 waiting . append ( node ) waits [ node ] = True children = graph [ node ] if times_seen [ node ] == len ( children ) : to_visit . pop ( ) dfs_min [ node ] = dfs_num [ node ] for child in children : if waits [ child ] and dfs_min [ child ] < dfs_min [ node ] : dfs_min [ node ] = dfs_min [ child ] if dfs_min [ node ] == dfs_num [ node ] : component = [ ] while True : u = waiting . pop ( ) waits [ u ] = False component . append ( u ) if u == node : break sccp . append ( component ) else : child = children [ times_seen [ node ] ] times_seen [ node ] += 1 if times_seen [ child ] == - 1 : times_seen [ child ] = 0 to_visit . append ( child ) return sccp
Strongly connected components by Tarjan iterative implementation
19,941
def kosaraju ( graph ) : n = len ( graph ) order = [ ] sccp = [ ] kosaraju_dfs ( graph , range ( n ) , order , [ ] ) kosaraju_dfs ( reverse ( graph ) , order [ : : - 1 ] , [ ] , sccp ) return sccp [ : : - 1 ]
Strongly connected components by Kosaraju
19,942
def get_template_dirs ( ) : temp_glob = rel_to_cwd ( 'templates' , '**' , 'templates' , 'config.yaml' ) temp_groups = glob ( temp_glob ) temp_groups = [ get_parent_dir ( path , 2 ) for path in temp_groups ] return set ( temp_groups )
Return a set of all template directories .
19,943
def get_scheme_dirs ( ) : scheme_glob = rel_to_cwd ( 'schemes' , '**' , '*.yaml' ) scheme_groups = glob ( scheme_glob ) scheme_groups = [ get_parent_dir ( path ) for path in scheme_groups ] return set ( scheme_groups )
Return a set of all scheme directories .
19,944
def build ( templates = None , schemes = None , base_output_dir = None ) : template_dirs = templates or get_template_dirs ( ) scheme_files = get_scheme_files ( schemes ) base_output_dir = base_output_dir or rel_to_cwd ( 'output' ) if not template_dirs or not scheme_files : raise LookupError try : os . makedirs ( base_output_dir ) except FileExistsError : pass if not os . access ( base_output_dir , os . W_OK ) : raise PermissionError templates = [ TemplateGroup ( path ) for path in template_dirs ] build_from_job_list ( scheme_files , templates , base_output_dir ) print ( 'Finished building process.' )
Main build function to initiate building process .
19,945
def write_sources_file ( ) : file_content = ( 'schemes: ' 'https://github.com/chriskempson/base16-schemes-source.git\n' 'templates: ' 'https://github.com/chriskempson/base16-templates-source.git' ) file_path = rel_to_cwd ( 'sources.yaml' ) with open ( file_path , 'w' ) as file_ : file_ . write ( file_content )
Write a sources . yaml file to current working dir .
19,946
def get_yaml_dict ( yaml_file ) : try : with open ( yaml_file , 'r' ) as file_ : yaml_dict = yaml . safe_load ( file_ . read ( ) ) or { } return yaml_dict except FileNotFoundError : return { }
Return a yaml_dict from reading yaml_file . If yaml_file is empty or doesn t exist return an empty dict instead .
19,947
def _get_temp ( self , content ) : temp = None for line in content . splitlines ( ) : if not temp : match = TEMP_NEEDLE . match ( line ) if match : temp = match . group ( 1 ) . strip ( ) continue else : match = TEMP_END_NEEDLE . match ( line ) if match : return temp raise IndexError ( self . path )
Get the string that points to a specific base16 scheme .
19,948
def get_colorscheme ( self , scheme_file ) : scheme = get_yaml_dict ( scheme_file ) scheme_slug = builder . slugify ( scheme_file ) builder . format_scheme ( scheme , scheme_slug ) try : temp_base , temp_sub = self . temp . split ( '##' ) except ValueError : temp_base , temp_sub = ( self . temp . strip ( '##' ) , 'default' ) temp_path = rel_to_cwd ( 'templates' , temp_base ) temp_group = builder . TemplateGroup ( temp_path ) try : single_temp = temp_group . templates [ temp_sub ] except KeyError : raise FileNotFoundError ( None , None , self . path + ' (sub-template)' ) colorscheme = pystache . render ( single_temp [ 'parsed' ] , scheme ) return colorscheme
Return a string object with the colorscheme that is to be inserted .
19,949
def write ( self ) : with open ( self . path , 'w' ) as file_ : file_ . write ( self . content )
Write content back to file .
19,950
def update_mode ( arg_namespace ) : try : updater . update ( custom_sources = arg_namespace . custom ) except ( PermissionError , FileNotFoundError ) as exception : if isinstance ( exception , PermissionError ) : print ( 'No write permission for current working directory.' ) if isinstance ( exception , FileNotFoundError ) : print ( 'Necessary resources for updating not found in current ' 'working directory.' )
Check command line arguments and run update function .
19,951
def get_address_details ( address , coin_symbol = 'btc' , txn_limit = None , api_key = None , before_bh = None , after_bh = None , unspent_only = False , show_confidence = False , confirmations = 0 , include_script = False ) : assert is_valid_address_for_coinsymbol ( b58_address = address , coin_symbol = coin_symbol ) , address assert isinstance ( show_confidence , bool ) , show_confidence url = make_url ( coin_symbol , ** dict ( addrs = address ) ) params = { } if txn_limit : params [ 'limit' ] = txn_limit if api_key : params [ 'token' ] = api_key if before_bh : params [ 'before' ] = before_bh if after_bh : params [ 'after' ] = after_bh if confirmations : params [ 'confirmations' ] = confirmations if unspent_only : params [ 'unspentOnly' ] = 'true' if show_confidence : params [ 'includeConfidence' ] = 'true' if include_script : params [ 'includeScript' ] = 'true' r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) r = get_valid_json ( r ) return _clean_tx ( response_dict = r )
Takes an address and coin_symbol and returns the address details
19,952
def get_addresses_details ( address_list , coin_symbol = 'btc' , txn_limit = None , api_key = None , before_bh = None , after_bh = None , unspent_only = False , show_confidence = False , confirmations = 0 , include_script = False ) : for address in address_list : assert is_valid_address_for_coinsymbol ( b58_address = address , coin_symbol = coin_symbol ) , address assert isinstance ( show_confidence , bool ) , show_confidence kwargs = dict ( addrs = ';' . join ( [ str ( addr ) for addr in address_list ] ) ) url = make_url ( coin_symbol , ** kwargs ) params = { } if txn_limit : params [ 'limit' ] = txn_limit if api_key : params [ 'token' ] = api_key if before_bh : params [ 'before' ] = before_bh if after_bh : params [ 'after' ] = after_bh if confirmations : params [ 'confirmations' ] = confirmations if unspent_only : params [ 'unspentOnly' ] = 'true' if show_confidence : params [ 'includeConfidence' ] = 'true' if include_script : params [ 'includeScript' ] = 'true' r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) r = get_valid_json ( r ) return [ _clean_tx ( response_dict = d ) for d in r ]
Batch version of get_address_details method
19,953
def get_wallet_transactions ( wallet_name , api_key , coin_symbol = 'btc' , before_bh = None , after_bh = None , txn_limit = None , omit_addresses = False , unspent_only = False , show_confidence = False , confirmations = 0 ) : assert len ( wallet_name ) <= 25 , wallet_name assert api_key assert is_valid_coin_symbol ( coin_symbol = coin_symbol ) assert isinstance ( show_confidence , bool ) , show_confidence assert isinstance ( omit_addresses , bool ) , omit_addresses url = make_url ( coin_symbol , ** dict ( addrs = wallet_name ) ) params = { } if txn_limit : params [ 'limit' ] = txn_limit if api_key : params [ 'token' ] = api_key if before_bh : params [ 'before' ] = before_bh if after_bh : params [ 'after' ] = after_bh if confirmations : params [ 'confirmations' ] = confirmations if unspent_only : params [ 'unspentOnly' ] = 'true' if show_confidence : params [ 'includeConfidence' ] = 'true' if omit_addresses : params [ 'omitWalletAddresses' ] = 'true' r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return _clean_tx ( get_valid_json ( r ) )
Takes a wallet api_key coin_symbol and returns the wallet s details
19,954
def get_address_overview ( address , coin_symbol = 'btc' , api_key = None ) : assert is_valid_address_for_coinsymbol ( b58_address = address , coin_symbol = coin_symbol ) url = make_url ( coin_symbol , 'addrs' , ** { address : 'balance' } ) params = { } if api_key : params [ 'token' ] = api_key r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Takes an address and coin_symbol and return the address details
19,955
def generate_new_address ( coin_symbol = 'btc' , api_key = None ) : assert api_key , 'api_key required' assert is_valid_coin_symbol ( coin_symbol ) if coin_symbol not in ( 'btc-testnet' , 'bcy' ) : WARNING_MSG = [ 'Generating private key details server-side.' , 'You really should do this client-side.' , 'See https://github.com/sbuss/bitmerchant for an example.' , ] print ( ' ' . join ( WARNING_MSG ) ) url = make_url ( coin_symbol , 'addrs' ) params = { 'token' : api_key } r = requests . post ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Takes a coin_symbol and returns a new address with it s public and private keys .
19,956
def get_transaction_details ( tx_hash , coin_symbol = 'btc' , limit = None , tx_input_offset = None , tx_output_offset = None , include_hex = False , show_confidence = False , confidence_only = False , api_key = None ) : assert is_valid_hash ( tx_hash ) , tx_hash assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol added = 'txs/{}{}' . format ( tx_hash , '/confidence' if confidence_only else '' ) url = make_url ( coin_symbol , added ) params = { } if api_key : params [ 'token' ] = api_key if limit : params [ 'limit' ] = limit if tx_input_offset : params [ 'inStart' ] = tx_input_offset if tx_output_offset : params [ 'outStart' ] = tx_output_offset if include_hex : params [ 'includeHex' ] = 'true' if show_confidence and not confidence_only : params [ 'includeConfidence' ] = 'true' r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_dict = get_valid_json ( r ) if 'error' not in response_dict and not confidence_only : if response_dict [ 'block_height' ] > 0 : response_dict [ 'confirmed' ] = parser . parse ( response_dict [ 'confirmed' ] ) else : response_dict [ 'block_height' ] = None response_dict [ 'confirmed' ] = None response_dict [ 'received' ] = parser . parse ( response_dict [ 'received' ] ) return response_dict
Takes a tx_hash coin_symbol and limit and returns the transaction details
19,957
def get_transactions_details ( tx_hash_list , coin_symbol = 'btc' , limit = None , api_key = None ) : for tx_hash in tx_hash_list : assert is_valid_hash ( tx_hash ) assert is_valid_coin_symbol ( coin_symbol ) if len ( tx_hash_list ) == 0 : return [ ] elif len ( tx_hash_list ) == 1 : return [ get_transaction_details ( tx_hash = tx_hash_list [ 0 ] , coin_symbol = coin_symbol , limit = limit , api_key = api_key ) ] url = make_url ( coin_symbol , ** dict ( txs = ';' . join ( tx_hash_list ) ) ) params = { } if api_key : params [ 'token' ] = api_key if limit : params [ 'limit' ] = limit r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_dict_list = get_valid_json ( r ) cleaned_dict_list = [ ] for response_dict in response_dict_list : if 'error' not in response_dict : if response_dict [ 'block_height' ] > 0 : response_dict [ 'confirmed' ] = parser . parse ( response_dict [ 'confirmed' ] ) else : response_dict [ 'confirmed' ] = None response_dict [ 'block_height' ] = None response_dict [ 'received' ] = parser . parse ( response_dict [ 'received' ] ) cleaned_dict_list . append ( response_dict ) return cleaned_dict_list
Takes a list of tx_hashes coin_symbol and limit and returns the transaction details
19,958
def get_num_confirmations ( tx_hash , coin_symbol = 'btc' , api_key = None ) : return get_transaction_details ( tx_hash = tx_hash , coin_symbol = coin_symbol , limit = 1 , api_key = api_key ) . get ( 'confirmations' )
Given a tx_hash return the number of confirmations that transactions has .
19,959
def get_broadcast_transactions ( coin_symbol = 'btc' , limit = 10 , api_key = None ) : url = make_url ( coin_symbol , 'txs' ) params = { } if api_key : params [ 'token' ] = api_key if limit : params [ 'limit' ] = limit r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_dict = get_valid_json ( r ) unconfirmed_txs = [ ] for unconfirmed_tx in response_dict : unconfirmed_tx [ 'received' ] = parser . parse ( unconfirmed_tx [ 'received' ] ) unconfirmed_txs . append ( unconfirmed_tx ) return unconfirmed_txs
Get a list of broadcast but unconfirmed transactions Similar to bitcoind s getrawmempool method
19,960
def get_block_overview ( block_representation , coin_symbol = 'btc' , txn_limit = None , txn_offset = None , api_key = None ) : assert is_valid_coin_symbol ( coin_symbol ) assert is_valid_block_representation ( block_representation = block_representation , coin_symbol = coin_symbol ) url = make_url ( coin_symbol , ** dict ( blocks = block_representation ) ) params = { } if api_key : params [ 'token' ] = api_key if txn_limit : params [ 'limit' ] = txn_limit if txn_offset : params [ 'txstart' ] = txn_offset r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_dict = get_valid_json ( r ) if 'error' in response_dict : return response_dict return _clean_block ( response_dict = response_dict )
Takes a block_representation coin_symbol and txn_limit and gets an overview of that block including up to X transaction ids . Note that block_representation may be the block number or block hash
19,961
def get_blocks_overview ( block_representation_list , coin_symbol = 'btc' , txn_limit = None , api_key = None ) : for block_representation in block_representation_list : assert is_valid_block_representation ( block_representation = block_representation , coin_symbol = coin_symbol ) assert is_valid_coin_symbol ( coin_symbol ) blocks = ';' . join ( [ str ( x ) for x in block_representation_list ] ) url = make_url ( coin_symbol , ** dict ( blocks = blocks ) ) logger . info ( url ) params = { } if api_key : params [ 'token' ] = api_key if txn_limit : params [ 'limit' ] = txn_limit r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) r = get_valid_json ( r ) return [ _clean_tx ( response_dict = d ) for d in r ]
Batch request version of get_blocks_overview
19,962
def get_merkle_root ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'mrkl_root' ]
Takes a block_representation and returns the merkle root
19,963
def get_bits ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'bits' ]
Takes a block_representation and returns the number of bits
19,964
def get_nonce ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'bits' ]
Takes a block_representation and returns the nonce
19,965
def get_prev_block_hash ( block_representation , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'prev_block' ]
Takes a block_representation and returns the previous block hash
19,966
def get_block_hash ( block_height , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_height , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'hash' ]
Takes a block_height and returns the block_hash
19,967
def get_block_height ( block_hash , coin_symbol = 'btc' , api_key = None ) : return get_block_overview ( block_representation = block_hash , coin_symbol = coin_symbol , txn_limit = 1 , api_key = api_key ) [ 'height' ]
Takes a block_hash and returns the block_height
19,968
def get_block_details ( block_representation , coin_symbol = 'btc' , txn_limit = None , txn_offset = None , in_out_limit = None , api_key = None ) : assert is_valid_coin_symbol ( coin_symbol ) block_overview = get_block_overview ( block_representation = block_representation , coin_symbol = coin_symbol , txn_limit = txn_limit , txn_offset = txn_offset , api_key = api_key , ) if 'error' in block_overview : return block_overview txids_to_lookup = block_overview [ 'txids' ] txs_details = get_transactions_details ( tx_hash_list = txids_to_lookup , coin_symbol = coin_symbol , limit = in_out_limit , api_key = api_key , ) if 'error' in txs_details : return txs_details txids_comparator_dict = { } for cnt , tx_id in enumerate ( txids_to_lookup ) : txids_comparator_dict [ tx_id ] = cnt block_overview [ 'txids' ] = sorted ( txs_details , key = lambda k : txids_comparator_dict . get ( k . get ( 'hash' ) , 9999 ) , ) return block_overview
Takes a block_representation coin_symbol and txn_limit and 1 ) Gets the block overview 2 ) Makes a separate API call to get specific data on txn_limit transactions
19,969
def get_blockchain_fee_estimates ( coin_symbol = 'btc' , api_key = None ) : overview = get_blockchain_overview ( coin_symbol = coin_symbol , api_key = api_key ) return { 'high_fee_per_kb' : overview [ 'high_fee_per_kb' ] , 'medium_fee_per_kb' : overview [ 'medium_fee_per_kb' ] , 'low_fee_per_kb' : overview [ 'low_fee_per_kb' ] , }
Returns high medium and low fee estimates for a given blockchain .
19,970
def get_forwarding_address_details ( destination_address , api_key , callback_url = None , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) assert api_key , 'api_key required' url = make_url ( coin_symbol , 'payments' ) logger . info ( url ) params = { 'token' : api_key } data = { 'destination' : destination_address , } if callback_url : data [ 'callback_url' ] = callback_url r = requests . post ( url , json = data , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Give a destination address and return the details of the input address that will automatically forward to the destination address
19,971
def get_forwarding_address ( destination_address , api_key , callback_url = None , coin_symbol = 'btc' ) : assert api_key , 'api_key required' resp_dict = get_forwarding_address_details ( destination_address = destination_address , api_key = api_key , callback_url = callback_url , coin_symbol = coin_symbol ) return resp_dict [ 'input_address' ]
Give a destination address and return an input address that will automatically forward to the destination address . See get_forwarding_address_details if you also need the forwarding address ID .
19,972
def delete_forwarding_address ( payment_id , coin_symbol = 'btc' , api_key = None ) : assert payment_id , 'payment_id required' assert is_valid_coin_symbol ( coin_symbol ) assert api_key , 'api_key required' params = { 'token' : api_key } url = make_url ( ** dict ( payments = payment_id ) ) r = requests . delete ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r , allow_204 = True )
Delete a forwarding address on a specific blockchain using its payment id
19,973
def send_faucet_coins ( address_to_fund , satoshis , api_key , coin_symbol = 'bcy' ) : assert coin_symbol in ( 'bcy' , 'btc-testnet' ) assert is_valid_address_for_coinsymbol ( b58_address = address_to_fund , coin_symbol = coin_symbol ) assert satoshis > 0 assert api_key , 'api_key required' url = make_url ( coin_symbol , 'faucet' ) data = { 'address' : address_to_fund , 'amount' : satoshis , } params = { 'token' : api_key } r = requests . post ( url , json = data , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Send yourself test coins on the bitcoin or blockcypher testnet
19,974
def list_wallet_names ( api_key , is_hd_wallet = False , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key params = { 'token' : api_key } kwargs = dict ( wallets = 'hd' if is_hd_wallet else '' ) url = make_url ( coin_symbol , ** kwargs ) r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Get all the wallets belonging to an API key
19,975
def create_wallet_from_address ( wallet_name , address , api_key , coin_symbol = 'btc' ) : assert is_valid_address_for_coinsymbol ( address , coin_symbol ) assert api_key assert is_valid_wallet_name ( wallet_name ) , wallet_name data = { 'name' : wallet_name , 'addresses' : [ address , ] , } params = { 'token' : api_key } url = make_url ( coin_symbol , 'wallets' ) r = requests . post ( url , json = data , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Create a new wallet with one address
19,976
def get_wallet_addresses ( wallet_name , api_key , is_hd_wallet = False , zero_balance = None , used = None , omit_addresses = False , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) assert api_key assert len ( wallet_name ) <= 25 , wallet_name assert zero_balance in ( None , True , False ) assert used in ( None , True , False ) assert isinstance ( omit_addresses , bool ) , omit_addresses params = { 'token' : api_key } kwargs = { 'hd/' if is_hd_wallet else '' : wallet_name } url = make_url ( coin_symbol , 'wallets' , ** kwargs ) if zero_balance is True : params [ 'zerobalance' ] = 'true' elif zero_balance is False : params [ 'zerobalance' ] = 'false' if used is True : params [ 'used' ] = 'true' elif used is False : params [ 'used' ] = 'false' if omit_addresses : params [ 'omitWalletAddresses' ] = 'true' r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r )
Returns a list of wallet addresses as well as some meta - data
19,977
def make_tx_signatures ( txs_to_sign , privkey_list , pubkey_list ) : assert len ( privkey_list ) == len ( pubkey_list ) == len ( txs_to_sign ) signatures = [ ] for cnt , tx_to_sign in enumerate ( txs_to_sign ) : sig = der_encode_sig ( * ecdsa_raw_sign ( tx_to_sign . rstrip ( ' \t\r\n\0' ) , privkey_list [ cnt ] ) ) err_msg = 'Bad Signature: sig %s for tx %s with pubkey %s' % ( sig , tx_to_sign , pubkey_list [ cnt ] , ) assert ecdsa_raw_verify ( tx_to_sign , der_decode_sig ( sig ) , pubkey_list [ cnt ] ) , err_msg signatures . append ( sig ) return signatures
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
19,978
def broadcast_signed_transaction ( unsigned_tx , signatures , pubkeys , coin_symbol = 'btc' , api_key = None ) : assert 'errors' not in unsigned_tx , unsigned_tx assert api_key , 'api_key required' url = make_url ( coin_symbol , ** dict ( txs = 'send' ) ) data = unsigned_tx . copy ( ) data [ 'signatures' ] = signatures data [ 'pubkeys' ] = pubkeys params = { 'token' : api_key } r = requests . post ( url , params = params , json = data , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_dict = get_valid_json ( r ) if response_dict . get ( 'tx' ) and response_dict . get ( 'received' ) : response_dict [ 'tx' ] [ 'received' ] = parser . parse ( response_dict [ 'tx' ] [ 'received' ] ) return response_dict
Broadcasts the transaction from create_unsigned_tx
19,979
def simple_spend ( from_privkey , to_address , to_satoshis , change_address = None , privkey_is_compressed = True , min_confirmations = 0 , api_key = None , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert isinstance ( to_satoshis , int ) , to_satoshis assert api_key , 'api_key required' if privkey_is_compressed : from_pubkey = compress ( privkey_to_pubkey ( from_privkey ) ) else : from_pubkey = privkey_to_pubkey ( from_privkey ) from_address = pubkey_to_address ( pubkey = from_pubkey , magicbyte = COIN_SYMBOL_MAPPINGS [ coin_symbol ] [ 'vbyte_pubkey' ] , ) inputs = [ { 'address' : from_address } , ] logger . info ( 'inputs: %s' % inputs ) outputs = [ { 'address' : to_address , 'value' : to_satoshis } , ] logger . info ( 'outputs: %s' % outputs ) unsigned_tx = create_unsigned_tx ( inputs = inputs , outputs = outputs , change_address = change_address , coin_symbol = coin_symbol , min_confirmations = min_confirmations , verify_tosigntx = False , include_tosigntx = True , api_key = api_key , ) logger . info ( 'unsigned_tx: %s' % unsigned_tx ) if 'errors' in unsigned_tx : print ( 'TX Error(s): Tx NOT Signed or Broadcast' ) for error in unsigned_tx [ 'errors' ] : print ( error [ 'error' ] ) raise Exception ( 'Build Unsigned TX Error' ) if change_address : change_address_to_use = change_address else : change_address_to_use = from_address tx_is_correct , err_msg = verify_unsigned_tx ( unsigned_tx = unsigned_tx , inputs = inputs , outputs = outputs , sweep_funds = bool ( to_satoshis == - 1 ) , change_address = change_address_to_use , coin_symbol = coin_symbol , ) if not tx_is_correct : print ( unsigned_tx ) raise Exception ( 'TX Verification Error: %s' % err_msg ) privkey_list , pubkey_list = [ ] , [ ] for proposed_input in unsigned_tx [ 'tx' ] [ 'inputs' ] : privkey_list . append ( from_privkey ) pubkey_list . append ( from_pubkey ) assert len ( proposed_input [ 'addresses' ] ) == 1 , proposed_input [ 'addresses' ] logger . info ( 'pubkey_list: %s' % pubkey_list ) tx_signatures = make_tx_signatures ( txs_to_sign = unsigned_tx [ 'tosign' ] , privkey_list = privkey_list , pubkey_list = pubkey_list , ) logger . info ( 'tx_signatures: %s' % tx_signatures ) broadcasted_tx = broadcast_signed_transaction ( unsigned_tx = unsigned_tx , signatures = tx_signatures , pubkeys = pubkey_list , coin_symbol = coin_symbol , api_key = api_key , ) logger . info ( 'broadcasted_tx: %s' % broadcasted_tx ) if 'errors' in broadcasted_tx : print ( 'TX Error(s): Tx May NOT Have Been Broadcast' ) for error in broadcasted_tx [ 'errors' ] : print ( error [ 'error' ] ) print ( broadcasted_tx ) return return broadcasted_tx [ 'tx' ] [ 'hash' ]
Simple method to spend from one single - key address to another .
19,980
def get_metadata ( address = None , tx_hash = None , block_hash = None , api_key = None , private = True , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key or not private , 'Cannot see private metadata without an API key' kwarg = get_valid_metadata_identifier ( coin_symbol = coin_symbol , address = address , tx_hash = tx_hash , block_hash = block_hash , ) url = make_url ( coin_symbol , meta = True , ** kwarg ) params = { 'token' : api_key } if api_key else { 'private' : 'true' } r = requests . get ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) response_dict = get_valid_json ( r ) return response_dict
Get metadata using blockcypher s API .
19,981
def put_metadata ( metadata_dict , address = None , tx_hash = None , block_hash = None , api_key = None , private = True , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key assert metadata_dict and isinstance ( metadata_dict , dict ) , metadata_dict kwarg = get_valid_metadata_identifier ( coin_symbol = coin_symbol , address = address , tx_hash = tx_hash , block_hash = block_hash , ) url = make_url ( coin_symbol , meta = True , ** kwarg ) params = { 'token' : api_key } if private : params [ 'private' ] = 'true' r = requests . put ( url , json = metadata_dict , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r , allow_204 = True )
Embed metadata using blockcypher s API .
19,982
def delete_metadata ( address = None , tx_hash = None , block_hash = None , api_key = None , coin_symbol = 'btc' ) : assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol assert api_key , 'api_key required' kwarg = get_valid_metadata_identifier ( coin_symbol = coin_symbol , address = address , tx_hash = tx_hash , block_hash = block_hash , ) url = make_url ( coin_symbol , meta = True , ** kwarg ) params = { 'token' : api_key } r = requests . delete ( url , params = params , verify = True , timeout = TIMEOUT_IN_SECONDS ) return get_valid_json ( r , allow_204 = True )
Only available for metadata that was embedded privately .
19,983
def to_satoshis ( input_quantity , input_type ) : assert input_type in UNIT_CHOICES , input_type if input_type in ( 'btc' , 'mbtc' , 'bit' ) : satoshis = float ( input_quantity ) * float ( UNIT_MAPPINGS [ input_type ] [ 'satoshis_per' ] ) elif input_type == 'satoshi' : satoshis = input_quantity else : raise Exception ( 'Invalid Unit Choice: %s' % input_type ) return int ( satoshis )
convert to satoshis no rounding
19,984
def get_txn_outputs ( raw_tx_hex , output_addr_list , coin_symbol ) : err_msg = 'Library not able to parse %s transactions' % coin_symbol assert lib_can_deserialize_cs ( coin_symbol ) , err_msg assert isinstance ( output_addr_list , ( list , tuple ) ) for output_addr in output_addr_list : assert is_valid_address ( output_addr ) , output_addr output_addr_set = set ( output_addr_list ) outputs = [ ] deserialized_tx = deserialize ( str ( raw_tx_hex ) ) for out in deserialized_tx . get ( 'outs' , [ ] ) : output = { 'value' : out [ 'value' ] } pubkey_addr = script_to_address ( out [ 'script' ] , vbyte = COIN_SYMBOL_MAPPINGS [ coin_symbol ] [ 'vbyte_pubkey' ] ) script_addr = script_to_address ( out [ 'script' ] , vbyte = COIN_SYMBOL_MAPPINGS [ coin_symbol ] [ 'vbyte_script' ] ) nulldata = out [ 'script' ] if out [ 'script' ] [ 0 : 2 ] == '6a' else None if pubkey_addr in output_addr_set : address = pubkey_addr output [ 'address' ] = address elif script_addr in output_addr_set : address = script_addr output [ 'address' ] = address elif nulldata : output [ 'script' ] = nulldata output [ 'script_type' ] = 'null-data' else : raise Exception ( 'Script %s Does Not Contain a Valid Output Address: %s' % ( out [ 'script' ] , output_addr_set , ) ) outputs . append ( output ) return outputs
Used to verify a transaction hex does what s expected of it .
19,985
def get_blockcypher_walletname_from_mpub ( mpub , subchain_indices = [ ] ) : mpub = mpub . encode ( 'utf-8' ) if subchain_indices : mpub += ',' . join ( [ str ( x ) for x in subchain_indices ] ) . encode ( 'utf-8' ) return 'X%s' % sha256 ( mpub ) . hexdigest ( ) [ : 24 ]
Blockcypher limits wallet names to 25 chars .
19,986
def crl ( self ) : revoked_certs = self . get_revoked_certs ( ) crl = crypto . CRL ( ) now_str = timezone . now ( ) . strftime ( generalized_time ) for cert in revoked_certs : revoked = crypto . Revoked ( ) revoked . set_serial ( bytes_compat ( cert . serial_number ) ) revoked . set_reason ( b'unspecified' ) revoked . set_rev_date ( bytes_compat ( now_str ) ) crl . add_revoked ( revoked ) return crl . export ( self . x509 , self . pkey , days = 1 , digest = b'sha256' )
Returns up to date CRL of this CA
19,987
def crl ( request , pk ) : authenticated = request . user . is_authenticated authenticated = authenticated ( ) if callable ( authenticated ) else authenticated if app_settings . CRL_PROTECTED and not authenticated : return HttpResponse ( _ ( 'Forbidden' ) , status = 403 , content_type = 'text/plain' ) ca = crl . ca_model . objects . get ( pk = pk ) return HttpResponse ( ca . crl , status = 200 , content_type = 'application/x-pem-file' )
returns CRL of a CA
19,988
def font_list ( text = "test" , test = False ) : fonts = set ( FONT_MAP . keys ( ) ) if test : fonts = fonts - set ( TEST_FILTERED_FONTS ) for item in sorted ( list ( fonts ) ) : print ( str ( item ) + " : " ) text_temp = text try : tprint ( text_temp , str ( item ) ) except Exception : print ( FONT_ENVIRONMENT_WARNING )
Print all fonts .
19,989
def art_list ( test = False ) : for i in sorted ( list ( art_dic . keys ( ) ) ) : try : if test : raise Exception print ( i ) aprint ( i ) line ( ) except Exception : print ( ART_ENVIRONMENT_WARNING ) line ( ) if test : break
Print all 1 - Line arts .
19,990
def help_func ( ) : tprint ( "art" ) tprint ( "v" + VERSION ) print ( DESCRIPTION + "\n" ) print ( "Webpage : http://art.shaghighi.ir\n" ) print ( "Help : \n" ) print ( " - list ) print ( " - fonts ) print ( " - test ) print ( " - text 'yourtext' 'font(optional)' ) print ( " - shape 'shapename' ) print ( " - save 'yourtext' 'font(optional)' ) print ( " - all 'yourtext' )
Print help page .
19,991
def aprint ( artname , number = 1 , text = "" ) : print ( art ( artname = artname , number = number , text = text ) )
Print 1 - line art .
19,992
def art ( artname , number = 1 , text = "" ) : if isinstance ( artname , str ) is False : raise artError ( ART_TYPE_ERROR ) artname = artname . lower ( ) arts = sorted ( art_dic . keys ( ) ) if artname == "random" or artname == "rand" or artname == "rnd" : filtered_arts = list ( set ( arts ) - set ( RANDOM_FILTERED_ARTS ) ) artname = random . choice ( filtered_arts ) elif artname not in art_dic . keys ( ) : distance_list = list ( map ( lambda x : distance_calc ( artname , x ) , arts ) ) min_distance = min ( distance_list ) selected_art = arts [ distance_list . index ( min_distance ) ] threshold = max ( len ( artname ) , len ( selected_art ) ) / 2 if min_distance < threshold : artname = selected_art else : raise artError ( ART_NAME_ERROR ) art_value = art_dic [ artname ] if isinstance ( number , int ) is False : raise artError ( NUMBER_TYPE_ERROR ) if isinstance ( art_value , str ) : return ( art_value + " " ) * number if isinstance ( text , str ) is False : raise artError ( TEXT_TYPE_ERROR ) return ( art_value [ 0 ] + text + art_value [ 1 ] + " " ) * number
Return 1 - line art .
19,993
def distance_calc ( s1 , s2 ) : if len ( s1 ) > len ( s2 ) : s1 , s2 = s2 , s1 distances = range ( len ( s1 ) + 1 ) for i2 , c2 in enumerate ( s2 ) : distances_ = [ i2 + 1 ] for i1 , c1 in enumerate ( s1 ) : if c1 == c2 : distances_ . append ( distances [ i1 ] ) else : distances_ . append ( 1 + min ( ( distances [ i1 ] , distances [ i1 + 1 ] , distances_ [ - 1 ] ) ) ) distances = distances_ return distances [ - 1 ]
Calculate Levenshtein distance between two words .
19,994
def wizard_font ( text ) : text_length = len ( text ) if text_length <= TEXT_XLARGE_THRESHOLD : font = random . choice ( XLARGE_WIZARD_FONT ) elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD : font = random . choice ( LARGE_WIZARD_FONT ) elif text_length > TEXT_LARGE_THRESHOLD and text_length <= TEXT_MEDIUM_THRESHOLD : font = random . choice ( MEDIUM_WIZARD_FONT ) else : font = random . choice ( SMALL_WIZARD_FONT ) return font
Check input text length for wizard mode .
19,995
def indirect_font ( font , fonts , text ) : if font == "rnd-small" or font == "random-small" or font == "rand-small" : font = random . choice ( RND_SIZE_DICT [ "small_list" ] ) return font if font == "rnd-medium" or font == "random-medium" or font == "rand-medium" : font = random . choice ( RND_SIZE_DICT [ "medium_list" ] ) return font if font == "rnd-large" or font == "random-large" or font == "rand-large" : font = random . choice ( RND_SIZE_DICT [ "large_list" ] ) return font if font == "rnd-xlarge" or font == "random-xlarge" or font == "rand-xlarge" : font = random . choice ( RND_SIZE_DICT [ "xlarge_list" ] ) return font if font == "random" or font == "rand" or font == "rnd" : filtered_fonts = list ( set ( fonts ) - set ( RANDOM_FILTERED_FONTS ) ) font = random . choice ( filtered_fonts ) return font if font == "wizard" or font == "wiz" or font == "magic" : font = wizard_font ( text ) return font if font == "rnd-na" or font == "random-na" or font == "rand-na" : font = random . choice ( TEST_FILTERED_FONTS ) return font if font not in FONT_MAP . keys ( ) : distance_list = list ( map ( lambda x : distance_calc ( font , x ) , fonts ) ) font = fonts [ distance_list . index ( min ( distance_list ) ) ] return font
Check input font for indirect modes .
19,996
def __word2art ( word , font , chr_ignore , letters ) : split_list = [ ] result_list = [ ] splitter = "\n" for i in word : if ( ord ( i ) == 9 ) or ( ord ( i ) == 32 and font == "block" ) : continue if ( i not in letters . keys ( ) ) : if ( chr_ignore ) : continue else : raise artError ( str ( i ) + " is invalid." ) if len ( letters [ i ] ) == 0 : continue split_list . append ( letters [ i ] . split ( "\n" ) ) if font in [ "mirror" , "mirror_flip" ] : split_list . reverse ( ) if len ( split_list ) == 0 : return "" for i in range ( len ( split_list [ 0 ] ) ) : temp = "" for j in range ( len ( split_list ) ) : if j > 0 and ( i == 1 or i == len ( split_list [ 0 ] ) - 2 ) and font == "block" : temp = temp + " " temp = temp + split_list [ j ] [ i ] result_list . append ( temp ) if "win32" != sys . platform : splitter = "\r\n" result = ( splitter ) . join ( result_list ) if result [ - 1 ] != "\n" : result += splitter return result
Return art word .
19,997
def set_default ( font = DEFAULT_FONT , chr_ignore = True , filename = "art" , print_status = True ) : if isinstance ( font , str ) is False : raise artError ( FONT_TYPE_ERROR ) if isinstance ( chr_ignore , bool ) is False : raise artError ( CHR_IGNORE_TYPE_ERROR ) if isinstance ( filename , str ) is False : raise artError ( FILE_TYPE_ERROR ) if isinstance ( print_status , bool ) is False : raise artError ( PRINT_STATUS_TYPE_ERROR ) tprint . __defaults__ = ( font , chr_ignore ) tsave . __defaults__ = ( font , filename , chr_ignore , print_status ) text2art . __defaults__ = ( font , chr_ignore )
Change text2art tprint and tsave default values .
19,998
def objectgetter ( model , attr_name = 'pk' , field_name = 'pk' ) : def _getter ( request , * view_args , ** view_kwargs ) : if attr_name not in view_kwargs : raise ImproperlyConfigured ( 'Argument {0} is not available. Given arguments: [{1}]' . format ( attr_name , ', ' . join ( view_kwargs . keys ( ) ) ) ) try : return get_object_or_404 ( model , ** { field_name : view_kwargs [ attr_name ] } ) except FieldError : raise ImproperlyConfigured ( 'Model {0} has no field named {1}' . format ( model , field_name ) ) return _getter
Helper that returns a function suitable for use as the fn argument to the permission_required decorator . Internally uses get_object_or_404 so keep in mind that this may raise Http404 .
19,999
def set_base_dir ( self , base_dir ) : self . _base_dir = base_dir self . icon_cache . set_base_dir ( base_dir )
Set the base directory to be used for all relative filenames .