idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
30,800 | def bot_intent ( self ) -> "IntentAPI" : if not self . _bot_intent : self . _bot_intent = IntentAPI ( self . bot_mxid , self , state_store = self . state_store , log = self . intent_log ) return self . _bot_intent | Get the intent API for the appservice bot . |
30,801 | def intent ( self , user : str = None , token : Optional [ str ] = None ) -> "IntentAPI" : if self . is_real_user : raise ValueError ( "Can't get child intent of real user" ) if token : return IntentAPI ( user , self . real_user ( user , token ) , self . bot_intent ( ) , self . state_store , self . intent_log ) return ... | Get the intent API for a specific user . |
30,802 | def request ( self , method : str , path : str , content : Optional [ Union [ dict , bytes , str ] ] = None , timestamp : Optional [ int ] = None , external_url : Optional [ str ] = None , headers : Optional [ Dict [ str , str ] ] = None , query_params : Optional [ Dict [ str , Any ] ] = None , api_path : str = "/_matr... | Make a raw HTTP request . |
30,803 | def _add_section ( self , section ) : section . rid = 0 plen = 0 while self . _merge and self . _sections and plen != len ( self . _sections ) : plen = len ( self . _sections ) self . _sections = [ s for s in self . _sections if not section . join ( s ) ] self . _sections . append ( section ) | Adds a new section to the free section list but before that and if section merge is enabled tries to join the rectangle with all existing sections if successful the resulting section is again merged with the remaining sections until the operation fails . The result is then appended to the list . |
30,804 | def _refine_candidate ( self , width , height ) : packer = newPacker ( PackingMode . Offline , PackingBin . BFF , pack_algo = self . _pack_algo , sort_algo = SORT_LSIDE , rotation = self . _rotation ) packer . add_bin ( width , height ) for r in self . _rectangles : packer . add_rect ( * r ) packer . pack ( ) if len ( ... | Use bottom - left packing algorithm to find a lower height for the container . |
30,805 | def _generate_splits ( self , m , r ) : new_rects = [ ] if r . left > m . left : new_rects . append ( Rectangle ( m . left , m . bottom , r . left - m . left , m . height ) ) if r . right < m . right : new_rects . append ( Rectangle ( r . right , m . bottom , m . right - r . right , m . height ) ) if r . top < m . top ... | When a rectangle is placed inside a maximal rectangle it stops being one and up to 4 new maximal rectangles may appear depending on the placement . _generate_splits calculates them . |
30,806 | def _remove_duplicates ( self ) : contained = set ( ) for m1 , m2 in itertools . combinations ( self . _max_rects , 2 ) : if m1 . contains ( m2 ) : contained . add ( m2 ) elif m2 . contains ( m1 ) : contained . add ( m1 ) self . _max_rects = [ m for m in self . _max_rects if m not in contained ] | Remove every maximal rectangle contained by another one . |
30,807 | def fitness ( self , width , height ) : assert ( width > 0 and height > 0 ) rect , max_rect = self . _select_position ( width , height ) if rect is None : return None return self . _rect_fitness ( max_rect , rect . width , rect . height ) | Metric used to rate how much space is wasted if a rectangle is placed . Returns a value greater or equal to zero the smaller the value the more fit is the rectangle . If the rectangle can t be placed returns None . |
30,808 | def _select_position ( self , w , h ) : fitn = ( ( m . y + h , m . x , w , h , m ) for m in self . _max_rects if self . _rect_fitness ( m , w , h ) is not None ) fitr = ( ( m . y + w , m . x , h , w , m ) for m in self . _max_rects if self . _rect_fitness ( m , h , w ) is not None ) if not self . rot : fitr = [ ] fit =... | Select the position where the y coordinate of the top of the rectangle is lower if there are severtal pick the one with the smallest x coordinate |
30,809 | def _fits_surface ( self , width , height ) : assert ( width > 0 and height > 0 ) if self . rot and ( width > self . width or height > self . height ) : width , height = height , width if width > self . width or height > self . height : return False else : return True | Test surface is big enough to place a rectangle |
30,810 | def validate_packing ( self ) : surface = Rectangle ( 0 , 0 , self . width , self . height ) for r in self : if not surface . contains ( r ) : raise Exception ( "Rectangle placed outside surface" ) rectangles = [ r for r in self ] if len ( rectangles ) <= 1 : return for r1 in range ( 0 , len ( rectangles ) - 2 ) : for ... | Check for collisions between rectangles also check all are placed inside surface . |
30,811 | def add_waste ( self , x , y , width , height ) : self . _add_section ( Rectangle ( x , y , width , height ) ) | Add new waste section |
30,812 | def distance ( self , point ) : return sqrt ( ( self . x - point . x ) ** 2 + ( self . y - point . y ) ** 2 ) | Calculate distance to another point |
30,813 | def move ( self , x , y ) : self . x = x self . y = y | Move Rectangle to x y coordinates |
30,814 | def contains ( self , rect ) : return ( rect . y >= self . y and rect . x >= self . x and rect . y + rect . height <= self . y + self . height and rect . x + rect . width <= self . x + self . width ) | Tests if another rectangle is contained by this one |
30,815 | def intersects ( self , rect , edges = False ) : if ( self . bottom > rect . top or self . top < rect . bottom or self . left > rect . right or self . right < rect . left ) : return False if not edges : if ( self . bottom == rect . top or self . top == rect . bottom or self . left == rect . right or self . right == rec... | Detect intersections between this rectangle and rect . |
30,816 | def join ( self , other ) : if self . contains ( other ) : return True if other . contains ( self ) : self . x = other . x self . y = other . y self . width = other . width self . height = other . height return True if not self . intersects ( other , edges = True ) : return False if self . left == other . left and self... | Try to join a rectangle to this one if the result is also a rectangle and the operation is successful and this rectangle is modified to the union . |
30,817 | def newPacker ( mode = PackingMode . Offline , bin_algo = PackingBin . BBF , pack_algo = MaxRectsBssf , sort_algo = SORT_AREA , rotation = True ) : packer_class = None if mode == PackingMode . Online : sort_algo = None if bin_algo == PackingBin . BNF : packer_class = PackerOnlineBNF elif bin_algo == PackingBin . BFF : ... | Packer factory helper function |
30,818 | def _new_open_bin ( self , width = None , height = None , rid = None ) : factories_to_delete = set ( ) new_bin = None for key , binfac in self . _empty_bins . items ( ) : if not binfac . fits_inside ( width , height ) : continue new_bin = binfac . new_bin ( ) if new_bin is None : continue self . _open_bins . append ( n... | Extract the next empty bin and append it to open bins |
30,819 | def _find_best_fit ( self , pbin ) : fit = ( ( pbin . fitness ( r [ 0 ] , r [ 1 ] ) , k ) for k , r in self . _sorted_rect . items ( ) ) fit = ( f for f in fit if f [ 0 ] is not None ) try : _ , rect = min ( fit , key = self . first_item ) return rect except ValueError : return None | Return best fitness rectangle from rectangles packing _sorted_rect list |
30,820 | def _new_open_bin ( self , remaining_rect ) : factories_to_delete = set ( ) new_bin = None for key , binfac in self . _empty_bins . items ( ) : a_rectangle_fits = False for _ , rect in remaining_rect . items ( ) : if binfac . fits_inside ( rect [ 0 ] , rect [ 1 ] ) : a_rectangle_fits = True break if not a_rectangle_fit... | Extract the next bin where at least one of the rectangles in rem |
30,821 | def _placement_points_generator ( self , skyline , width ) : skyline_r = skyline [ - 1 ] . right skyline_l = skyline [ 0 ] . left ppointsl = ( s . left for s in skyline if s . left + width <= skyline_r ) ppointsr = ( s . right - width for s in skyline if s . right - width >= skyline_l ) return heapq . merge ( ppointsl ... | Returns a generator for the x coordinates of all the placement points on the skyline for a given rectangle . |
30,822 | def _generate_placements ( self , width , height ) : skyline = self . _skyline points = collections . deque ( ) left_index = right_index = 0 support_height = skyline [ 0 ] . top support_index = 0 placements = self . _placement_points_generator ( skyline , width ) for p in placements : if p + width > skyline [ right_ind... | Generate a list with |
30,823 | def _select_position ( self , width , height ) : positions = self . _generate_placements ( width , height ) if self . rot and width != height : positions += self . _generate_placements ( height , width ) if not positions : return None , None return min ( ( ( p [ 0 ] , self . _rect_fitness ( * p ) ) for p in positions )... | Search for the placement with the bes fitness for the rectangle . |
30,824 | def fitness ( self , width , height ) : assert ( width > 0 and height > 0 ) if width > max ( self . width , self . height ) or height > max ( self . height , self . width ) : return None if self . _waste_management : if self . _waste . fitness ( width , height ) is not None : return 0 rect , fitness = self . _select_po... | Search for the best fitness |
30,825 | def add_rect ( self , width , height , rid = None ) : assert ( width > 0 and height > 0 ) if width > max ( self . width , self . height ) or height > max ( self . height , self . width ) : return None rect = None if self . _waste_management : rect = self . _waste . add_rect ( width , height , rid ) if not rect : rect ,... | Add new rectangle |
30,826 | def abspath ( path , ref = None ) : if ref : path = os . path . join ( ref , path ) if not os . path . isabs ( path ) : raise ValueError ( "expected an absolute path but got '%s'" % path ) return path | Create an absolute path . |
30,827 | def split_path ( path , ref = None ) : path = abspath ( path , ref ) return path . strip ( os . path . sep ) . split ( os . path . sep ) | Split a path into its components . |
30,828 | def get_value ( instance , path , ref = None ) : for part in split_path ( path , ref ) : if isinstance ( instance , list ) : part = int ( part ) elif not isinstance ( instance , dict ) : raise TypeError ( "expected `list` or `dict` but got `%s`" % instance ) try : instance = instance [ part ] except KeyError : raise Ke... | Get the value from instance at the given path . |
30,829 | def pop_value ( instance , path , ref = None ) : head , tail = os . path . split ( abspath ( path , ref ) ) instance = get_value ( instance , head ) if isinstance ( instance , list ) : tail = int ( tail ) return instance . pop ( tail ) | Pop the value from instance at the given path . |
30,830 | def merge ( x , y ) : keys_x = set ( x ) keys_y = set ( y ) for key in keys_y - keys_x : x [ key ] = y [ key ] for key in keys_x & keys_y : value_x = x [ key ] value_y = y [ key ] if isinstance ( value_x , dict ) and isinstance ( value_y , dict ) : x [ key ] = merge ( value_x , value_y ) else : if value_x != value_y : ... | Merge two dictionaries and raise an error for inconsistencies . |
30,831 | def set_default_from_schema ( instance , schema ) : for name , property_ in schema . get ( 'properties' , { } ) . items ( ) : if 'default' in property_ : instance . setdefault ( name , property_ [ 'default' ] ) if 'properties' in property_ : set_default_from_schema ( instance . setdefault ( name , { } ) , property_ ) r... | Populate default values on an instance given a schema . |
30,832 | def apply ( instance , func , path = None ) : path = path or os . path . sep if isinstance ( instance , list ) : return [ apply ( item , func , os . path . join ( path , str ( i ) ) ) for i , item in enumerate ( instance ) ] elif isinstance ( instance , dict ) : return { key : apply ( value , func , os . path . join ( ... | Apply func to all fundamental types of instance . |
30,833 | def get_free_port ( ports = None ) : if ports is None : with contextlib . closing ( socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) ) as _socket : _socket . bind ( ( '' , 0 ) ) _ , port = _socket . getsockname ( ) return port for port in ports : with contextlib . closing ( socket . socket ( socket . AF_INET... | Get a free port . |
30,834 | def build_parameter_parts ( configuration , * parameters ) : for parameter in parameters : values = configuration . pop ( parameter , [ ] ) if values : if not isinstance ( values , list ) : values = [ values ] for value in values : yield '--%s=%s' % ( parameter , value ) | Construct command parts for one or more parameters . |
30,835 | def build_dict_parameter_parts ( configuration , * parameters , ** defaults ) : for parameter in parameters : for key , value in configuration . pop ( parameter , { } ) . items ( ) : yield '--%s=%s=%s' % ( parameter , key , value ) | Construct command parts for one or more parameters each of which constitutes an assignment of the form key = value . |
30,836 | def build_docker_run_command ( configuration ) : parts = configuration . pop ( 'docker' ) . split ( ) parts . append ( 'run' ) run = configuration . pop ( 'run' ) if 'env-file' in run : run [ 'env-file' ] = [ os . path . join ( configuration [ 'workspace' ] , env_file ) for env_file in run [ 'env-file' ] ] parts . exte... | Translate a declarative docker configuration to a docker run command . |
30,837 | def build_docker_build_command ( configuration ) : parts = configuration . pop ( 'docker' , 'docker' ) . split ( ) parts . append ( 'build' ) build = configuration . pop ( 'build' ) build [ 'path' ] = os . path . join ( configuration [ 'workspace' ] , build [ 'path' ] ) build [ 'file' ] = os . path . join ( build [ 'pa... | Translate a declarative docker configuration to a docker build command . |
30,838 | def add_argument ( self , parser , path , name = None , schema = None , ** kwargs ) : schema = schema or self . SCHEMA name = name or ( '--%s' % os . path . basename ( path ) ) self . arguments [ name . strip ( '-' ) ] = path path = util . split_path ( path ) path = os . path . sep . join ( it . chain ( [ os . path . s... | Add an argument to the parser based on a schema definition . |
30,839 | def apply ( self , configuration , schema , args ) : for name , path in self . arguments . items ( ) : value = getattr ( args , name . replace ( '-' , '_' ) ) if value is not None : util . set_value ( configuration , path , value ) return configuration | Apply the plugin to the configuration . |
30,840 | def load_plugins ( ) : plugin_cls = { } for entry_point in pkg_resources . iter_entry_points ( 'docker_interface.plugins' ) : cls = entry_point . load ( ) assert cls . COMMANDS is not None , "plugin '%s' does not define its commands" % entry_point . name assert cls . ORDER is not None , "plugin '%s' does not define its... | Load all availabe plugins . |
30,841 | def substitute_variables ( cls , configuration , value , ref ) : if isinstance ( value , str ) : while True : match = cls . REF_PATTERN . search ( value ) if match is None : break path = os . path . join ( os . path . dirname ( ref ) , match . group ( 'path' ) ) try : value = value . replace ( match . group ( 0 ) , str... | Substitute variables in value from configuration where any path reference is relative to ref . |
30,842 | def get_user_group ( self , user = None , group = None ) : user = user or os . getuid ( ) try : try : user = pwd . getpwuid ( int ( user ) ) except ValueError : user = pwd . getpwnam ( user ) except KeyError as ex : self . logger . fatal ( "could not resolve user: %s" , ex ) raise group = group or user . pw_gid try : t... | Get the user and group information . |
30,843 | def pretty_str ( something , indent = 0 ) : if isinstance ( something , CodeEntity ) : return something . pretty_str ( indent = indent ) else : return ( ' ' * indent ) + repr ( something ) | Return a human - readable string representation of an object . |
30,844 | def walk_preorder ( self ) : yield self for child in self . _children ( ) : for descendant in child . walk_preorder ( ) : yield descendant | Iterates the program tree starting from this object going down . |
30,845 | def _lookup_parent ( self , cls ) : codeobj = self . parent while codeobj is not None and not isinstance ( codeobj , cls ) : codeobj = codeobj . parent return codeobj | Lookup a transitive parent object that is an instance of a given class . |
30,846 | def ast_str ( self , indent = 0 ) : line = self . line or 0 col = self . column or 0 name = type ( self ) . __name__ spell = getattr ( self , 'name' , '[no spelling]' ) result = ' ({})' . format ( self . result ) if hasattr ( self , 'result' ) else '' prefix = indent * '| ' return '{}[{}:{}] {}{}: {}' . format ( prefix... | Return a minimal string to print a tree - like structure . |
30,847 | def is_local ( self ) : return ( isinstance ( self . scope , CodeStatement ) or ( isinstance ( self . scope , CodeFunction ) and self not in self . scope . parameters ) ) | Whether this is a local variable . |
30,848 | def is_parameter ( self ) : return ( isinstance ( self . scope , CodeFunction ) and self in self . scope . parameters ) | Whether this is a function parameter . |
30,849 | def _afterpass ( self ) : if hasattr ( self , '_fi' ) : return fi = 0 for codeobj in self . walk_preorder ( ) : codeobj . _fi = fi fi += 1 if isinstance ( codeobj , CodeOperator ) and codeobj . is_assignment : if codeobj . arguments and isinstance ( codeobj . arguments [ 0 ] , CodeReference ) : var = codeobj . argument... | Assign a function - local index to each child object and register write operations to variables . |
30,850 | def _set_condition ( self , condition ) : assert isinstance ( condition , CodeExpression . TYPES ) self . condition = condition | Set the condition for this control flow structure . |
30,851 | def _set_body ( self , body ) : assert isinstance ( body , CodeStatement ) if isinstance ( body , CodeBlock ) : self . body = body else : self . body . _add ( body ) | Set the main body for this control flow structure . |
30,852 | def get_branches ( self ) : if self . else_branch : return [ self . then_branch , self . else_branch ] return [ self . then_branch ] | Return a list with the conditional branch and the default branch . |
30,853 | def list_files ( path ) : files = [ ] if os . path . isdir ( path ) : for stats in os . walk ( path ) : for f in stats [ 2 ] : files . append ( os . path . join ( stats [ 0 ] , f ) ) elif os . path . isfile ( path ) : files = [ path ] return files | Recursively collects a list of files at a path . |
30,854 | def dump ( self ) : text = '' for result in self . objects : if result . is_failure or result . is_error : text += '\n#{red}#{bright}' text += '{}\n' . format ( '' . ljust ( 79 , '=' ) ) status = 'FAILED' if result . is_failure else 'ERROR' text += '{}: {}\n' . format ( status , result . process ) text += '{}\n#{{reset... | Returns the results in string format . |
30,855 | def dump_junit ( self ) : testsuites = ElementTree . Element ( 'testsuites' , name = 'therapist' , time = str ( round ( self . execution_time , 2 ) ) , tests = str ( self . count ( ) ) , failures = str ( self . count ( status = Result . FAILURE ) ) , errors = str ( self . count ( status = Result . ERROR ) ) ) for resul... | Returns a string containing XML mapped to the JUnit schema . |
30,856 | def install ( ** kwargs ) : force = kwargs . get ( 'force' ) preserve_legacy = kwargs . get ( 'preserve_legacy' ) colorama . init ( strip = kwargs . get ( 'no_color' ) ) stdout = subprocess . check_output ( 'which therapist' , shell = True ) therapist_bin = stdout . decode ( 'utf-8' ) . split ( ) [ 0 ] git_dir = curren... | Install the pre - commit hook . |
30,857 | def uninstall ( ** kwargs ) : force = kwargs . get ( 'force' ) restore_legacy = kwargs . get ( 'restore_legacy' ) colorama . init ( strip = kwargs . get ( 'no_color' ) ) git_dir = current_git_dir ( ) if git_dir is None : output ( NOT_GIT_REPO_MSG ) exit ( 1 ) hook_path = os . path . join ( git_dir , 'hooks' , 'pre-comm... | Uninstall the current pre - commit hook . |
30,858 | def run ( ** kwargs ) : paths = kwargs . pop ( 'paths' , ( ) ) action = kwargs . pop ( 'action' ) plugin = kwargs . pop ( 'plugin' ) junit_xml = kwargs . pop ( 'junit_xml' ) use_tracked_files = kwargs . pop ( 'use_tracked_files' ) quiet = kwargs . pop ( 'quiet' ) colorama . init ( strip = kwargs . pop ( 'no_color' ) ) ... | Run the Therapist suite . |
30,859 | def use ( ctx , shortcut ) : git_dir = current_git_dir ( ) if git_dir is None : output ( NOT_GIT_REPO_MSG ) exit ( 1 ) repo_root = os . path . dirname ( git_dir ) config = get_config ( repo_root ) try : use_shortcut = config . shortcuts . get ( shortcut ) while use_shortcut . extends is not None : base = config . short... | Use a shortcut . |
30,860 | def identify_hook ( path ) : with open ( path , 'r' ) as f : f . readline ( ) version_line = f . readline ( ) if version_line . startswith ( '# THERAPIST' ) : return version_line . split ( ) [ 2 ] | Verify that the file at path is the therapist hook and return the hash |
30,861 | def hash_hook ( path , options ) : with open ( path , 'r' ) as f : data = f . read ( ) for key in sorted ( iterkeys ( options ) ) : data += '\n#{}={}' . format ( key , options . get ( key ) ) return hashlib . md5 ( data . encode ( ) ) . hexdigest ( ) | Hash a hook file |
30,862 | def run_process ( self , process ) : message = u'#{bright}' message += u'{} ' . format ( str ( process ) [ : 68 ] ) . ljust ( 69 , '.' ) stashed = False if self . unstaged_changes and not self . include_unstaged_changes : out , err , code = self . git . stash ( keep_index = True , quiet = True ) stashed = code == 0 try... | Runs a single action . |
30,863 | def _extract_upnperror ( self , err_xml ) : nsmap = { 's' : list ( err_xml . nsmap . values ( ) ) [ 0 ] } fault_str = err_xml . findtext ( 's:Body/s:Fault/faultstring' , namespaces = nsmap ) try : err = err_xml . xpath ( 's:Body/s:Fault/detail/*[name()="%s"]' % fault_str , namespaces = nsmap ) [ 0 ] except IndexError :... | Extract the error code and error description from an error returned by the device . |
30,864 | def _remove_extraneous_xml_declarations ( xml_str ) : xml_declaration = '' if xml_str . startswith ( '<?xml' ) : xml_declaration , xml_str = xml_str . split ( '?>' , maxsplit = 1 ) xml_declaration += '?>' xml_str = re . sub ( r'<\?xml.*?\?>' , '' , xml_str , flags = re . I ) return xml_declaration + xml_str | Sometimes devices return XML with more than one XML declaration in such as when returning their own XML config files . This removes the extra ones and preserves the first one . |
30,865 | def call ( self , action_name , arg_in = None , http_auth = None , http_headers = None ) : if arg_in is None : arg_in = { } soap_env = '{%s}' % NS_SOAP_ENV m = '{%s}' % self . service_type root = etree . Element ( soap_env + 'Envelope' , nsmap = { 'SOAP-ENV' : NS_SOAP_ENV } ) root . attrib [ soap_env + 'encodingStyle' ... | Construct the XML and make the call to the device . Parse the response values into a dict . |
30,866 | def _read_services ( self ) : for node in self . _findall ( 'device//serviceList/service' ) : findtext = partial ( node . findtext , namespaces = self . _root_xml . nsmap ) svc = Service ( self , self . _url_base , findtext ( 'serviceType' ) , findtext ( 'serviceId' ) , findtext ( 'controlURL' ) , findtext ( 'SCPDURL' ... | Read the control XML file and populate self . services with a list of services in the form of Service class instances . |
30,867 | def find_action ( self , action_name ) : for service in self . services : action = service . find_action ( action_name ) if action is not None : return action | Find an action by name . Convenience method that searches through all the services offered by the Server for an action and returns an Action instance . If the action is not found returns None . If multiple actions with the same name are found it returns the first one . |
30,868 | def subscribe ( self , callback_url , timeout = None ) : url = urljoin ( self . _url_base , self . _event_sub_url ) headers = dict ( HOST = urlparse ( url ) . netloc , CALLBACK = '<%s>' % callback_url , NT = 'upnp:event' ) if timeout is not None : headers [ 'TIMEOUT' ] = 'Second-%s' % timeout resp = requests . request ... | Set up a subscription to the events offered by this service . |
30,869 | def renew_subscription ( self , sid , timeout = None ) : url = urljoin ( self . _url_base , self . _event_sub_url ) headers = dict ( HOST = urlparse ( url ) . netloc , SID = sid ) if timeout is not None : headers [ 'TIMEOUT' ] = 'Second-%s' % timeout resp = requests . request ( 'SUBSCRIBE' , url , headers = headers , a... | Renews a previously configured subscription . |
30,870 | def cancel_subscription ( self , sid ) : url = urljoin ( self . _url_base , self . _event_sub_url ) headers = dict ( HOST = urlparse ( url ) . netloc , SID = sid ) resp = requests . request ( 'UNSUBSCRIBE' , url , headers = headers , auth = self . device . http_auth ) resp . raise_for_status ( ) | Unsubscribes from a previously configured subscription . |
30,871 | def discover ( timeout = 5 ) : devices = { } for entry in scan ( timeout ) : if entry . location in devices : continue try : devices [ entry . location ] = Device ( entry . location ) except Exception as exc : log = _getLogger ( "ssdp" ) log . error ( 'Error \'%s\' for %s' , exc , entry . location ) return list ( devic... | Convenience method to discover UPnP devices on the network . Returns a list of upnp . Device instances . Any invalid servers are silently ignored . |
30,872 | def to_dot ( self , path : str , title : Optional [ str ] = None ) : g = graphviz . Digraph ( format = 'svg' ) g . node ( 'fake' , style = 'invisible' ) for state in self . _states : if state == self . _initial_state : if state in self . _accepting_states : g . node ( str ( state ) , root = 'true' , shape = 'doublecirc... | Print the automaton to a dot file |
30,873 | def levels_to_accepting_states ( self ) -> dict : res = { accepting_state : 0 for accepting_state in self . _accepting_states } level = 0 z_current , z_next = set ( ) , set ( ) z_next = set ( self . _accepting_states ) while z_current != z_next : level += 1 z_current = z_next z_next = copy ( z_current ) for state in se... | Return a dict from states to level i . e . the number of steps to reach any accepting state . level = - 1 if the state cannot reach any accepting state |
30,874 | def determinize ( self ) -> DFA : nfa = self new_states = { macro_state for macro_state in powerset ( nfa . _states ) } initial_state = frozenset ( [ nfa . _initial_state ] ) final_states = { q for q in new_states if len ( q . intersection ( nfa . _accepting_states ) ) != 0 } transition_function = { } for state_set in ... | Determinize the NFA |
30,875 | def req ( self , method , params = ( ) ) : response = self . session . post ( self . url , data = json . dumps ( { "method" : method , "params" : params , "jsonrpc" : "1.1" } ) , ) . json ( ) if response [ "error" ] is not None : return response [ "error" ] else : return response [ "result" ] | send request to ppcoind |
30,876 | def batch ( self , reqs ) : batch_data = [ ] for req_id , req in enumerate ( reqs ) : batch_data . append ( { "method" : req [ 0 ] , "params" : req [ 1 ] , "jsonrpc" : "2.0" , "id" : req_id } ) data = json . dumps ( batch_data ) response = self . session . post ( self . url , data = data ) . json ( ) return response | send batch request using jsonrpc 2 . 0 |
30,877 | def walletpassphrase ( self , passphrase , timeout = 99999999 , mint_only = True ) : return self . req ( "walletpassphrase" , [ passphrase , timeout , mint_only ] ) | used to unlock wallet for minting |
30,878 | def getblock ( self , blockhash , decode = False ) : if not decode : decode = "false" return self . req ( "getblock" , [ blockhash , decode ] ) else : return self . req ( "getblock" , [ blockhash ] ) | returns detail block info . |
30,879 | def sendfrom ( self , account , address , amount ) : return self . req ( "sendfrom" , [ account , address , amount ] ) | send outgoing tx from specified account to a given address |
30,880 | def listtransactions ( self , account = "" , many = 999 , since = 0 ) : return self . req ( "listtransactions" , [ account , many , since ] ) | list all transactions associated with this wallet |
30,881 | def verifymessage ( self , address , signature , message ) : return self . req ( "verifymessage" , [ address , signature , message ] ) | Verify a signed message . |
30,882 | def coroutine ( f ) : @ wraps ( f ) def g ( * args , ** kwargs ) : sink = f ( * args , ** kwargs ) sink . send ( None ) return sink return g | A sink should be send None first so that the coroutine arrives at the yield position . This wrapper takes care that this is done automatically when the coroutine is started . |
30,883 | def add_call ( self , func ) : self . trace . append ( "{} ({}:{})" . format ( object_name ( func ) , inspect . getsourcefile ( func ) , inspect . getsourcelines ( func ) [ 1 ] ) ) return self | Add a call to the trace . |
30,884 | def all ( pred : Callable , xs : Iterable ) : for x in xs : if not pred ( x ) : return False return True | Check whether all the elements of the iterable xs fullfill predicate pred . |
30,885 | def any ( pred : Callable , xs : Iterable ) : b = find_first ( pred , xs ) return True if b is not None else False | Check if at least one element of the iterable xs fullfills predicate pred . |
30,886 | def map ( fun : Callable , xs : Iterable ) : generator = ( fun ( x ) for x in xs ) return gather ( * generator ) | Traverse an iterable object applying function fun to each element and finally creats a workflow from it . |
30,887 | def zip_with ( fun : Callable , xs : Iterable , ys : Iterable ) : generator = ( fun ( * rs ) for rs in zip ( xs , ys ) ) return gather ( * generator ) | Fuse two Iterable object using the function fun . Notice that if the two objects have different len the shortest object gives the result s shape . |
30,888 | def _arg_to_str ( arg ) : if isinstance ( arg , str ) : return _sugar ( repr ( arg ) ) elif arg is Empty : return '\u2014' else : return _sugar ( str ( arg ) ) | Convert argument to a string . |
30,889 | def is_node_ready ( node ) : return all ( ref_argument ( node . bound_args , a ) is not Empty for a in serialize_arguments ( node . bound_args ) ) | Returns True if none of the argument holders contain any Empty object . |
30,890 | def add_job_to_db ( self , key , job ) : job_msg = self . registry . deep_encode ( job ) prov = prov_key ( job_msg ) def set_link ( duplicate_id ) : self . cur . execute ( 'update "jobs" set "link" = ?, "status" = ? where "id" = ?' , ( duplicate_id , Status . DUPLICATE , key ) ) with self . lock : self . cur . execute ... | Add job info to the database . |
30,891 | def job_exists ( self , prov ) : with self . lock : self . cur . execute ( 'select * from "jobs" where "prov" = ?;' , ( prov , ) ) rec = self . cur . fetchone ( ) return rec is not None | Check if a job exists in the database . |
30,892 | def store_result_in_db ( self , result , always_cache = True ) : job = self [ result . key ] def extend_dependent_links ( ) : with self . lock : new_workflow_id = id ( get_workflow ( result . value ) ) self . links [ new_workflow_id ] . extend ( self . links [ id ( job . workflow ) ] ) del self . links [ id ( job . wor... | Store a result in the database . |
30,893 | def add_time_stamp ( self , db_id , name ) : with self . lock : self . cur . execute ( 'insert into "timestamps" ("job", "what")' 'values (?, ?);' , ( db_id , name ) ) | Add a timestamp to the database . |
30,894 | def static_sum ( values , limit_n = 1000 ) : if len ( values ) < limit_n : return sum ( values ) else : half = len ( values ) // 2 return add ( static_sum ( values [ : half ] , limit_n ) , static_sum ( values [ half : ] , limit_n ) ) | Example of static sum routine . |
30,895 | def dynamic_sum ( values , limit_n = 1000 , acc = 0 , depth = 4 ) : if len ( values ) < limit_n : return acc + sum ( values ) if depth > 0 : half = len ( values ) // 2 return add ( dynamic_sum ( values [ : half ] , limit_n , acc , depth = depth - 1 ) , dynamic_sum ( values [ half : ] , limit_n , 0 , depth = depth - 1 )... | Example of dynamic sum . |
30,896 | def flush ( self ) : while not self . _queue . empty ( ) : self . _queue . get ( ) self . _queue . task_done ( ) self . close ( ) | Erases queue and set end - of - queue message . |
30,897 | def find_links_to ( links , node ) : return { address : src for src , ( tgt , address ) in _all_valid ( links ) if tgt == node } | Find links to a node . |
30,898 | def _all_valid ( links ) : for k , v in links . items ( ) : for i in v : yield k , i | Iterates over all links forgetting emtpy registers . |
30,899 | def from_call ( foo , args , kwargs , hints , call_by_value = True ) : bound_args = signature ( foo ) . bind ( * args , ** kwargs ) bound_args . apply_defaults ( ) variadic = next ( ( x . name for x in bound_args . signature . parameters . values ( ) if x . kind == Parameter . VAR_POSITIONAL ) , None ) if variadic : if... | Takes a function and a set of arguments it needs to run on . Returns a newly constructed workflow representing the promised value from the evaluation of the function with said arguments . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.