idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
600 | def from_json ( cls , json_doc ) : try : d = json . load ( json_doc ) except AttributeError : # catch the read() error d = json . loads ( json_doc ) return cls . from_dict ( d ) | Parse a JSON string and build an entity . | 56 | 10 |
601 | def _multiple_field ( cls ) : klassdict = cls . __dict__ try : # Checking for cls.entitylist_multifield would return any inherited # values, so we check the class __dict__ explicitly. return klassdict [ "_entitylist_multifield" ] [ 0 ] except ( KeyError , IndexError , TypeError ) : from . import fields multifield_tuple... | Return the multiple TypedField associated with this EntityList . | 234 | 12 |
602 | def _finalize_namespaces ( self , ns_dict = None ) : if ns_dict : # Add the user's entries to our set for ns , alias in six . iteritems ( ns_dict ) : self . _collected_namespaces . add_namespace_uri ( ns , alias ) # Add the ID namespaces self . _collected_namespaces . add_namespace_uri ( ns_uri = idgen . get_id_namespa... | Returns a dictionary of namespaces to be exported with an XML document . | 460 | 14 |
603 | def get ( self , query , sort , page , size ) : urlkwargs = { 'q' : query , 'sort' : sort , 'size' : size , } communities = Community . filter_communities ( query , sort ) page = communities . paginate ( page , size ) links = default_links_pagination_factory ( page , urlkwargs ) links_headers = map ( lambda key : ( 'li... | Get a list of all the communities . | 185 | 8 |
604 | def get ( self , community_id ) : community = Community . get ( community_id ) if not community : abort ( 404 ) etag = community . version_id self . check_etag ( etag ) response = self . make_response ( community , links_item_factory = default_links_item_factory ) response . set_etag ( etag ) return response | Get the details of the specified community . | 84 | 8 |
605 | def Phylesystem ( repos_dict = None , repos_par = None , with_caching = True , repo_nexml2json = None , git_ssh = None , pkey = None , git_action_class = PhylesystemGitAction , mirror_info = None , new_study_prefix = None , infrastructure_commit_author = 'OpenTree API <api@opentreeoflife.org>' ) : if not repo_nexml2jso... | Factory function for a _Phylesystem object . | 281 | 10 |
606 | def convert_html_entities ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return html . unescape ( text_string ) . replace ( """ , "'" ) else : raise InputError ( "string not passed as argument for text_string" ) | Converts HTML5 character references within text_string to their corresponding unicode characters and returns converted string as type str . | 80 | 24 |
607 | def convert_ligatures ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : for i in range ( 0 , len ( LIGATURES ) ) : text_string = text_string . replace ( LIGATURES [ str ( i ) ] [ "ligature" ] , LIGATURES [ str ( i ) ] [ "term" ] ) return text_string else :... | Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str . | 116 | 23 |
608 | def correct_spelling ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : word_list = text_string . split ( ) spellchecked_word_list = [ ] for word in word_list : spellchecked_word_list . append ( spellcheck . correct_word ( word ) ) return " " . join ( spell... | Splits string and converts words not found within a pre - built dictionary to their most likely actual word based on a relative probability dictionary . Returns edited string as type str . | 115 | 34 |
609 | def create_sentence_list ( text_string ) : if text_string is None or text_string == "" : return [ ] elif isinstance ( text_string , str ) : return SENTENCE_TOKENIZER . tokenize ( text_string ) else : raise InputError ( "non-string passed as argument for create_sentence_list" ) | Splits text_string into a list of sentences based on NLTK s english . pickle tokenizer and returns said list as type list of str . | 80 | 32 |
610 | def keyword_tokenize ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return " " . join ( [ word for word in KEYWORD_TOKENIZER . tokenize ( text_string ) if word not in STOPWORDS and len ( word ) >= 3 ] ) else : raise InputError ( "string not passed as ar... | Extracts keywords from text_string using NLTK s list of English stopwords ignoring words of a length smaller than 3 and returns the new string as type str . | 99 | 35 |
611 | def lemmatize ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return LEMMATIZER . lemmatize ( text_string ) else : raise InputError ( "string not passed as primary argument" ) | Returns base from of text_string using NLTK s WordNetLemmatizer as type str . | 69 | 22 |
612 | def lowercase ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return text_string . lower ( ) else : raise InputError ( "string not passed as argument for text_string" ) | Converts text_string into lowercase and returns the converted string as type str . | 62 | 17 |
613 | def preprocess_text ( text_string , function_list ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : if isinstance ( function_list , list ) : for func in function_list : try : text_string = func ( text_string ) except ( NameError , TypeError ) : raise FunctionError ( "in... | Given each function within function_list applies the order of functions put forward onto text_string returning the processed string as type str . | 143 | 26 |
614 | def remove_esc_chars ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return " " . join ( re . sub ( r'\\\w' , "" , text_string ) . split ( ) ) else : raise InputError ( "string not passed as argument" ) | Removes any escape character within text_string and returns the new string as type str . | 82 | 18 |
615 | def remove_numbers ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return " " . join ( re . sub ( r'\b[\d.\/,]+' , "" , text_string ) . split ( ) ) else : raise InputError ( "string not passed as argument" ) | Removes any digit value discovered within text_string and returns the new string as type str . | 86 | 19 |
616 | def remove_number_words ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : for word in NUMBER_WORDS : text_string = re . sub ( r'[\S]*\b' + word + r'[\S]*' , "" , text_string ) return " " . join ( text_string . split ( ) ) else : raise InputError ( "string ... | Removes any integer represented as a word within text_string and returns the new string as type str . | 112 | 21 |
617 | def remove_urls ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return " " . join ( re . sub ( r'http\S+' , "" , text_string ) . split ( ) ) else : raise InputError ( "string not passed as argument" ) | Removes all URLs within text_string and returns the new string as type str . | 81 | 17 |
618 | def remove_whitespace ( text_string ) : if text_string is None or text_string == "" : return "" elif isinstance ( text_string , str ) : return " " . join ( text_string . split ( ) ) else : raise InputError ( "none type or string not passed as an argument" ) | Removes all whitespace found within text_string and returns new string as type str . | 71 | 18 |
619 | def log ( self , level , message , * args , * * kwargs ) : extra = self . extras . copy ( ) extra . update ( kwargs . pop ( 'extra' , { } ) ) kwargs [ 'extra' ] = extra self . logger . log ( level , message , * args , * * kwargs ) | This is the primary method to override to ensure logging with extra options gets correctly specified . | 75 | 17 |
620 | def warning ( self , message , * args , * * kwargs ) : warncls = kwargs . pop ( 'warning' , None ) if warncls and self . raise_warnings : warnings . warn ( message , warncls ) return self . log ( logging . WARNING , message , * args , * * kwargs ) | Specialized warnings system . If a warning subclass is passed into the keyword arguments and raise_warnings is True - the warnning will be passed to the warnings module . | 75 | 34 |
621 | def log ( self , level , message , * args , * * kwargs ) : extra = kwargs . pop ( 'extra' , { } ) extra . update ( { 'user' : self . user } ) kwargs [ 'extra' ] = extra super ( ServiceLogger , self ) . log ( level , message , * args , * * kwargs ) | Provide current user as extra context to the logger | 82 | 10 |
622 | def logger ( self ) : if not hasattr ( self , '_logger' ) or not self . _logger : self . _logger = ServiceLogger ( ) return self . _logger | Instantiates and returns a ServiceLogger instance | 44 | 10 |
623 | def ot_find_studies ( arg_dict , exact = True , verbose = False , oti_wrapper = None ) : if oti_wrapper is None : from peyotl . sugar import oti oti_wrapper = oti return oti_wrapper . find_studies ( arg_dict , exact = exact , verbose = verbose , wrap_response = True ) | Uses a peyotl wrapper around an Open Tree web service to get a list of studies including values value for a given property to be searched on porperty . | 85 | 34 |
624 | def main ( argv ) : import argparse description = 'Uses Open Tree of Life web services to try to find a tree with the value property pair specified. ' 'setting --fuzzy will allow fuzzy matching' parser = argparse . ArgumentParser ( prog = 'ot-get-tree' , description = description ) parser . add_argument ( 'arg_dict' , ... | This function sets up a command - line option parser and then calls print_matching_trees to do all of the real work . | 306 | 28 |
625 | def main ( argv ) : import argparse import codecs # have to be ready to deal with utf-8 names out = codecs . getwriter ( 'utf-8' ) ( sys . stdout ) description = '''Takes a series of at least 2 OTT ids and reports the OTT of their least inclusive taxonomic ancestor and that taxon's ancestors.''' parser = argparse . Arg... | This function sets up a command - line option parser and then calls to do all of the real work . | 293 | 21 |
626 | def is_sequence ( value ) : return ( hasattr ( value , "__iter__" ) and not isinstance ( value , ( six . string_types , six . binary_type ) ) ) | Determine if a value is a sequence type . | 43 | 11 |
627 | def import_class ( classpath ) : modname , classname = classpath . rsplit ( "." , 1 ) module = importlib . import_module ( modname ) klass = getattr ( module , classname ) return klass | Import the class referred to by the fully qualified class path . | 52 | 12 |
628 | def resolve_class ( classref ) : if classref is None : return None elif isinstance ( classref , six . class_types ) : return classref elif isinstance ( classref , six . string_types ) : return import_class ( classref ) else : raise ValueError ( "Unable to resolve class for '%s'" % classref ) | Attempt to return a Python class for the input class reference . | 79 | 12 |
629 | def needkwargs ( * argnames ) : required = set ( argnames ) def decorator ( func ) : def inner ( * args , * * kwargs ) : missing = required - set ( kwargs ) if missing : err = "%s kwargs are missing." % list ( missing ) raise ValueError ( err ) return func ( * args , * * kwargs ) return inner return decorator | Function decorator which checks that the decorated function is called with a set of required kwargs . | 88 | 20 |
630 | def get ( host = "localhost" , port = 3551 , timeout = 30 ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) sock . settimeout ( timeout ) sock . connect ( ( host , port ) ) sock . send ( CMD_STATUS ) buffr = "" while not buffr . endswith ( EOF ) : buffr += sock . recv ( BUFFER_SIZE ) . decode ( ) s... | Connect to the APCUPSd NIS and request its status . | 109 | 14 |
631 | def strip_units_from_lines ( lines ) : for line in lines : for unit in ALL_UNITS : if line . endswith ( " %s" % unit ) : line = line [ : - 1 - len ( unit ) ] yield line | Removes all units from the ends of the lines . | 55 | 11 |
632 | def print_status ( raw_status , strip_units = False ) : lines = split ( raw_status ) if strip_units : lines = strip_units_from_lines ( lines ) for line in lines : print ( line ) | Print the status to stdout in the same format as the original apcaccess . | 50 | 17 |
633 | def get_cached_parent_for_taxon ( self , child_taxon ) : if self . _ott_id2taxon is None : resp = child_taxon . _taxonomic_lineage [ 0 ] tl = child_taxon . _taxonomic_lineage [ 1 : ] assert 'taxonomic_lineage' not in resp resp [ 'taxonomic_lineage' ] = tl return TaxonWrapper ( taxonomy = child_taxon . taxonomy , taxoma... | If the taxa are being cached this call will create a the lineage spike for taxon child_taxon | 316 | 22 |
634 | def update_empty_fields ( self , * * kwargs ) : if self . _is_deprecated is None : self . _is_deprecated = kwargs . get ( 'is_deprecated' ) if self . _is_dubious is None : self . _is_dubious = kwargs . get ( 'is_dubious' ) if self . _is_synonym is None : self . _is_synonym = kwargs . get ( 'is_synonym' ) if self . _syn... | Updates the field of info about an OTU that might not be filled in by a match_names or taxon call . | 352 | 26 |
635 | def _check_rev_dict ( tree , ebt ) : ebs = defaultdict ( dict ) for edge in ebt . values ( ) : source_id = edge [ '@source' ] edge_id = edge [ '@id' ] ebs [ source_id ] [ edge_id ] = edge assert ebs == tree [ 'edgeBySourceId' ] | Verifyies that ebt is the inverse of the edgeBySourceId data member of tree | 81 | 19 |
636 | def _create_edge_by_target ( self ) : ebt = { } for edge_dict in self . _edge_by_source . values ( ) : for edge_id , edge in edge_dict . items ( ) : target_id = edge [ '@target' ] edge [ '@id' ] = edge_id assert target_id not in ebt ebt [ target_id ] = edge # _check_rev_dict(self._tree, ebt) return ebt | creates a edge_by_target dict with the same edge objects as the edge_by_source . Also adds an | 108 | 25 |
637 | def prune_to_ingroup ( self ) : # Prune to just the ingroup if not self . _ingroup_node_id : _LOG . debug ( 'No ingroup node was specified.' ) self . _ingroup_node_id = self . root_node_id elif self . _ingroup_node_id != self . root_node_id : self . _do_prune_to_ingroup ( ) self . root_node_id = self . _ingroup_node_id... | Remove nodes and edges from tree if they are not the ingroup or a descendant of it . | 137 | 19 |
638 | def prune_clade ( self , node_id ) : to_del_nodes = [ node_id ] while bool ( to_del_nodes ) : node_id = to_del_nodes . pop ( 0 ) self . _flag_node_as_del_and_del_in_by_target ( node_id ) ebsd = self . _edge_by_source . get ( node_id ) if ebsd is not None : child_edges = list ( ebsd . values ( ) ) to_del_nodes . extend ... | Prune node_id and the edges and nodes that are tipward of it . Caller must delete the edge to node_id . | 159 | 27 |
639 | def suppress_deg_one_node ( self , to_par_edge , nd_id , to_child_edge ) : # circumvent the node with nd_id to_child_edge_id = to_child_edge [ '@id' ] par = to_par_edge [ '@source' ] self . _edge_by_source [ par ] [ to_child_edge_id ] = to_child_edge to_child_edge [ '@source' ] = par # make it a tip... del self . _edge... | Deletes to_par_edge and nd_id . To be used when nd_id is an out - degree = 1 node | 145 | 29 |
640 | def describe ( self ) : return { "name" : self . name , "params" : self . params , "returns" : self . returns , "description" : self . description , } | Describes the method . | 42 | 5 |
641 | def params ( self ) : return [ { "name" : p_name , "type" : p_type . __name__ } for ( p_name , p_type ) in self . signature . parameter_types ] | The parameters for this method in a JSON - compatible format | 48 | 11 |
642 | def returns ( self ) : return_type = self . signature . return_type none_type = type ( None ) if return_type is not None and return_type is not none_type : return return_type . __name__ | The return type for this method in a JSON - compatible format . | 50 | 13 |
643 | def create ( parameter_names , parameter_types , return_type ) : ordered_pairs = [ ( name , parameter_types [ name ] ) for name in parameter_names ] return MethodSignature ( ordered_pairs , return_type ) | Returns a signature object ensuring order of parameter names and types . | 53 | 12 |
644 | def _hbf_handle_child_elements ( self , obj , ntl ) : # accumulate a list of the children names in ko, and # the a dictionary of tag to xml elements. # repetition of a tag means that it will map to a list of # xml elements cd = { } ko = [ ] ks = set ( ) for child in ntl : k = child . nodeName if k == 'meta' and ( not s... | Indirect recursion through _gen_hbf_el | 348 | 12 |
645 | def get_xml_parser ( encoding = None ) : parser = etree . ETCompatXMLParser ( huge_tree = True , remove_comments = True , strip_cdata = False , remove_blank_text = True , resolve_entities = False , encoding = encoding ) return parser | Returns an etree . ETCompatXMLParser instance . | 65 | 14 |
646 | def get_etree_root ( doc , encoding = None ) : tree = get_etree ( doc , encoding ) root = tree . getroot ( ) return root | Returns an instance of lxml . etree . _Element for the given doc input . | 36 | 18 |
647 | def strip_cdata ( text ) : if not is_cdata ( text ) : return text xml = "<e>{0}</e>" . format ( text ) node = etree . fromstring ( xml ) return node . text | Removes all CDATA blocks from text if it contains them . | 51 | 13 |
648 | def _is_valid ( self , value ) : # Entities have an istypeof method that can perform more sophisticated # type checking. if hasattr ( self . _type , "istypeof" ) : return self . _type . istypeof ( value ) else : return isinstance ( value , self . _type ) | Return True if the input value is valid for insertion into the inner list . | 70 | 15 |
649 | def _fix_value ( self , value ) : try : return self . _castfunc ( value ) except : error = "Can't put '{0}' ({1}) into a {2}. Expected a {3} object." error = error . format ( value , # Input value type ( value ) , # Type of input value type ( self ) , # Type of collection self . _type # Expected type of input value ) s... | Attempt to coerce value into the correct type . | 119 | 10 |
650 | def members_entries ( self , all_are_optional : Optional [ bool ] = False ) -> List [ Tuple [ str , str ] ] : if self . _type_reference : rval : List [ Tuple [ str , str ] ] = [ ] for n , t in self . _context . reference ( self . _type_reference ) . members_entries ( all_are_optional ) : rval . append ( ( n , self . _e... | Generate a list quoted raw name signature type entries for this pairdef recursively traversing reference types | 186 | 21 |
651 | def _initializer_for ( self , raw_name : str , cooked_name : str , prefix : Optional [ str ] ) -> List [ str ] : mt_val = self . _ebnf . mt_value ( self . _typ ) rval = [ ] if is_valid_python ( raw_name ) : if prefix : # If a prefix exists, the input has already been processed - no if clause is necessary rval . append ... | Create an initializer entry for the entry | 348 | 8 |
652 | def _assert_link_secret ( self , action : str ) : if self . _link_secret is None : LOGGER . debug ( 'HolderProver._assert_link_secret: action %s requires link secret but it is not set' , action ) raise AbsentLinkSecret ( 'Action {} requires link secret but it is not set' . format ( action ) ) | Raise AbsentLinkSecret if link secret is not set . | 80 | 12 |
653 | def rev_regs ( self ) -> list : LOGGER . debug ( 'HolderProver.rev_regs >>>' ) rv = [ basename ( f ) for f in Tails . links ( self . _dir_tails ) ] LOGGER . debug ( 'HolderProver.rev_regs <<< %s' , rv ) return rv | Return list of revocation registry identifiers for which HolderProver has tails files . | 81 | 15 |
654 | async def create_cred_req ( self , cred_offer_json : str , cd_id : str ) -> ( str , str ) : LOGGER . debug ( 'HolderProver.create_cred_req >>> cred_offer_json: %s, cd_id: %s' , cred_offer_json , cd_id ) self . _assert_link_secret ( 'create_cred_req' ) # Check that ledger has schema on ledger where cred def expects - in... | Create credential request as HolderProver and store in wallet ; return credential json and metadata json . | 377 | 19 |
655 | async def load_cache ( self , archive : bool = False ) -> int : LOGGER . debug ( 'HolderProver.load_cache >>> archive: %s' , archive ) rv = int ( time ( ) ) box_ids = json . loads ( await self . get_box_ids_json ( ) ) for s_id in box_ids [ 'schema_id' ] : with SCHEMA_CACHE . lock : await self . get_schema ( s_id ) for ... | Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet . | 366 | 20 |
656 | async def get_creds ( self , proof_req_json : str , filt : dict = None , filt_dflt_incl : bool = False ) -> ( Set [ str ] , str ) : LOGGER . debug ( 'HolderProver.get_creds >>> proof_req_json: %s, filt: %s' , proof_req_json , filt ) if filt is None : filt = { } rv = None creds_json = await anoncreds . prover_get_creden... | Get credentials from HolderProver wallet corresponding to proof request and filter criteria ; return credential identifiers from wallet and credentials json . Return empty set and empty production for no such credentials . | 719 | 35 |
657 | async def get_creds_by_id ( self , proof_req_json : str , cred_ids : set ) -> str : LOGGER . debug ( 'HolderProver.get_creds_by_id >>> proof_req_json: %s, cred_ids: %s' , proof_req_json , cred_ids ) creds_json = await anoncreds . prover_get_credentials_for_proof_req ( self . wallet . handle , proof_req_json ) # retain ... | Get creds structure from HolderProver wallet by credential identifiers . | 196 | 13 |
658 | def histogram ( data ) : ret = { } for datum in data : if datum in ret : ret [ datum ] += 1 else : ret [ datum ] = 1 return ret | Returns a histogram of your data . | 41 | 8 |
659 | def print_data ( data ) : print ( ", " . join ( [ "{}=>{}" . format ( key , value ) for key , value in data ] ) ) | Prints object key - value pairs in a custom format | 37 | 11 |
660 | def subdir_findall ( dir , subdir ) : strip_n = len ( dir . split ( '/' ) ) path = '/' . join ( ( dir , subdir ) ) return [ '/' . join ( s . split ( '/' ) [ strip_n : ] ) for s in setuptools . findall ( path ) ] | Find all files in a subdirectory and return paths relative to dir | 75 | 13 |
661 | def find_package_data ( packages ) : package_data = { } for package in packages : package_data [ package ] = [ ] for subdir in find_subdirectories ( package ) : if '.' . join ( ( package , subdir ) ) in packages : # skip submodules logging . debug ( "skipping submodule %s/%s" % ( package , subdir ) ) continue if skip_t... | For a list of packages find the package_data | 156 | 10 |
662 | def process_file_metrics ( context , file_processors ) : file_metrics = OrderedDict ( ) # TODO make available the includes and excludes feature gitignore = [ ] if os . path . isfile ( '.gitignore' ) : with open ( '.gitignore' , 'r' ) as ifile : gitignore = ifile . read ( ) . splitlines ( ) in_files = glob_files ( conte... | Main routine for metrics . | 353 | 5 |
663 | def process_build_metrics ( context , build_processors ) : build_metrics = OrderedDict ( ) # reset all processors for p in build_processors : p . reset ( ) # collect metrics from all processors for p in build_processors : build_metrics . update ( p . build_metrics ) return build_metrics | use processors to collect build metrics . | 77 | 7 |
664 | def summary ( processors , metrics , context ) : # display aggregated metric values on language level def display_header ( processors , before = '' , after = '' ) : """Display the header for the summary results.""" print ( before , end = ' ' ) for processor in processors : processor . display_header ( ) print ( after )... | Print the summary | 494 | 3 |
665 | def get_portfolios3 ( ) : g1 = [ 0 ] g2 = [ 1 ] g7 = [ 2 ] g13 = [ 3 ] g14 = [ 4 ] # sync cond g15 = [ 5 ] g16 = [ 6 ] g18 = [ 7 ] g21 = [ 8 ] g22 = [ 9 ] g23 = [ 10 , 11 ] portfolios = [ g1 + g15 + g18 , g2 + g16 + g21 , g13 + g22 , g7 + g23 ] passive = g14 # sync_cond return portfolios , passive | Returns portfolios with U12 and U20 generators removed and generators of the same type at the same bus aggregated . | 125 | 23 |
666 | def call ( self , tag_name : str , * args , * * kwargs ) : if hasattr ( self , tag_name ) : getattr ( self , tag_name ) ( * args , * * kwargs ) | Convenience method for calling methods with walker . | 51 | 11 |
667 | def der ( self , x : Sym ) : name = 'der({:s})' . format ( x . name ( ) ) if name not in self . scope [ 'dvar' ] . keys ( ) : self . scope [ 'dvar' ] [ name ] = self . sym . sym ( name , * x . shape ) self . scope [ 'states' ] . append ( x . name ( ) ) return self . scope [ 'dvar' ] [ name ] | Get the derivative of the variable create it if it doesn t exist . | 102 | 14 |
668 | def noise_gaussian ( self , mean , std ) : assert std > 0 ng = self . sym . sym ( 'ng_{:d}' . format ( len ( self . scope [ 'ng' ] ) ) ) self . scope [ 'ng' ] . append ( ng ) return mean + std * ng | Create a gaussian noise variable | 67 | 6 |
669 | def noise_uniform ( self , lower_bound , upper_bound ) : assert upper_bound > lower_bound nu = self . sym . sym ( 'nu_{:d}' . format ( len ( self . scope [ 'nu' ] ) ) ) self . scope [ 'nu' ] . append ( nu ) return lower_bound + nu * ( upper_bound - lower_bound ) | Create a uniform noise variable | 85 | 5 |
670 | def log ( self , * args , * * kwargs ) : if self . verbose : print ( ' ' * self . depth , * args , * * kwargs ) | Convenience function for printing indenting debug output . | 39 | 11 |
671 | def get_case6ww ( ) : path = os . path . dirname ( pylon . __file__ ) path = os . path . join ( path , "test" , "data" ) path = os . path . join ( path , "case6ww" , "case6ww.pkl" ) case = pylon . Case . load ( path ) case . generators [ 0 ] . p_cost = ( 0.0 , 4.0 , 200.0 ) case . generators [ 1 ] . p_cost = ( 0.0 , 3.... | Returns the 6 bus case from Wood & Wollenberg PG&C . | 391 | 15 |
672 | def get_case24_ieee_rts ( ) : path = os . path . dirname ( pylon . __file__ ) path = os . path . join ( path , "test" , "data" ) path = os . path . join ( path , "case24_ieee_rts" , "case24_ieee_rts.pkl" ) case = pylon . Case . load ( path ) # FIXME: Correct generator naming order. for g in case . generators : g . name... | Returns the 24 bus IEEE Reliability Test System . | 115 | 10 |
673 | def get_discrete_task_agent ( generators , market , nStates , nOffer , markups , withholds , maxSteps , learner , Pd0 = None , Pd_min = 0.0 ) : env = pyreto . discrete . MarketEnvironment ( generators , market , numStates = nStates , numOffbids = nOffer , markups = markups , withholds = withholds , Pd0 = Pd0 , Pd_min =... | Returns a tuple of task and agent for the given learner . | 178 | 13 |
674 | def get_zero_task_agent ( generators , market , nOffer , maxSteps ) : env = pyreto . discrete . MarketEnvironment ( generators , market , nOffer ) task = pyreto . discrete . ProfitTask ( env , maxSteps = maxSteps ) agent = pyreto . util . ZeroAgent ( env . outdim , env . indim ) return task , agent | Returns a task - agent tuple whose action is always zero . | 87 | 12 |
675 | def get_neg_one_task_agent ( generators , market , nOffer , maxSteps ) : env = pyreto . discrete . MarketEnvironment ( generators , market , nOffer ) task = pyreto . discrete . ProfitTask ( env , maxSteps = maxSteps ) agent = pyreto . util . NegOneAgent ( env . outdim , env . indim ) return task , agent | Returns a task - agent tuple whose action is always minus one . | 90 | 13 |
676 | def run_experiment ( experiment , roleouts , episodes , in_cloud = False , dynProfile = None ) : def run ( ) : if dynProfile is None : maxsteps = len ( experiment . profile ) # episode length else : maxsteps = dynProfile . shape [ 1 ] na = len ( experiment . agents ) ni = roleouts * episodes * maxsteps all_action = zer... | Runs the given experiment and returns the results . | 704 | 10 |
677 | def get_full_year ( ) : weekly = get_weekly ( ) daily = get_daily ( ) hourly_winter_wkdy , hourly_winter_wknd = get_winter_hourly ( ) hourly_summer_wkdy , hourly_summer_wknd = get_summer_hourly ( ) hourly_spring_autumn_wkdy , hourly_spring_autumn_wknd = get_spring_autumn_hourly ( ) fullyear = zeros ( 364 * 24 ) c = 0 l... | Returns percentages of peak load for all hours of the year . | 345 | 12 |
678 | def get_all_days ( ) : weekly = get_weekly ( ) daily = get_daily ( ) return [ w * ( d / 100.0 ) for w in weekly for d in daily ] | Returns percentages of peak load for all days of the year . Data from the IEEE RTS . | 43 | 19 |
679 | def get_q_experiment ( case , minor = 1 ) : gen = case . generators profile = array ( [ 1.0 ] ) maxSteps = len ( profile ) if minor == 1 : alpha = 0.3 # Learning rate. gamma = 0.99 # Discount factor # The closer epsilon gets to 0, the more greedy and less explorative. epsilon = 0.9 decay = 0.97 tau = 150.0 # Boltzmann ... | Returns an experiment that uses Q - learning . | 424 | 9 |
680 | def q_limited ( self ) : if ( self . q >= self . q_max ) or ( self . q <= self . q_min ) : return True else : return False | Is the machine at it s limit of reactive power? | 39 | 11 |
681 | def total_cost ( self , p = None , p_cost = None , pcost_model = None ) : p = self . p if p is None else p p_cost = self . p_cost if p_cost is None else p_cost pcost_model = self . pcost_model if pcost_model is None else pcost_model p = 0.0 if not self . online else p if pcost_model == PW_LINEAR : n_segments = len ( p_... | Computes total cost for the generator at the given output level . | 388 | 13 |
682 | def poly_to_pwl ( self , n_points = 4 ) : assert self . pcost_model == POLYNOMIAL p_min = self . p_min p_max = self . p_max p_cost = [ ] if p_min > 0.0 : # Make the first segment go from the origin to p_min. step = ( p_max - p_min ) / ( n_points - 2 ) y0 = self . total_cost ( 0.0 ) p_cost . append ( ( 0.0 , y0 ) ) x = ... | Sets the piece - wise linear cost attribute converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max . | 225 | 38 |
683 | def get_offers ( self , n_points = 6 ) : from pyreto . smart_market import Offer qtyprc = self . _get_qtyprc ( n_points ) return [ Offer ( self , qty , prc ) for qty , prc in qtyprc ] | Returns quantity and price offers created from the cost function . | 68 | 11 |
684 | def get_bids ( self , n_points = 6 ) : from pyreto . smart_market import Bid qtyprc = self . _get_qtyprc ( n_points ) return [ Bid ( self , qty , prc ) for qty , prc in qtyprc ] | Returns quantity and price bids created from the cost function . | 68 | 11 |
685 | def offers_to_pwl ( self , offers ) : assert not self . is_load # Only apply offers associated with this generator. g_offers = [ offer for offer in offers if offer . generator == self ] # Fliter out zero quantity offers. gt_zero = [ offr for offr in g_offers if round ( offr . quantity , 4 ) > 0.0 ] # Ignore withheld of... | Updates the piece - wise linear total cost function using the given offer blocks . | 415 | 16 |
686 | def bids_to_pwl ( self , bids ) : assert self . is_load # Apply only those bids associated with this dispatchable load. vl_bids = [ bid for bid in bids if bid . vLoad == self ] # Filter out zero quantity bids. gt_zero = [ bid for bid in vl_bids if round ( bid . quantity , 4 ) > 0.0 ] # Ignore withheld offers. valid_bid... | Updates the piece - wise linear total cost function using the given bid blocks . | 401 | 16 |
687 | def _adjust_limits ( self ) : if not self . is_load : # self.p_min = min([point[0] for point in self.p_cost]) self . p_max = max ( [ point [ 0 ] for point in self . p_cost ] ) else : p_min = min ( [ point [ 0 ] for point in self . p_cost ] ) self . p_max = 0.0 self . q_min = self . q_min * p_min / self . p_min self . q... | Sets the active power limits p_max and p_min according to the pwl cost function points . | 145 | 22 |
688 | def indim ( self ) : indim = self . numOffbids * len ( self . generators ) if self . maxWithhold is not None : return indim * 2 else : return indim | The number of action values that the environment accepts . | 43 | 10 |
689 | def _getBusVoltageLambdaSensor ( self ) : muVmin = array ( [ b . mu_vmin for b in self . market . case . connected_buses ] ) muVmax = array ( [ b . mu_vmax for b in self . market . case . connected_buses ] ) muVmin = - 1.0 * muVmin diff = muVmin + muVmax return diff | Returns an array of length nb where each value is the sum of the Lagrangian multipliers on the upper and the negative of the Lagrangian multipliers on the lower voltage limits . | 94 | 39 |
690 | def DoxyfileParse ( file_contents ) : data = { } import shlex lex = shlex . shlex ( instream = file_contents , posix = True ) lex . wordchars += "*+./-:" lex . whitespace = lex . whitespace . replace ( "\n" , "" ) lex . escape = "" lineno = lex . lineno token = lex . get_token ( ) key = token # the first token should b... | Parse a Doxygen source file and return a dictionary of all the values . Values will be strings and lists of strings . | 490 | 26 |
691 | def DoxySourceScan ( node , env , path ) : default_file_patterns = [ '*.c' , '*.cc' , '*.cxx' , '*.cpp' , '*.c++' , '*.java' , '*.ii' , '*.ixx' , '*.ipp' , '*.i++' , '*.inl' , '*.h' , '*.hh ' , '*.hxx' , '*.hpp' , '*.h++' , '*.idl' , '*.odl' , '*.cs' , '*.php' , '*.php3' , '*.inc' , '*.m' , '*.mm' , '*.py' , ] default_... | Doxygen Doxyfile source scanner . This should scan the Doxygen file and add any files used to generate docs to the list of source files . | 769 | 32 |
692 | def DoxyEmitter ( source , target , env ) : # possible output formats and their default values and output locations output_formats = { "HTML" : ( "YES" , "html" ) , "LATEX" : ( "YES" , "latex" ) , "RTF" : ( "NO" , "rtf" ) , "MAN" : ( "YES" , "man" ) , "XML" : ( "NO" , "xml" ) , } data = DoxyfileParse ( source [ 0 ] . g... | Doxygen Doxyfile emitter | 423 | 8 |
693 | def generate ( env ) : doxyfile_scanner = env . Scanner ( DoxySourceScan , "DoxySourceScan" , scan_check = DoxySourceScanCheck , ) import SCons . Builder doxyfile_builder = SCons . Builder . Builder ( action = "cd ${SOURCE.dir} && ${DOXYGEN} ${SOURCE.file}" , emitter = DoxyEmitter , target_factory = env . fs . Entry , ... | Add builders and construction variables for the Doxygen tool . This is currently for Doxygen 1 . 4 . 6 . | 159 | 25 |
694 | def reset ( self ) : self . _positions = [ ] self . _line = 1 self . _curr = None # current scope we are analyzing self . _scope = 0 self . language = None | Reset metric counter . | 44 | 5 |
695 | def add_scope ( self , scope_type , scope_name , scope_start , is_method = False ) : if self . _curr is not None : self . _curr [ 'end' ] = scope_start - 1 # close last scope self . _curr = { 'type' : scope_type , 'name' : scope_name , 'start' : scope_start , 'end' : scope_start } if is_method and self . _positions : l... | we identified a scope and add it to positions . | 168 | 10 |
696 | def process_token ( self , tok ) : if tok [ 0 ] == Token . Text : count = tok [ 1 ] . count ( '\n' ) if count : self . _line += count # adjust linecount if self . _detector . process ( tok ) : pass # works been completed in the detector elif tok [ 0 ] == Token . Punctuation : if tok [ 0 ] == Token . Punctuation and tok... | count lines and track position of classes and functions | 282 | 9 |
697 | def _unpack_model ( self , om ) : buses = om . case . connected_buses branches = om . case . online_branches gens = om . case . online_generators cp = om . get_cost_params ( ) # Bf = om._Bf # Pfinj = om._Pfinj return buses , branches , gens , cp | Returns data from the OPF model . | 81 | 8 |
698 | def _dimension_data ( self , buses , branches , generators ) : ipol = [ i for i , g in enumerate ( generators ) if g . pcost_model == POLYNOMIAL ] ipwl = [ i for i , g in enumerate ( generators ) if g . pcost_model == PW_LINEAR ] nb = len ( buses ) nl = len ( branches ) # Number of general cost vars, w. nw = self . om ... | Returns the problem dimensions . | 200 | 5 |
699 | def _linear_constraints ( self , om ) : A , l , u = om . linear_constraints ( ) # l <= A*x <= u # Indexes for equality, greater than (unbounded above), less than # (unbounded below) and doubly-bounded box constraints. # ieq = flatnonzero( abs(u - l) <= EPS ) # igt = flatnonzero( (u >= 1e10) & (l > -1e10) ) # ilt = flat... | Returns the linear problem constraints . | 459 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.