idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
24,400 | def generate ( num , prompt_default = True ) : p = Problem ( num ) problem_text = p . text msg = "Generate file for problem %i?" % num click . confirm ( msg , default = prompt_default , abort = True ) if p . glob : filename = str ( p . file ) msg = '"{}" already exists. Overwrite?' . format ( filename ) click . confirm ( click . style ( msg , fg = 'red' ) , abort = True ) else : previous_file = Problem ( num - 1 ) . file prefix = previous_file . prefix if previous_file else '' filename = p . filename ( prefix = prefix ) header = 'Project Euler Problem %i' % num divider = '=' * len ( header ) text = '\n' . join ( [ header , divider , '' , problem_text ] ) content = '\n' . join ( [ '' ] ) with open ( filename , 'w' ) as f : f . write ( content + '\n\n\n' ) click . secho ( 'Successfully created "{}".' . format ( filename ) , fg = 'green' ) if p . resources : p . copy_resources ( ) | Generates Python file for a problem . |
24,401 | def preview ( num ) : problem_text = Problem ( num ) . text click . secho ( "Project Euler Problem %i" % num , bold = True ) click . echo ( problem_text ) | Prints the text of a problem . |
24,402 | def skip ( num ) : click . echo ( "Current problem is problem %i." % num ) generate ( num + 1 , prompt_default = False ) Problem ( num ) . file . change_suffix ( '-skipped' ) | Generates Python file for the next problem . |
24,403 | def verify ( num , filename = None , exit = True ) : p = Problem ( num ) filename = filename or p . filename ( ) if not os . path . isfile ( filename ) : if p . glob : filename = str ( p . file ) else : click . secho ( 'No file found for problem %i.' % p . num , fg = 'red' ) sys . exit ( 1 ) solution = p . solution click . echo ( 'Checking "{}" against solution: ' . format ( filename ) , nl = False ) cmd = ( sys . executable or 'python' , filename ) start = clock ( ) proc = subprocess . Popen ( cmd , stdout = subprocess . PIPE ) stdout = proc . communicate ( ) [ 0 ] end = clock ( ) time_info = format_time ( start , end ) if proc . poll ( ) != 0 : click . secho ( 'Error calling "{}".' . format ( filename ) , fg = 'red' ) click . secho ( time_info , fg = 'cyan' ) return sys . exit ( 1 ) if exit else None if isinstance ( stdout , bytes ) : output = stdout . decode ( 'ascii' ) output_lines = output . splitlines ( ) if output else [ '[no output]' ] if len ( output_lines ) > 1 : is_correct = False click . echo ( ) click . secho ( '\n' . join ( output_lines ) , bold = True , fg = 'red' ) else : is_correct = output_lines [ 0 ] == solution fg_colour = 'green' if is_correct else 'red' click . secho ( output_lines [ 0 ] , bold = True , fg = fg_colour ) click . secho ( time_info , fg = 'cyan' ) if is_correct : p . file . change_suffix ( '' ) return sys . exit ( 1 ) if exit and not is_correct else is_correct | Verifies the solution to a problem . |
24,404 | def verify_all ( num ) : keys = ( 'correct' , 'incorrect' , 'error' , 'skipped' , 'missing' ) symbols = ( 'C' , 'I' , 'E' , 'S' , '.' ) colours = ( 'green' , 'red' , 'yellow' , 'cyan' , 'white' ) status = OrderedDict ( ( key , click . style ( symbol , fg = colour , bold = True ) ) for key , symbol , colour in zip ( keys , symbols , colours ) ) overview = { } files = problem_glob ( ) if not files : click . echo ( "No Project Euler files found in the current directory." ) sys . exit ( 1 ) for file in files : try : is_correct = verify ( file . num , filename = str ( file ) , exit = False ) except KeyboardInterrupt : overview [ file . num ] = status [ 'skipped' ] else : if is_correct is None : overview [ file . num ] = status [ 'error' ] elif is_correct : overview [ file . num ] = status [ 'correct' ] elif not is_correct : overview [ file . num ] = status [ 'incorrect' ] if file . num != num : file . change_suffix ( '-skipped' ) click . echo ( ) legend = ', ' . join ( '{} = {}' . format ( v , k ) for k , v in status . items ( ) ) click . echo ( '-' * 63 ) click . echo ( legend + '\n' ) num_of_rows = ( num + 19 ) // 20 for row in range ( 1 , num_of_rows + 1 ) : low , high = ( row * 20 ) - 19 , ( row * 20 ) click . echo ( "Problems {:03d}-{:03d}: " . format ( low , high ) , nl = False ) for problem in range ( low , high + 1 ) : status = overview [ problem ] if problem in overview else '.' spacer = ' ' if ( problem % 5 == 0 ) else ' ' click . secho ( status + spacer , nl = ( problem % 20 == 0 ) ) click . echo ( ) | Verifies all problem files in the current directory and prints an overview of the status of each problem . |
24,405 | def euler_options ( fn ) : euler_functions = cheat , generate , preview , skip , verify , verify_all for option in reversed ( euler_functions ) : name , docstring = option . __name__ , option . __doc__ kwargs = { 'flag_value' : option , 'help' : docstring } flag = '--%s' % name . replace ( '_' , '-' ) flags = [ flag ] if '_' in name else [ flag , '-%s' % name [ 0 ] ] fn = click . option ( 'option' , * flags , ** kwargs ) ( fn ) return fn | Decorator to link CLI options with their appropriate functions |
24,406 | def main ( option , problem ) : if problem == 0 or option in { skip , verify_all } : files = problem_glob ( ) problem = max ( file . num for file in files ) if files else 0 if problem == 0 : if option not in { cheat , preview , verify_all } : msg = "No Project Euler files found in the current directory." click . echo ( msg ) option = generate problem = 1 elif option is preview : problem += 1 if option is None : verify ( problem ) problem += 1 option = generate elif option is None : option = verify if Problem ( problem ) . glob else generate option ( problem ) sys . exit ( 0 ) | Python - based Project Euler command line tool . |
24,407 | def start ( self , * args , ** kwargs ) : if args : LOG . debug ( "args: %s" % str ( args ) ) if kwargs : LOG . debug ( "kwargs: %s" % str ( kwargs ) ) try : self . _server . start ( ) self . _server . proxyInit ( ) return True except Exception as err : LOG . critical ( "Failed to start server" ) LOG . debug ( str ( err ) ) self . _server . stop ( ) return False | Start the server thread if it wasn t created with autostart = True . |
24,408 | def stop ( self , * args , ** kwargs ) : if args : LOG . debug ( "args: %s" % str ( args ) ) if kwargs : LOG . debug ( "kwargs: %s" % str ( kwargs ) ) try : self . _server . stop ( ) self . _server = None self . devices . clear ( ) self . devices_all . clear ( ) self . devices_raw . clear ( ) self . devices_raw_dict . clear ( ) return True except Exception as err : LOG . critical ( "Failed to stop server" ) LOG . debug ( str ( err ) ) return False | Stop the server thread . |
24,409 | def getMetadata ( self , remote , address , key ) : if self . _server is not None : return self . _server . getAllMetadata ( remote , address , key ) | Get metadata of device |
24,410 | def get_hs_color ( self ) : hm_color = self . getCachedOrUpdatedValue ( "COLOR" , channel = self . _color_channel ) if hm_color >= 200 : return 0 , 0 return hm_color / 200 , 1 | Return the color of the light as HSV color without the value component for the brightness . |
24,411 | def set_hs_color ( self , hue : float , saturation : float ) : self . turn_off_effect ( ) if saturation < 0.1 : hm_color = 200 else : hm_color = int ( round ( max ( min ( hue , 1 ) , 0 ) * 199 ) ) self . setValue ( key = "COLOR" , channel = self . _color_channel , value = hm_color ) | Set a fixed color and also turn off effects in order to see the color . |
24,412 | def get_effect ( self ) -> str : effect_value = self . getCachedOrUpdatedValue ( "PROGRAM" , channel = self . _effect_channel ) try : return self . _light_effect_list [ effect_value ] except IndexError : LOG . error ( "Unexpected color effect returned by CCU" ) return "Unknown" | Return the current color change program of the light . |
24,413 | def set_effect ( self , effect_name : str ) : try : effect_index = self . _light_effect_list . index ( effect_name ) except ValueError : LOG . error ( "Trying to set unknown light effect" ) return False return self . setValue ( key = "PROGRAM" , channel = self . _effect_channel , value = effect_index ) | Sets the color change program of the light . |
24,414 | def make_http_credentials ( username = None , password = None ) : credentials = '' if username is None : return credentials if username is not None : if ':' in username : return credentials credentials += username if credentials and password is not None : credentials += ":%s" % password return "%s@" % credentials | Build auth part for api_url . |
24,415 | def build_api_url ( host = REMOTES [ 'default' ] [ 'ip' ] , port = REMOTES [ 'default' ] [ 'port' ] , path = REMOTES [ 'default' ] [ 'path' ] , username = None , password = None , ssl = False ) : credentials = make_http_credentials ( username , password ) scheme = 'http' if not path : path = '' if path and not path . startswith ( '/' ) : path = "/%s" % path if ssl : scheme += 's' return "%s://%s%s:%i%s" % ( scheme , credentials , host , port , path ) | Build API URL from components . |
24,416 | def createDeviceObjects ( self , interface_id ) : global WORKING WORKING = True remote = interface_id . split ( '-' ) [ - 1 ] LOG . debug ( "RPCFunctions.createDeviceObjects: iterating interface_id = %s" % ( remote , ) ) for dev in self . _devices_raw [ remote ] : if not dev [ 'PARENT' ] : if dev [ 'ADDRESS' ] not in self . devices_all [ remote ] : try : if dev [ 'TYPE' ] in devicetypes . SUPPORTED : deviceObject = devicetypes . SUPPORTED [ dev [ 'TYPE' ] ] ( dev , self . _proxies [ interface_id ] , self . resolveparamsets ) LOG . debug ( "RPCFunctions.createDeviceObjects: created %s as SUPPORTED device for %s" % ( dev [ 'ADDRESS' ] , dev [ 'TYPE' ] ) ) else : deviceObject = devicetypes . UNSUPPORTED ( dev , self . _proxies [ interface_id ] , self . resolveparamsets ) LOG . debug ( "RPCFunctions.createDeviceObjects: created %s as UNSUPPORTED device for %s" % ( dev [ 'ADDRESS' ] , dev [ 'TYPE' ] ) ) LOG . debug ( "RPCFunctions.createDeviceObjects: adding to self.devices_all" ) self . devices_all [ remote ] [ dev [ 'ADDRESS' ] ] = deviceObject LOG . debug ( "RPCFunctions.createDeviceObjects: adding to self.devices" ) self . devices [ remote ] [ dev [ 'ADDRESS' ] ] = deviceObject except Exception as err : LOG . critical ( "RPCFunctions.createDeviceObjects: Parent: %s" , str ( err ) ) for dev in self . _devices_raw [ remote ] : if dev [ 'PARENT' ] : try : if dev [ 'ADDRESS' ] not in self . devices_all [ remote ] : deviceObject = HMChannel ( dev , self . _proxies [ interface_id ] , self . resolveparamsets ) self . devices_all [ remote ] [ dev [ 'ADDRESS' ] ] = deviceObject self . devices [ remote ] [ dev [ 'PARENT' ] ] . CHANNELS [ dev [ 'INDEX' ] ] = deviceObject except Exception as err : LOG . critical ( "RPCFunctions.createDeviceObjects: Child: %s" , str ( err ) ) if self . devices_all [ remote ] and self . remotes [ remote ] . get ( 'resolvenames' , False ) : self . addDeviceNames ( remote ) WORKING = False if self . systemcallback : self . systemcallback ( 'createDeviceObjects' ) return True | Transform the raw device descriptions into instances of devicetypes . generic . HMDevice or availabe subclass . |
24,417 | def event ( self , interface_id , address , value_key , value ) : LOG . debug ( "RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % ( interface_id , address , value_key . upper ( ) , str ( value ) ) ) self . devices_all [ interface_id . split ( '-' ) [ - 1 ] ] [ address ] . event ( interface_id , value_key . upper ( ) , value ) if self . eventcallback : self . eventcallback ( interface_id = interface_id , address = address , value_key = value_key . upper ( ) , value = value ) return True | If a device emits some sort event we will handle it here . |
24,418 | def __request ( self , * args , ** kwargs ) : with self . lock : parent = xmlrpc . client . ServerProxy return parent . _ServerProxy__request ( self , * args , ** kwargs ) | Call method on server side |
24,419 | def parseCCUSysVar ( self , data ) : if data [ 'type' ] == 'LOGIC' : return data [ 'name' ] , data [ 'value' ] == 'true' elif data [ 'type' ] == 'NUMBER' : return data [ 'name' ] , float ( data [ 'value' ] ) elif data [ 'type' ] == 'LIST' : return data [ 'name' ] , int ( data [ 'value' ] ) else : return data [ 'name' ] , data [ 'value' ] | Helper to parse type of system variables of CCU |
24,420 | def jsonRpcLogin ( self , remote ) : session = False try : params = { "username" : self . remotes [ remote ] [ 'username' ] , "password" : self . remotes [ remote ] [ 'password' ] } response = self . _rpcfunctions . jsonRpcPost ( self . remotes [ remote ] [ 'ip' ] , self . remotes [ remote ] . get ( 'jsonport' , DEFAULT_JSONPORT ) , "Session.login" , params ) if response [ 'error' ] is None and response [ 'result' ] : session = response [ 'result' ] if not session : LOG . warning ( "ServerThread.jsonRpcLogin: Unable to open session." ) except Exception as err : LOG . debug ( "ServerThread.jsonRpcLogin: Exception while logging in via JSON-RPC: %s" % str ( err ) ) return session | Login to CCU and return session |
24,421 | def jsonRpcLogout ( self , remote , session ) : logout = False try : params = { "_session_id_" : session } response = self . _rpcfunctions . jsonRpcPost ( self . remotes [ remote ] [ 'ip' ] , self . remotes [ remote ] . get ( 'jsonport' , DEFAULT_JSONPORT ) , "Session.logout" , params ) if response [ 'error' ] is None and response [ 'result' ] : logout = response [ 'result' ] except Exception as err : LOG . debug ( "ServerThread.jsonRpcLogout: Exception while logging in via JSON-RPC: %s" % str ( err ) ) return logout | Logout of CCU |
24,422 | def homegearCheckInit ( self , remote ) : rdict = self . remotes . get ( remote ) if not rdict : return False if rdict . get ( 'type' ) != BACKEND_HOMEGEAR : return False try : interface_id = "%s-%s" % ( self . _interface_id , remote ) return self . proxies [ interface_id ] . clientServerInitialized ( interface_id ) except Exception as err : LOG . debug ( "ServerThread.homegearCheckInit: Exception: %s" % str ( err ) ) return False | Check if proxy is still initialized |
24,423 | def set_ontime ( self , ontime ) : try : ontime = float ( ontime ) except Exception as err : LOG . debug ( "SwitchPowermeter.set_ontime: Exception %s" % ( err , ) ) return False self . actionNodeData ( "ON_TIME" , ontime ) | Set duration th switch stays on when toggled . |
24,424 | def event ( self , interface_id , key , value ) : LOG . info ( "HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s" % ( self . _ADDRESS , interface_id , key , value ) ) self . _VALUES [ key ] = value for callback in self . _eventcallbacks : LOG . debug ( "HMGeneric.event: Using callback %s " % str ( callback ) ) callback ( self . _ADDRESS , interface_id , key , value ) | Handle the event received by server . |
24,425 | def getParamsetDescription ( self , paramset ) : try : self . _PARAMSET_DESCRIPTIONS [ paramset ] = self . _proxy . getParamsetDescription ( self . _ADDRESS , paramset ) except Exception as err : LOG . error ( "HMGeneric.getParamsetDescription: Exception: " + str ( err ) ) return False | Descriptions for paramsets are available to determine what can be don with the device . |
24,426 | def updateParamset ( self , paramset ) : try : if paramset : if self . _proxy : returnset = self . _proxy . getParamset ( self . _ADDRESS , paramset ) if returnset : self . _paramsets [ paramset ] = returnset if self . PARAMSETS : if self . PARAMSETS . get ( PARAMSET_VALUES ) : self . _VALUES [ PARAM_UNREACH ] = self . PARAMSETS . get ( PARAMSET_VALUES ) . get ( PARAM_UNREACH ) return True return False except Exception as err : LOG . debug ( "HMGeneric.updateParamset: Exception: %s, %s, %s" % ( str ( err ) , str ( self . _ADDRESS ) , str ( paramset ) ) ) return False | Devices should not update their own paramsets . They rely on the state of the server . Hence we pull the specified paramset . |
24,427 | def updateParamsets ( self ) : try : for ps in self . _PARAMSETS : self . updateParamset ( ps ) return True except Exception as err : LOG . error ( "HMGeneric.updateParamsets: Exception: " + str ( err ) ) return False | Devices should update their own paramsets . They rely on the state of the server . Hence we pull all paramsets . |
24,428 | def putParamset ( self , paramset , data = { } ) : try : if paramset in self . _PARAMSETS and data : self . _proxy . putParamset ( self . _ADDRESS , paramset , data ) self . updateParamsets ( ) return True else : return False except Exception as err : LOG . error ( "HMGeneric.putParamset: Exception: " + str ( err ) ) return False | Some devices act upon changes to paramsets . A putted paramset must not contain all keys available in the specified paramset just the ones which are writable and should be changed . |
24,429 | def getCachedOrUpdatedValue ( self , key ) : try : return self . _VALUES [ key ] except KeyError : return self . getValue ( key ) | Gets the device s value with the given key . |
24,430 | def getCachedOrUpdatedValue ( self , key , channel = None ) : if channel : return self . _hmchannels [ channel ] . getCachedOrUpdatedValue ( key ) try : return self . _VALUES [ key ] except KeyError : value = self . _VALUES [ key ] = self . getValue ( key ) return value | Gets the channel s value with the given key . |
24,431 | def UNREACH ( self ) : if self . _VALUES . get ( PARAM_UNREACH , False ) : return True else : for device in self . _hmchannels . values ( ) : if device . UNREACH : return True return False | Returns true if the device or any children is not reachable |
24,432 | def getAttributeData ( self , name , channel = None ) : return self . _getNodeData ( name , self . _ATTRIBUTENODE , channel ) | Returns a attribut |
24,433 | def getBinaryData ( self , name , channel = None ) : return self . _getNodeData ( name , self . _BINARYNODE , channel ) | Returns a binary node |
24,434 | def set_temperature ( self , target_temperature ) : try : target_temperature = float ( target_temperature ) except Exception as err : LOG . debug ( "Thermostat.set_temperature: Exception %s" % ( err , ) ) return False self . writeNodeData ( "SET_TEMPERATURE" , target_temperature ) | Set the target temperature . |
24,435 | def stop ( self ) : LOG . info ( "Shutting down server" ) self . server . shutdown ( ) LOG . debug ( "ServerThread.stop: Stopping ServerThread" ) self . server . server_close ( ) LOG . info ( "Server stopped" ) | Shut down our XML - RPC server . |
24,436 | def heirarchical_help ( shovel , prefix ) : result = [ ] tuples = heirarchical_helper ( shovel , prefix ) if not tuples : return '' longest = max ( len ( name + ' ' * level ) for name , _ , level in tuples ) fmt = '%%%is => %%-50s' % longest for name , docstring , level in tuples : if docstring == None : result . append ( ' ' * level + name + '/' ) else : docstring = re . sub ( r'\s+' , ' ' , docstring ) . strip ( ) if len ( docstring ) > 50 : docstring = docstring [ : 47 ] + '...' result . append ( fmt % ( name , docstring ) ) return '\n' . join ( result ) | Given a shovel of tasks display a heirarchical list of the tasks |
24,437 | def shovel_help ( shovel , * names ) : if not len ( names ) : return heirarchical_help ( shovel , '' ) else : for name in names : task = shovel [ name ] if isinstance ( task , Shovel ) : return heirarchical_help ( task , name ) else : return task . help ( ) | Return a string about help with the tasks or lists tasks available |
24,438 | def load ( cls , path , base = None ) : obj = cls ( ) obj . read ( path , base ) return obj | Either load a path and return a shovel object or return None |
24,439 | def extend ( self , tasks ) : self . _tasks . extend ( tasks ) for task in tasks : current = self . map modules = task . fullname . split ( '.' ) for module in modules [ : - 1 ] : if not isinstance ( current [ module ] , Shovel ) : logger . warn ( 'Overriding task %s with a module' % current [ module ] . file ) shovel = Shovel ( ) shovel . overrides = current [ module ] current [ module ] = shovel current = current [ module ] . map name = modules [ - 1 ] if name in current : logger . warn ( 'Overriding %s with %s' % ( '.' . join ( modules ) , task . file ) ) task . overrides = current [ name ] current [ name ] = task | Add tasks to this particular shovel |
24,440 | def read ( self , path , base = None ) : if base == None : base = os . getcwd ( ) absolute = os . path . abspath ( path ) if os . path . isfile ( absolute ) : logger . info ( 'Loading %s' % absolute ) self . extend ( Task . load ( path , base ) ) elif os . path . isdir ( absolute ) : tasks = [ ] for root , _ , files in os . walk ( absolute ) : files = [ f for f in files if f . endswith ( '.py' ) ] for child in files : absolute = os . path . join ( root , child ) logger . info ( 'Loading %s' % absolute ) tasks . extend ( Task . load ( absolute , base ) ) self . extend ( tasks ) | Import some tasks |
24,441 | def keys ( self ) : keys = [ ] for key , value in self . map . items ( ) : if isinstance ( value , Shovel ) : keys . extend ( [ key + '.' + k for k in value . keys ( ) ] ) else : keys . append ( key ) return sorted ( keys ) | Return all valid keys |
24,442 | def items ( self ) : pairs = [ ] for key , value in self . map . items ( ) : if isinstance ( value , Shovel ) : pairs . extend ( [ ( key + '.' + k , v ) for k , v in value . items ( ) ] ) else : pairs . append ( ( key , value ) ) return sorted ( pairs ) | Return a list of tuples of all the keys and tasks |
24,443 | def tasks ( self , name ) : found = self [ name ] if isinstance ( found , Shovel ) : return [ v for _ , v in found . items ( ) ] return [ found ] | Get all the tasks that match a name |
24,444 | def make ( cls , obj ) : try : cls . _cache . append ( Task ( obj ) ) except Exception : logger . exception ( 'Unable to make task for %s' % repr ( obj ) ) | Given a callable object return a new callable object |
24,445 | def load ( cls , path , base = None ) : base = base or os . getcwd ( ) absolute = os . path . abspath ( path ) parent = os . path . dirname ( absolute ) name , _ , _ = os . path . basename ( absolute ) . rpartition ( '.py' ) fobj , path , description = imp . find_module ( name , [ parent ] ) try : imp . load_module ( name , fobj , path , description ) finally : if fobj : fobj . close ( ) relative , _ , _ = os . path . relpath ( path , base ) . rpartition ( '.py' ) for task in cls . _cache : parts = relative . split ( os . path . sep ) parts . append ( task . name ) parts = [ part . strip ( '.' ) for part in parts if part not in ( 'shovel' , '.shovel' , '__init__' , '.' , '..' , '' ) ] task . fullname = '.' . join ( parts ) logger . debug ( 'Found task %s in %s' % ( task . fullname , task . module ) ) return cls . clear ( ) | Return a list of the tasks stored in a file |
24,446 | def capture ( self , * args , ** kwargs ) : import traceback try : from StringIO import StringIO except ImportError : from io import StringIO stdout , stderr = sys . stdout , sys . stderr sys . stdout = out = StringIO ( ) sys . stderr = err = StringIO ( ) result = { 'exception' : None , 'stderr' : None , 'stdout' : None , 'return' : None } try : result [ 'return' ] = self . __call__ ( * args , ** kwargs ) except Exception : result [ 'exception' ] = traceback . format_exc ( ) sys . stdout , sys . stderr = stdout , stderr result [ 'stderr' ] = err . getvalue ( ) result [ 'stdout' ] = out . getvalue ( ) return result | Run a task and return a dictionary with stderr stdout and the return value . Also the traceback from the exception if there was one |
24,447 | def dry ( self , * args , ** kwargs ) : return 'Would have executed:\n%s%s' % ( self . name , Args ( self . spec ) . explain ( * args , ** kwargs ) ) | Perform a dry - run of the task |
24,448 | def help ( self ) : result = [ '=' * 50 , self . name ] if self . doc : result . extend ( [ '=' * 30 , self . doc ] ) override = self . overrides while override : if isinstance ( override , Shovel ) : result . append ( 'Overrides module' ) else : result . append ( 'Overrides %s' % override . file ) override = override . overrides result . extend ( [ '=' * 30 , 'From %s on line %i' % ( self . file , self . line ) , '=' * 30 , '%s%s' % ( self . name , str ( Args ( self . spec ) ) ) ] ) return os . linesep . join ( result ) | Return the help string of the task |
24,449 | def explain ( self , * args , ** kwargs ) : args = self . get ( * args , ** kwargs ) results = [ '%s = %s' % ( name , value ) for name , value in args . required ] results . extend ( [ '%s = %s (overridden)' % ( name , value ) for name , value in args . overridden ] ) results . extend ( [ '%s = %s (default)' % ( name , value ) for name , value in args . defaulted ] ) if self . _varargs : results . append ( '%s = %s' % ( self . _varargs , args . varargs ) ) if self . _kwargs : results . append ( '%s = %s' % ( self . _kwargs , args . kwargs ) ) return '\n\t' . join ( results ) | Return a string that describes how these args are interpreted |
24,450 | def get ( self , * args , ** kwargs ) : required = [ arg for arg in self . _args if arg not in kwargs ] if len ( args ) < len ( required ) : raise TypeError ( 'Missing arguments %s' % required [ len ( args ) : ] ) required = list ( zip ( required , args ) ) args = args [ len ( required ) : ] defaulted = [ ( name , default ) for name , default in self . _defaults if name not in kwargs ] overridden = list ( zip ( [ d [ 0 ] for d in defaulted ] , args ) ) args = args [ len ( overridden ) : ] defaulted = defaulted [ len ( overridden ) : ] if args and not self . _varargs : raise TypeError ( 'Too many arguments provided' ) return ArgTuple ( required , overridden , defaulted , args , kwargs ) | Evaluate this argspec with the provided arguments |
24,451 | def sumnum ( * args ) : print ( '%s = %f' % ( ' + ' . join ( args ) , sum ( float ( arg ) for arg in args ) ) ) | Computes the sum of the provided numbers |
24,452 | def attributes ( name , ** kwargs ) : print ( '%s has attributes:' % name ) for key , value in kwargs . items ( ) : print ( '\t%s => %s' % ( key , value ) ) | Prints a name and all keyword attributes |
24,453 | def render ( self , name , value , attrs = None , multi = False , renderer = None ) : DJANGO_111_OR_UP = ( VERSION [ 0 ] == 1 and VERSION [ 1 ] >= 11 ) or ( VERSION [ 0 ] >= 2 ) if DJANGO_111_OR_UP : return super ( DynamicRawIDWidget , self ) . render ( name , value , attrs , renderer = renderer ) if attrs is None : attrs = { } related_url = reverse ( 'admin:{0}_{1}_changelist' . format ( self . rel . to . _meta . app_label , self . rel . to . _meta . object_name . lower ( ) , ) , current_app = self . admin_site . name , ) params = self . url_parameters ( ) if params : url = u'?' + u'&' . join ( [ u'{0}={1}' . format ( k , v ) for k , v in params . items ( ) ] ) else : url = u'' if "class" not in attrs : attrs [ 'class' ] = ( 'vForeignKeyRawIdAdminField' ) app_name = self . rel . to . _meta . app_label . strip ( ) model_name = self . rel . to . _meta . object_name . lower ( ) . strip ( ) hidden_input = super ( widgets . ForeignKeyRawIdWidget , self ) . render ( name , value , attrs ) extra_context = { 'hidden_input' : hidden_input , 'name' : name , 'app_name' : app_name , 'model_name' : model_name , 'related_url' : related_url , 'url' : url , } return render_to_string ( 'dynamic_raw_id/admin/widgets/dynamic_raw_id_field.html' , extra_context , ) | Django < = 1 . 10 variant . |
24,454 | def get_context ( self , name , value , attrs ) : context = super ( DynamicRawIDWidget , self ) . get_context ( name , value , attrs ) model = self . rel . model if VERSION [ 0 ] == 2 else self . rel . to related_url = reverse ( 'admin:{0}_{1}_changelist' . format ( model . _meta . app_label , model . _meta . object_name . lower ( ) ) , current_app = self . admin_site . name , ) params = self . url_parameters ( ) if params : url = u'?' + u'&' . join ( [ u'{0}={1}' . format ( k , v ) for k , v in params . items ( ) ] ) else : url = u'' if "class" not in attrs : attrs [ 'class' ] = ( 'vForeignKeyRawIdAdminField' ) app_name = model . _meta . app_label . strip ( ) model_name = model . _meta . object_name . lower ( ) . strip ( ) context . update ( { 'name' : name , 'app_name' : app_name , 'model_name' : model_name , 'related_url' : related_url , 'url' : url , } ) return context | Django > = 1 . 11 variant . |
24,455 | def get_form ( self , request , rel , admin_site ) : return DynamicRawIDFilterForm ( admin_site = admin_site , rel = rel , field_name = self . field_path , data = self . used_parameters , ) | Return filter form . |
24,456 | def queryset ( self , request , queryset ) : if self . form . is_valid ( ) : filter_params = dict ( filter ( lambda x : bool ( x [ 1 ] ) , self . form . cleaned_data . items ( ) ) ) return queryset . filter ( ** filter_params ) return queryset | Filter queryset using params from the form . |
24,457 | def decorator ( cls , candidate , * exp_args , ** exp_kwargs ) : def wrapper ( control ) : @ wraps ( control ) def inner ( * args , ** kwargs ) : experiment = cls ( * exp_args , ** exp_kwargs ) experiment . control ( control , args = args , kwargs = kwargs ) experiment . candidate ( candidate , args = args , kwargs = kwargs ) return experiment . conduct ( ) return inner return wrapper | Decorate a control function in order to conduct an experiment when called . |
24,458 | def candidate ( self , cand_func , args = None , kwargs = None , name = 'Candidate' , context = None ) : self . _candidates . append ( { 'func' : cand_func , 'args' : args or [ ] , 'kwargs' : kwargs or { } , 'name' : name , 'context' : context or { } , } ) | Adds a candidate function to an experiment . Can be used multiple times for multiple candidates . |
24,459 | def encode ( data ) : if riemann . network . CASHADDR_PREFIX is None : raise ValueError ( 'Network {} does not support cashaddresses.' . format ( riemann . get_current_network_name ( ) ) ) data = convertbits ( data , 8 , 5 ) checksum = calculate_checksum ( riemann . network . CASHADDR_PREFIX , data ) payload = b32encode ( data + checksum ) form = '{prefix}:{payload}' return form . format ( prefix = riemann . network . CASHADDR_PREFIX , payload = payload ) | bytes - > str |
24,460 | def decode ( data ) : if riemann . network . CASHADDR_PREFIX is None : raise ValueError ( 'Network {} does not support cashaddresses.' . format ( riemann . get_current_network_name ( ) ) ) if data . find ( riemann . network . CASHADDR_PREFIX ) != 0 : raise ValueError ( 'Malformed cashaddr. Cannot locate prefix: {}' . format ( riemann . netowrk . CASHADDR_PREFIX ) ) prefix , data = data . split ( ':' ) decoded = b32decode ( data ) if not verify_checksum ( prefix , decoded ) : raise ValueError ( 'Bad cash address checksum' ) converted = convertbits ( decoded , 5 , 8 ) return bytes ( converted [ : - 6 ] ) | str - > bytes |
24,461 | def copy ( self , outpoint = None , stack_script = None , redeem_script = None , sequence = None ) : return TxIn ( outpoint = outpoint if outpoint is not None else self . outpoint , stack_script = ( stack_script if stack_script is not None else self . stack_script ) , redeem_script = ( redeem_script if redeem_script is not None else self . redeem_script ) , sequence = sequence if sequence is not None else self . sequence ) | TxIn - > TxIn |
24,462 | def from_bytes ( TxIn , byte_string ) : outpoint = Outpoint . from_bytes ( byte_string [ : 36 ] ) script_sig_len = VarInt . from_bytes ( byte_string [ 36 : 45 ] ) script_start = 36 + len ( script_sig_len ) script_end = script_start + script_sig_len . number script_sig = byte_string [ script_start : script_end ] sequence = byte_string [ script_end : script_end + 4 ] if script_sig == b'' : stack_script = b'' redeem_script = b'' else : stack_script , redeem_script = TxIn . _parse_script_sig ( script_sig ) return TxIn ( outpoint = outpoint , stack_script = stack_script , redeem_script = redeem_script , sequence = sequence ) | byte_string - > TxIn parses a TxIn from a byte - like object |
24,463 | def no_witness ( self ) : tx = bytes ( ) tx += self . version tx += VarInt ( len ( self . tx_ins ) ) . to_bytes ( ) for tx_in in self . tx_ins : tx += tx_in . to_bytes ( ) tx += VarInt ( len ( self . tx_outs ) ) . to_bytes ( ) for tx_out in self . tx_outs : tx += tx_out . to_bytes ( ) tx += self . lock_time return bytes ( tx ) | Tx - > bytes |
24,464 | def _hash_sequence ( self , sighash_type , anyone_can_pay ) : if anyone_can_pay or sighash_type == shared . SIGHASH_SINGLE : return b'\x00' * 32 else : sequences = ByteData ( ) for tx_in in self . tx_ins : sequences += tx_in . sequence return utils . hash256 ( sequences . to_bytes ( ) ) | BIP143 hashSequence implementation |
24,465 | def _adjusted_script_code ( self , script ) : script_code = ByteData ( ) if script [ 0 ] == len ( script ) - 1 : return script script_code += VarInt ( len ( script ) ) script_code += script return script_code | Checks if the script code pased in to the sighash function is already length - prepended This will break if there s a redeem script that s just a pushdata That won t happen in practice |
24,466 | def _hash_outputs ( self , index , sighash_type ) : if sighash_type == shared . SIGHASH_ALL : outputs = ByteData ( ) for tx_out in self . tx_outs : outputs += tx_out . to_bytes ( ) return utils . hash256 ( outputs . to_bytes ( ) ) elif ( sighash_type == shared . SIGHASH_SINGLE and index < len ( self . tx_outs ) ) : return utils . hash256 ( self . tx_outs [ index ] . to_bytes ( ) ) else : raise NotImplementedError ( 'I refuse to implement the SIGHASH_SINGLE bug.' ) | BIP143 hashOutputs implementation |
24,467 | def deserialize ( serialized_script ) : deserialized = [ ] i = 0 while i < len ( serialized_script ) : current_byte = serialized_script [ i ] if current_byte == 0xab : raise NotImplementedError ( 'OP_CODESEPARATOR is a bad idea.' ) if current_byte <= 75 and current_byte != 0 : deserialized . append ( serialized_script [ i + 1 : i + 1 + current_byte ] . hex ( ) ) i += 1 + current_byte if i > len ( serialized_script ) : raise IndexError ( 'Push {} caused out of bounds exception.' . format ( current_byte ) ) elif current_byte == 76 : blob_len = serialized_script [ i + 1 ] deserialized . append ( serialized_script [ i + 2 : i + 2 + blob_len ] . hex ( ) ) i += 2 + blob_len elif current_byte == 77 : blob_len = utils . le2i ( serialized_script [ i + 1 : i + 3 ] ) deserialized . append ( serialized_script [ i + 3 : i + 3 + blob_len ] . hex ( ) ) i += 3 + blob_len elif current_byte == 78 : raise NotImplementedError ( 'OP_PUSHDATA4 is a bad idea.' ) else : if current_byte in riemann . network . INT_TO_CODE_OVERWRITE : deserialized . append ( riemann . network . INT_TO_CODE_OVERWRITE [ current_byte ] ) elif current_byte in INT_TO_CODE : deserialized . append ( INT_TO_CODE [ current_byte ] ) else : raise ValueError ( 'Unsupported opcode. ' 'Got 0x%x' % serialized_script [ i ] ) i += 1 return ' ' . join ( deserialized ) | bytearray - > str |
24,468 | def _hsig_input ( self , index ) : hsig_input = z . ZcashByteData ( ) hsig_input += self . tx_joinsplits [ index ] . random_seed hsig_input += self . tx_joinsplits [ index ] . nullifiers hsig_input += self . joinsplit_pubkey return hsig_input . to_bytes ( ) | inputs for the hsig hash |
24,469 | def _primary_input ( self , index ) : primary_input = z . ZcashByteData ( ) primary_input += self . tx_joinsplits [ index ] . anchor primary_input += self . tx_joinsplits [ index ] . nullifiers primary_input += self . tx_joinsplits [ index ] . commitments primary_input += self . tx_joinsplits [ index ] . vpub_old primary_input += self . tx_joinsplits [ index ] . vpub_new primary_input += self . hsigs [ index ] primary_input += self . tx_joinsplits [ index ] . vmacs return primary_input . to_bytes ( ) | Primary input for the zkproof |
24,470 | def from_bytes ( SproutTx , byte_string ) : version = byte_string [ 0 : 4 ] tx_ins = [ ] tx_ins_num = shared . VarInt . from_bytes ( byte_string [ 4 : ] ) current = 4 + len ( tx_ins_num ) for _ in range ( tx_ins_num . number ) : tx_in = TxIn . from_bytes ( byte_string [ current : ] ) current += len ( tx_in ) tx_ins . append ( tx_in ) tx_outs = [ ] tx_outs_num = shared . VarInt . from_bytes ( byte_string [ current : ] ) current += len ( tx_outs_num ) for _ in range ( tx_outs_num . number ) : tx_out = TxOut . from_bytes ( byte_string [ current : ] ) current += len ( tx_out ) tx_outs . append ( tx_out ) lock_time = byte_string [ current : current + 4 ] current += 4 tx_joinsplits = None joinsplit_pubkey = None joinsplit_sig = None if utils . le2i ( version ) == 2 : tx_joinsplits = [ ] tx_joinsplits_num = shared . VarInt . from_bytes ( byte_string [ current : ] ) current += len ( tx_joinsplits_num ) for _ in range ( tx_joinsplits_num . number ) : joinsplit = z . SproutJoinsplit . from_bytes ( byte_string [ current : ] ) current += len ( joinsplit ) tx_joinsplits . append ( joinsplit ) joinsplit_pubkey = byte_string [ current : current + 32 ] current += 32 joinsplit_sig = byte_string [ current : current + 64 ] return SproutTx ( version = version , tx_ins = tx_ins , tx_outs = tx_outs , lock_time = lock_time , tx_joinsplits = tx_joinsplits , joinsplit_pubkey = joinsplit_pubkey , joinsplit_sig = joinsplit_sig ) | byte - like - > SproutTx |
24,471 | def copy ( self , version = None , tx_ins = None , tx_outs = None , lock_time = None , tx_joinsplits = None , joinsplit_pubkey = None , joinsplit_sig = None ) : return SproutTx ( version = version if version is not None else self . version , tx_ins = tx_ins if tx_ins is not None else self . tx_ins , tx_outs = tx_outs if tx_outs is not None else self . tx_outs , lock_time = ( lock_time if lock_time is not None else self . lock_time ) , tx_joinsplits = ( tx_joinsplits if tx_joinsplits is not None else self . tx_joinsplits ) , joinsplit_pubkey = ( joinsplit_pubkey if joinsplit_pubkey is not None else self . joinsplit_pubkey ) , joinsplit_sig = ( joinsplit_sig if joinsplit_sig is not None else self . joinsplit_sig ) ) | SproutTx ... - > Tx |
24,472 | def _make_immutable ( self ) : self . _bytes = bytes ( self . _bytes ) self . __immutable = True | Prevents any future changes to the object |
24,473 | def find ( self , substring ) : if isinstance ( substring , ByteData ) : substring = substring . to_bytes ( ) return self . _bytes . find ( substring ) | byte - like - > int Finds the index of substring |
24,474 | def from_bytes ( VarInt , byte_string ) : num = byte_string if num [ 0 ] <= 0xfc : num = num [ 0 : 1 ] non_compact = False elif num [ 0 ] == 0xfd : num = num [ 1 : 3 ] non_compact = ( num [ - 1 : ] == b'\x00' ) elif num [ 0 ] == 0xfe : num = num [ 1 : 5 ] non_compact = ( num [ - 2 : ] == b'\x00\x00' ) elif num [ 0 ] == 0xff : num = num [ 1 : 9 ] non_compact = ( num [ - 4 : ] == b'\x00\x00\x00\x00' ) if len ( num ) not in [ 1 , 2 , 4 , 8 ] : raise ValueError ( 'Malformed VarInt. Got: {}' . format ( byte_string . hex ( ) ) ) if ( non_compact and ( 'overwinter' in riemann . get_current_network_name ( ) or 'sapling' in riemann . get_current_network_name ( ) ) ) : raise ValueError ( 'VarInt must be compact. Got: {}' . format ( byte_string . hex ( ) ) ) ret = VarInt ( utils . le2i ( num ) , length = len ( num ) + 1 if non_compact else 0 ) return ret | byte - like - > VarInt accepts arbitrary length input gets a VarInt off the front |
24,475 | def copy ( self , tx_ins = None , tx_outs = None , lock_time = None , expiry_height = None , value_balance = None , tx_shielded_spends = None , tx_shielded_outputs = None , tx_joinsplits = None , joinsplit_pubkey = None , joinsplit_sig = None , binding_sig = None ) : return SaplingTx ( tx_ins = tx_ins if tx_ins is not None else self . tx_ins , tx_outs = tx_outs if tx_outs is not None else self . tx_outs , lock_time = ( lock_time if lock_time is not None else self . lock_time ) , expiry_height = ( expiry_height if expiry_height is not None else self . expiry_height ) , value_balance = ( value_balance if value_balance is not None else self . value_balance ) , tx_shielded_spends = ( tx_shielded_spends if tx_shielded_spends is not None else self . tx_shielded_spends ) , tx_shielded_outputs = ( tx_shielded_outputs if tx_shielded_outputs is not None else self . tx_shielded_outputs ) , tx_joinsplits = ( tx_joinsplits if tx_joinsplits is not None else self . tx_joinsplits ) , joinsplit_pubkey = ( joinsplit_pubkey if joinsplit_pubkey is not None else self . joinsplit_pubkey ) , joinsplit_sig = ( joinsplit_sig if joinsplit_sig is not None else self . joinsplit_sig ) , binding_sig = ( binding_sig if binding_sig is not None else self . binding_sig ) ) | SaplingTx ... - > SaplingTx |
24,476 | def encode ( data , checksum = True ) : if checksum : data = data + utils . hash256 ( data ) [ : 4 ] v , prefix = to_long ( 256 , lambda x : x , iter ( data ) ) data = from_long ( v , prefix , BASE58_BASE , lambda v : BASE58_ALPHABET [ v ] ) return data . decode ( "utf8" ) | Convert binary to base58 using BASE58_ALPHABET . |
24,477 | def make_pkh_output_script ( pubkey , witness = False ) : if witness and not riemann . network . SEGWIT : raise ValueError ( 'Network {} does not support witness scripts.' . format ( riemann . get_current_network_name ( ) ) ) output_script = bytearray ( ) if type ( pubkey ) is not bytearray and type ( pubkey ) is not bytes : raise ValueError ( 'Unknown pubkey format. ' 'Expected bytes. Got: {}' . format ( type ( pubkey ) ) ) pubkey_hash = utils . hash160 ( pubkey ) if witness : output_script . extend ( riemann . network . P2WPKH_PREFIX ) output_script . extend ( pubkey_hash ) else : output_script . extend ( b'\x76\xa9\x14' ) output_script . extend ( pubkey_hash ) output_script . extend ( b'\x88\xac' ) return output_script | bytearray - > bytearray |
24,478 | def _make_output ( value , output_script , version = None ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredTxOut ( value = value , version = version , output_script = output_script ) return tx . TxOut ( value = value , output_script = output_script ) | byte - like byte - like - > TxOut |
24,479 | def make_sh_output ( value , output_script , witness = False ) : return _make_output ( value = utils . i2le_padded ( value , 8 ) , output_script = make_sh_output_script ( output_script , witness ) ) | int str - > TxOut |
24,480 | def make_pkh_output ( value , pubkey , witness = False ) : return _make_output ( value = utils . i2le_padded ( value , 8 ) , output_script = make_pkh_output_script ( pubkey , witness ) ) | int bytearray - > TxOut |
24,481 | def make_outpoint ( tx_id_le , index , tree = None ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredOutpoint ( tx_id = tx_id_le , index = utils . i2le_padded ( index , 4 ) , tree = utils . i2le_padded ( tree , 1 ) ) return tx . Outpoint ( tx_id = tx_id_le , index = utils . i2le_padded ( index , 4 ) ) | byte - like int int - > Outpoint |
24,482 | def make_script_sig ( stack_script , redeem_script ) : stack_script += ' {}' . format ( serialization . hex_serialize ( redeem_script ) ) return serialization . serialize ( stack_script ) | str str - > bytearray |
24,483 | def make_legacy_input ( outpoint , stack_script , redeem_script , sequence ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredTxIn ( outpoint = outpoint , sequence = utils . i2le_padded ( sequence , 4 ) ) return tx . TxIn ( outpoint = outpoint , stack_script = stack_script , redeem_script = redeem_script , sequence = utils . i2le_padded ( sequence , 4 ) ) | Outpoint byte - like byte - like int - > TxIn |
24,484 | def make_witness_input ( outpoint , sequence ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredTxIn ( outpoint = outpoint , sequence = utils . i2le_padded ( sequence , 4 ) ) return tx . TxIn ( outpoint = outpoint , stack_script = b'' , redeem_script = b'' , sequence = utils . i2le_padded ( sequence , 4 ) ) | Outpoint int - > TxIn |
24,485 | def length_prepend ( byte_string ) : length = tx . VarInt ( len ( byte_string ) ) return length . to_bytes ( ) + byte_string | bytes - > bytes |
24,486 | def _hash_to_sh_address ( script_hash , witness = False , cashaddr = True ) : addr_bytes = bytearray ( ) if riemann . network . CASHADDR_P2SH is not None and cashaddr : addr_bytes . extend ( riemann . network . CASHADDR_P2SH ) addr_bytes . extend ( script_hash ) return riemann . network . CASHADDR_ENCODER . encode ( addr_bytes ) if witness : addr_bytes . extend ( riemann . network . P2WSH_PREFIX ) addr_bytes . extend ( script_hash ) return riemann . network . SEGWIT_ENCODER . encode ( addr_bytes ) else : addr_bytes . extend ( riemann . network . P2SH_PREFIX ) addr_bytes . extend ( script_hash ) return riemann . network . LEGACY_ENCODER . encode ( addr_bytes ) | bytes bool bool - > str cashaddrs are preferred where possible but cashaddr is ignored in most cases is there a better way to structure this? |
24,487 | def _ser_script_to_sh_address ( script_bytes , witness = False , cashaddr = True ) : if witness : script_hash = utils . sha256 ( script_bytes ) else : script_hash = utils . hash160 ( script_bytes ) return _hash_to_sh_address ( script_hash = script_hash , witness = witness , cashaddr = cashaddr ) | makes an p2sh address from a serialized script |
24,488 | def make_sh_address ( script_string , witness = False , cashaddr = True ) : script_bytes = script_ser . serialize ( script_string ) return _ser_script_to_sh_address ( script_bytes = script_bytes , witness = witness , cashaddr = cashaddr ) | str bool bool - > str |
24,489 | def to_output_script ( address ) : parsed = parse ( address ) parsed_hash = b'' try : if ( parsed . find ( riemann . network . P2WPKH_PREFIX ) == 0 and len ( parsed ) == 22 ) : return parsed except TypeError : pass try : if ( parsed . find ( riemann . network . P2WSH_PREFIX ) == 0 and len ( parsed ) == 34 ) : return parsed except TypeError : pass try : if ( parsed . find ( riemann . network . CASHADDR_P2SH ) == 0 and len ( parsed ) == len ( riemann . network . CASHADDR_P2SH ) + 20 ) : prefix = b'\xa9\x14' parsed_hash = parsed [ len ( riemann . network . P2SH_PREFIX ) : ] suffix = b'\x87' except TypeError : pass try : if ( parsed . find ( riemann . network . CASHADDR_P2PKH ) == 0 and len ( parsed ) == len ( riemann . network . CASHADDR_P2PKH ) + 20 ) : prefix = b'\x76\xa9\x14' parsed_hash = parsed [ len ( riemann . network . P2PKH_PREFIX ) : ] suffix = b'\x88\xac' except TypeError : pass if ( parsed . find ( riemann . network . P2PKH_PREFIX ) == 0 and len ( parsed ) == len ( riemann . network . P2PKH_PREFIX ) + 20 ) : prefix = b'\x76\xa9\x14' parsed_hash = parsed [ len ( riemann . network . P2PKH_PREFIX ) : ] suffix = b'\x88\xac' if ( parsed . find ( riemann . network . P2SH_PREFIX ) == 0 and len ( parsed ) == len ( riemann . network . P2SH_PREFIX ) + 20 ) : prefix = b'\xa9\x14' parsed_hash = parsed [ len ( riemann . network . P2SH_PREFIX ) : ] suffix = b'\x87' if parsed_hash == b'' : raise ValueError ( 'Cannot parse output script from address.' ) output_script = prefix + parsed_hash + suffix return output_script | str - > bytes There s probably a better way to do this |
24,490 | def parse_hash ( address ) : raw = parse ( address ) try : if address . find ( riemann . network . CASHADDR_PREFIX ) == 0 : if raw . find ( riemann . network . CASHADDR_P2SH ) == 0 : return raw [ len ( riemann . network . CASHADDR_P2SH ) : ] if raw . find ( riemann . network . CASHADDR_P2PKH ) == 0 : return raw [ len ( riemann . network . CASHADDR_P2PKH ) : ] except TypeError : pass try : if address . find ( riemann . network . BECH32_HRP ) == 0 : if raw . find ( riemann . network . P2WSH_PREFIX ) == 0 : return raw [ len ( riemann . network . P2WSH_PREFIX ) : ] if raw . find ( riemann . network . P2WPKH_PREFIX ) == 0 : return raw [ len ( riemann . network . P2WPKH_PREFIX ) : ] except TypeError : pass if raw . find ( riemann . network . P2SH_PREFIX ) == 0 : return raw [ len ( riemann . network . P2SH_PREFIX ) : ] if raw . find ( riemann . network . P2PKH_PREFIX ) == 0 : return raw [ len ( riemann . network . P2PKH_PREFIX ) : ] | str - > bytes There s probably a better way to do this . |
24,491 | def guess_version ( redeem_script ) : n = riemann . get_current_network_name ( ) if 'sprout' in n : return 1 if 'overwinter' in n : return 3 if 'sapling' in n : return 4 try : script_array = redeem_script . split ( ) script_array . index ( 'OP_CHECKSEQUENCEVERIFY' ) return 2 except ValueError : return 1 | str - > int Bitcoin uses tx version 2 for nSequence signaling . Zcash uses tx version 2 for joinsplits . |
24,492 | def guess_sequence ( redeem_script ) : try : script_array = redeem_script . split ( ) loc = script_array . index ( 'OP_CHECKSEQUENCEVERIFY' ) return int ( script_array [ loc - 1 ] , 16 ) except ValueError : return 0xFFFFFFFE | str - > int If OP_CSV is used guess an appropriate sequence Otherwise disable RBF but leave lock_time on . Fails if there s not a constant before OP_CSV |
24,493 | def output ( value , address ) : script = addr . to_output_script ( address ) value = utils . i2le_padded ( value , 8 ) return tb . _make_output ( value , script ) | int str - > TxOut accepts base58 or bech32 addresses |
24,494 | def outpoint ( tx_id , index , tree = None ) : tx_id_le = bytes . fromhex ( tx_id ) [ : : - 1 ] return tb . make_outpoint ( tx_id_le , index , tree ) | hex_str int int - > Outpoint accepts block explorer txid string |
24,495 | def unsigned_input ( outpoint , redeem_script = None , sequence = None ) : if redeem_script is not None and sequence is None : sequence = guess_sequence ( redeem_script ) if sequence is None : sequence = 0xFFFFFFFE return tb . make_legacy_input ( outpoint = outpoint , stack_script = b'' , redeem_script = b'' , sequence = sequence ) | Outpoint byte - like int - > TxIn |
24,496 | def p2pkh_input ( outpoint , sig , pubkey , sequence = 0xFFFFFFFE ) : stack_script = '{sig} {pk}' . format ( sig = sig , pk = pubkey ) stack_script = script_ser . serialize ( stack_script ) return tb . make_legacy_input ( outpoint , stack_script , b'' , sequence ) | OutPoint hex_string hex_string int - > TxIn Create a signed legacy TxIn from a p2pkh prevout |
24,497 | def p2sh_input ( outpoint , stack_script , redeem_script , sequence = None ) : if sequence is None : sequence = guess_sequence ( redeem_script ) stack_script = script_ser . serialize ( stack_script ) redeem_script = script_ser . hex_serialize ( redeem_script ) redeem_script = script_ser . serialize ( redeem_script ) return tb . make_legacy_input ( outpoint = outpoint , stack_script = stack_script , redeem_script = redeem_script , sequence = sequence ) | OutPoint str str int - > TxIn Create a signed legacy TxIn from a p2pkh prevout |
24,498 | def copy ( self , tx_ins = None , tx_outs = None , lock_time = None , expiry_height = None , tx_joinsplits = None , joinsplit_pubkey = None , joinsplit_sig = None ) : return OverwinterTx ( tx_ins = tx_ins if tx_ins is not None else self . tx_ins , tx_outs = tx_outs if tx_outs is not None else self . tx_outs , lock_time = ( lock_time if lock_time is not None else self . lock_time ) , expiry_height = ( expiry_height if expiry_height is not None else self . expiry_height ) , tx_joinsplits = ( tx_joinsplits if tx_joinsplits is not None else self . tx_joinsplits ) , joinsplit_pubkey = ( joinsplit_pubkey if joinsplit_pubkey is not None else self . joinsplit_pubkey ) , joinsplit_sig = ( joinsplit_sig if joinsplit_sig is not None else self . joinsplit_sig ) ) | OverwinterTx ... - > OverwinterTx |
24,499 | def from_bytes ( OverwinterTx , byte_string ) : header = byte_string [ 0 : 4 ] group_id = byte_string [ 4 : 8 ] if header != b'\x03\x00\x00\x80' or group_id != b'\x70\x82\xc4\x03' : raise ValueError ( 'Bad header or group ID. Expected {} and {}. Got: {} and {}' . format ( b'\x03\x00\x00\x80' . hex ( ) , b'\x70\x82\xc4\x03' . hex ( ) , header . hex ( ) , group_id . hex ( ) ) ) tx_ins = [ ] tx_ins_num = shared . VarInt . from_bytes ( byte_string [ 8 : ] ) current = 8 + len ( tx_ins_num ) for _ in range ( tx_ins_num . number ) : tx_in = TxIn . from_bytes ( byte_string [ current : ] ) current += len ( tx_in ) tx_ins . append ( tx_in ) tx_outs = [ ] tx_outs_num = shared . VarInt . from_bytes ( byte_string [ current : ] ) current += len ( tx_outs_num ) for _ in range ( tx_outs_num . number ) : tx_out = TxOut . from_bytes ( byte_string [ current : ] ) current += len ( tx_out ) tx_outs . append ( tx_out ) lock_time = byte_string [ current : current + 4 ] current += 4 expiry_height = byte_string [ current : current + 4 ] current += 4 if current == len ( byte_string ) : tx_joinsplits = tuple ( ) joinsplit_pubkey = None joinsplit_sig = None else : tx_joinsplits = [ ] tx_joinsplits_num = shared . VarInt . from_bytes ( byte_string [ current : ] ) current += len ( tx_outs_num ) for _ in range ( tx_joinsplits_num . number ) : tx_joinsplit = z . SproutJoinsplit . from_bytes ( byte_string [ current : ] ) current += len ( tx_joinsplit ) tx_joinsplits . append ( tx_joinsplit ) joinsplit_pubkey = byte_string [ current : current + 32 ] current += 32 joinsplit_sig = byte_string [ current : current + 64 ] return OverwinterTx ( tx_ins = tx_ins , tx_outs = tx_outs , lock_time = lock_time , expiry_height = expiry_height , tx_joinsplits = tx_joinsplits , joinsplit_pubkey = joinsplit_pubkey , joinsplit_sig = joinsplit_sig ) | byte - like - > OverwinterTx |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.