signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_db ( data ) : """Retrieve a snpEff database name and location relative to reference file ."""
snpeff_db = utils . get_in ( data , ( "genome_resources" , "aliases" , "snpeff" ) ) snpeff_base_dir = None if snpeff_db : snpeff_base_dir = utils . get_in ( data , ( "reference" , "snpeff" ) ) if not ( isinstance ( snpeff_base_dir , six . string_types ) and os . path . isdir ( snpeff_base_dir ) ) : snpe...
def error_handler_404 ( request ) : """500 error handler which includes ` ` request ` ` in the context . Templates : ` 500 . html ` Context : None"""
from django . template import Context , loader from django . http import HttpResponseServerError t = loader . get_template ( '404.html' ) return HttpResponseServerError ( t . render ( Context ( { 'request' : request , 'settings' : settings , } ) ) )
def wid_to_gid ( wid ) : """Calculate gid of a worksheet from its wid ."""
widval = wid [ 1 : ] if len ( wid ) > 3 else wid xorval = 474 if len ( wid ) > 3 else 31578 return str ( int ( widval , 36 ) ^ xorval )
def set_file_logger ( path , log_level = logging . DEBUG , format_string = None , logger_name = 'smc' ) : """Convenience function to quickly configure any level of logging to a file . : param int log _ level : A log level as specified in the ` logging ` module : param str format _ string : Optional format str...
if format_string is None : format_string = LOG_FORMAT log = logging . getLogger ( logger_name ) log . setLevel ( log_level ) # create file handler and set level ch = logging . FileHandler ( path ) ch . setLevel ( log_level ) # create formatter formatter = logging . Formatter ( format_string ) # add formatter to ch ...
def _ParseSubKey ( self , parser_mediator , registry_key , parent_path_segments , codepage = 'cp1252' ) : """Extract event objects from a MRUListEx Registry key . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . registry _...
try : mrulistex = self . _ParseMRUListExValue ( registry_key ) except ( ValueError , errors . ParseError ) as exception : parser_mediator . ProduceExtractionWarning ( 'unable to parse MRUListEx value with error: {0!s}' . format ( exception ) ) return if not mrulistex : return entry_numbers = { } values_...
def backward_char ( self , e ) : # ( C - b ) u"""Move back a character ."""
self . l_buffer . backward_char ( self . argument_reset ) self . finalize ( )
def make_client ( servers : Sequence [ str ] , * args , ** kwargs ) -> GMatrixClient : """Given a list of possible servers , chooses the closest available and create a GMatrixClient Params : servers : list of servers urls , with scheme ( http or https ) Rest of args and kwargs are forwarded to GMatrixClient c...
if len ( servers ) > 1 : sorted_servers = [ server_url for ( server_url , _ ) in sort_servers_closest ( servers ) ] log . info ( 'Automatically selecting matrix homeserver based on RTT' , sorted_servers = sorted_servers , ) elif len ( servers ) == 1 : sorted_servers = servers else : raise TransportError...
def get_deviation_content ( self , deviationid ) : """Fetch full data that is not included in the main devaition object The endpoint works with journals and literatures . Deviation objects returned from API contain only excerpt of a journal , use this endpoint to load full content . Any custom CSS rules and fon...
response = self . _req ( '/deviation/content' , { 'deviationid' : deviationid } ) content = { } if "html" in response : content [ 'html' ] = response [ 'html' ] if "css" in response : content [ 'css' ] = response [ 'css' ] if "css_fonts" in response : content [ 'css_fonts' ] = response [ 'css_fonts' ] retur...
def ip_rtm_config_route_static_route_oif_static_route_oif_type ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" ) rtm_config = ET . SubElement ( ip , "rtm-config" , xmlns = "urn:brocade.com:mgmt:brocade-rtm" ) route = ET . SubElement ( rtm_config , "route" ) static_route_oif = ET . SubElement ( route , "sta...
def render_template ( template_name , ** context ) : """Render a template into a response ."""
tmpl = jinja_env . get_template ( template_name ) context [ "url_for" ] = url_for return Response ( tmpl . render ( context ) , mimetype = "text/html" )
def rel_path ( base , path ) : """Return path relative to base ."""
if base == path : return '' assert is_prefix ( base , path ) , "{} not a prefix of {}" . format ( base , path ) return path [ len ( base ) : ] . strip ( '.' )
def __recognize_user_class ( self , node : yaml . Node , expected_type : Type ) -> RecResult : """Recognize a user - defined class in the node . This tries to recognize only exactly the specified class . It recurses down into the class ' s attributes , but not to its subclasses . See also _ _ recognize _ user _ c...
logger . debug ( 'Recognizing as a user-defined class' ) loc_str = '{}{}' . format ( node . start_mark , os . linesep ) if hasattr ( expected_type , 'yatiml_recognize' ) : try : unode = UnknownNode ( self , node ) expected_type . yatiml_recognize ( unode ) return [ expected_type ] , '' e...
async def approve ( self , remark : str = '' ) -> None : """Approve the request . : param remark : remark of friend ( only works in friend request )"""
try : await self . bot . call_action ( action = '.handle_quick_operation_async' , self_id = self . ctx . get ( 'self_id' ) , context = self . ctx , operation = { 'approve' : True , 'remark' : remark } ) except CQHttpError : pass
def remote ( self , func , * args , xfer_func = None , ** kwargs ) : """Calls func with the indicated args on the micropython board ."""
global HAS_BUFFER HAS_BUFFER = self . has_buffer if hasattr ( func , 'extra_funcs' ) : func_name = func . name func_lines = [ ] for extra_func in func . extra_funcs : func_lines += inspect . getsource ( extra_func ) . split ( '\n' ) func_lines += [ '' ] func_lines += filter ( lambda line...
def activate ( self , auth , codetype , code , defer = False ) : """Given an activation code , activate an entity for the client specified in < ResourceID > . Args : auth : < cik > codetype : Type of code being activated . code : Code to activate ."""
return self . _call ( 'activate' , auth , [ codetype , code ] , defer )
def _compute_dy_dtau ( self , tau , b , r2l2 ) : r"""Evaluate the derivative of the inner argument of the Matern kernel . Take the derivative of . . math : : y = 2 \ nu \ sum _ i ( \ tau _ i ^ 2 / l _ i ^ 2) Parameters tau : : py : class : ` Matrix ` , ( ` M ` , ` D ` ) ` M ` inputs with dimension ` D `...
if len ( b ) == 0 : return self . _compute_y ( tau ) elif len ( b ) == 1 : return 4.0 * self . nu * tau [ : , b [ 0 ] ] / ( self . params [ 2 + b [ 0 ] ] ) ** 2.0 elif ( len ( b ) == 2 ) and ( b [ 0 ] == b [ 1 ] ) : return 4.0 * self . nu / ( self . params [ 2 + b [ 0 ] ] ) ** 2.0 else : return scipy . ...
def makeResultsTable ( caption , panels , counts , filename , label ) : '''Make a time series regression results table by piecing together one or more panels . Saves a tex file to disk in the tables directory . Parameters caption : str or None Text to apply at the start of the table as a title . If None , t...
if caption is not None : note_size = '\\footnotesize' else : note_size = '\\tiny' note = '\\multicolumn{6}{p{0.95\\textwidth}}{' + note_size + ' \\textbf{Notes:} ' if counts [ 1 ] > 1 : note += 'Reported statistics are the average values for ' + str ( counts [ 1 ] ) + ' samples of ' + str ( counts [ 0 ] ) +...
def get_file_extension ( format_ ) : """Format identifier - > file extension"""
if format_ not in FORMAT_IDENTIFIER_TO_FORMAT_CLASS : raise UnknownFormatIdentifierError ( format_ ) for ext , f in FILE_EXTENSION_TO_FORMAT_IDENTIFIER . items ( ) : if f == format_ : return ext raise RuntimeError ( "No file extension for format %r" % format_ )
def parse_patients ( job , patient_dict , skip_fusions = False ) : """Parse a dict of patient entries to retain only the useful entries ( The user may provide more than we need and we don ' t want to download redundant things ) : param dict patient _ dict : The dict of patient entries parsed from the input conf...
output_dict = { 'ssec_encrypted' : patient_dict . get ( 'ssec_encrypted' ) in ( True , 'True' , 'true' ) , 'patient_id' : patient_dict [ 'patient_id' ] , 'tumor_type' : patient_dict [ 'tumor_type' ] , 'filter_for_OxoG' : patient_dict . get ( 'filter_for_OxoG' ) in ( True , 'True' , 'true' ) } out_keys = set ( ) if 'hla...
def encode ( obj , sedes = None , infer_serializer = True , cache = True ) : """Encode a Python object in RLP format . By default , the object is serialized in a suitable way first ( using : func : ` rlp . infer _ sedes ` ) and then encoded . Serialization can be explicitly suppressed by setting ` infer _ ser...
if isinstance ( obj , Serializable ) : cached_rlp = obj . _cached_rlp if sedes is None and cached_rlp : return cached_rlp else : really_cache = ( cache and sedes is None ) else : really_cache = False if sedes : item = sedes . serialize ( obj ) elif infer_serializer : item = infer...
def AddGroupTags ( r , group , tags , dry_run = False ) : """Adds tags to a node group . @ type group : str @ param group : group to add tags to @ type tags : list of string @ param tags : tags to add to the group @ type dry _ run : bool @ param dry _ run : whether to perform a dry run @ rtype : strin...
query = { "dry-run" : dry_run , "tag" : tags , } return r . request ( "put" , "/2/groups/%s/tags" % group , query = query )
def get_overlay ( self , overlay_name ) : """Return overlay as a dictionary . : param overlay _ name : name of the overlay : returns : overlay as a dictionary"""
url = self . http_manifest [ "overlays" ] [ overlay_name ] return self . _get_json_from_url ( url )
def rerun_process ( self , pid , title = None , agent = None ) : '''rerun _ process ( self , pid , title = None , agent = None ) Reruns a process : Parameters : * * pid * ( ` string ` ) - - Process id to rerun * * title * ( ` string ` ) - - Title for the process * * agent * ( ` string ` ) - - a valid valu...
request_data = { } if title : request_data [ 'name' ] = title if agent : request_data [ 'agents' ] = agent if self . input . get ( 'pid' ) : request_data [ 'pflow_id' ] = self . input . get ( 'pid' ) ret_data = self . _call_rest_api ( 'post' , '/processes/' + pid + '/rerun' , data = request_data , error = '...
def get_service ( service , model_form = 'models' , form_name = '' ) : """get the service name then load the model : param service : the service name : param model _ form : could be ' models ' or ' forms ' : param form _ name : the name of the form is model _ form is ' forms ' : type service : string : ty...
service_name = str ( service ) . split ( 'Service' ) [ 1 ] class_name = 'th_' + service_name . lower ( ) + '.' + model_form if model_form == 'forms' : return class_for_name ( class_name , service_name + form_name ) else : return class_for_name ( class_name , service_name )
def article_parse ( self , response , rss_title = None ) : """Checks any given response on being an article and if positiv , passes the response to the pipeline . : param obj response : The scrapy response : param str rss _ title : Title extracted from the rss feed"""
if not self . helper . parse_crawler . content_type ( response ) : return yield self . helper . parse_crawler . pass_to_pipeline_if_article ( response , self . ignored_allowed_domain , self . original_url , rss_title )
def fromstring ( cls , dis_string ) : """Create a DisRSTTree instance from a string containing a * . dis parse ."""
temp = tempfile . NamedTemporaryFile ( delete = False ) temp . write ( dis_string ) temp . close ( ) dis_tree = cls ( dis_filepath = temp . name ) os . unlink ( temp . name ) return dis_tree
def _smartos_zone_pkgin_data ( ) : '''SmartOS zone pkgsrc information'''
# Provides : # pkgin _ repositories grains = { 'pkgin_repositories' : [ ] , } pkginrepo = re . compile ( '^(?:https|http|ftp|file)://.*$' ) if os . path . isfile ( '/opt/local/etc/pkgin/repositories.conf' ) : with salt . utils . files . fopen ( '/opt/local/etc/pkgin/repositories.conf' , 'r' ) as fp_ : for l...
def revert ( self ) : """Delete the temporary program file ."""
if self . program_fp : self . program_fp . close ( ) super ( ProgramRunner , self ) . revert ( )
def _solve ( self , x0 , A , l , u , xmin , xmax ) : """Solves using Python Interior Point Solver ( PIPS ) ."""
s = pips ( self . _costfcn , x0 , A , l , u , xmin , xmax , self . _consfcn , self . _hessfcn , self . opt ) return s
def maybe_raise ( cls , error_type , ignores = None ) : """Raise an : exc : ` LibError ` unless the ` ` error _ type ` ` is : attr : ` ErrorType . OK ` or in the ` ` ignores ` ` list of error types . Internal method ."""
ignores = set ( ignores or [ ] ) ignores . add ( ErrorType . Ok ) if error_type not in ignores : raise LibError ( error_type )
def _set_port_security ( self , v , load = False ) : """Setter method for port _ security , mapped from YANG variable / interface / ethernet / switchport / port _ security ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ port _ security is considered as a p...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = port_security . port_security , is_container = 'container' , presence = True , yang_name = "port-security" , rest_name = "port-security" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , ...
def _miraligner ( fastq_file , out_file , species , db_folder , config ) : """Run miraligner tool ( from seqcluster suit ) with default parameters ."""
resources = config_utils . get_resources ( "miraligner" , config ) miraligner = config_utils . get_program ( "miraligner" , config ) jvm_opts = "-Xms750m -Xmx4g" if resources and resources . get ( "jvm_opts" ) : jvm_opts = " " . join ( resources . get ( "jvm_opts" ) ) export = _get_env ( ) cmd = ( "{export} {mirali...
def get_tenant_base_schema ( ) : """If TENANT _ CREATION _ FAKES _ MIGRATIONS , tenants will be created by cloning an existing schema specified by TENANT _ CLONE _ BASE ."""
schema = getattr ( settings , 'TENANT_BASE_SCHEMA' , False ) if schema : if not getattr ( settings , 'TENANT_CREATION_FAKES_MIGRATIONS' , False ) : raise ImproperlyConfigured ( 'TENANT_CREATION_FAKES_MIGRATIONS setting must be True to use ' 'TENANT_BASE_SCHEMA for cloning.' ) return schema
def destroy_by_name ( name , driver ) : """Destroy all nodes matching specified name"""
matches = [ node for node in list_nodes ( driver ) if node . name == name ] if len ( matches ) == 0 : logger . warn ( 'no node named %s' % name ) return False else : return all ( [ node . destroy ( ) for node in matches ] )
def info ( self , domain_id = None , domain = None ) : '''Get information for a specific domain Specify a domain by either ` ` domain _ id ` ` or ` ` domain ` ` , if both are specified , then ` ` domain _ id ` ` is used . : param str domain _ id : Domain ID : param str domain : Domain : return : Domain ob...
if domain_id != None : r = self . _api . do_post ( 'Domain.Info' , domain_id = domain_id ) elif domain != None : r = self . _api . do_post ( 'Domain.Info' , domain = domain ) else : raise DNSPodError ( 'Both domain_id and domain are not specificed' ) return Domain ( r [ 'domain' ] )
def translocation ( from_loc , to_loc ) : """Make a translocation dictionary . : param dict from _ loc : An entity dictionary from : func : ` pybel . dsl . entity ` : param dict to _ loc : An entity dictionary from : func : ` pybel . dsl . entity ` : rtype : dict"""
rv = _activity_helper ( TRANSLOCATION ) rv [ EFFECT ] = { FROM_LOC : Entity ( namespace = BEL_DEFAULT_NAMESPACE , name = from_loc ) if isinstance ( from_loc , str ) else from_loc , TO_LOC : Entity ( namespace = BEL_DEFAULT_NAMESPACE , name = to_loc ) if isinstance ( to_loc , str ) else to_loc , } return rv
def default_estimate ( opt_meth : Type [ OptimizationMethod ] , mo_prob : MOProblem , dp : int = 2 ) -> Tuple [ List [ float ] , List [ float ] ] : """The recommended nadir / ideal estimator - use a payoff table and then round off the result ."""
return round_off ( estimate_payoff_table ( opt_meth , mo_prob ) , dp )
def _init_boto3_clients ( self ) : """The utililty requires boto3 clients to Cloud Formation and S3 . Here is where we make them . Args : None Returns : Good or Bad ; True or False"""
try : profile = self . _config . get ( 'environment' , { } ) . get ( 'profile' ) region = self . _config . get ( 'environment' , { } ) . get ( 'region' ) if profile : self . _b3Sess = boto3 . session . Session ( profile_name = profile ) else : self . _b3Sess = boto3 . session . Session (...
def translate ( client , event , channel , nick , rest ) : """Translate a phrase using Google Translate . First argument should be the language [ s ] . It is a 2 letter abbreviation . It will auto detect the orig lang if you only give one ; or two languages joined by a | , for example ' en | de ' to trans fro...
try : set_key ( ) except Exception : return ( "No API key configured. Google charges for translation. " "Please register for an API key at " "https://code.google.com/apis/console/?api=translate&promo=tr " "and set the 'Google API key' config variable to a valid key" ) rest = rest . strip ( ) langpair , _ , rest...
def delete_asset ( self , asset_id = None ) : """Deletes an ` ` Asset ` ` . arg : asset _ id ( osid . id . Id ) : the ` ` Id ` ` of the ` ` Asset ` ` to remove raise : NotFound - ` ` asset _ id ` ` not found raise : NullArgument - ` ` asset _ id ` ` is ` ` null ` ` raise : OperationFailed - unable to comp...
# Implemented from awsosid template for - # osid . resource . ResourceAdminSession . delete _ resource _ template # clean up AWS asset = self . _asset_lookup_session . get_asset ( asset_id ) for ac in asset . asset_contents : self . delete_asset_content ( ac . ident ) self . _provider_session . delete_asset ( asset...
def find_numeration ( line ) : """Given a reference line , attempt to locate instances of citation ' numeration ' in the line . @ param line : ( string ) the reference line . @ return : ( string ) the reference line after numeration has been checked and possibly recognized / marked - up ."""
patterns = ( # vol , page , year re_numeration_vol_page_yr , re_numeration_vol_nucphys_page_yr , re_numeration_nucphys_vol_page_yr , # With sub volume re_numeration_vol_subvol_nucphys_yr_page , re_numeration_vol_nucphys_yr_subvol_page , # vol , year , page re_numeration_vol_yr_page , re_numeration_nucphys_vol_yr_page ,...
def add_comment ( self , comment , metadata = "" ) : """Add a canned comment : type comment : str : param comment : New canned comment : type metadata : str : param metadata : Optional metadata : rtype : dict : return : A dictionnary containing canned comment description"""
data = { 'comment' : comment , 'metadata' : metadata } return self . post ( 'createComment' , data )
def qtdoc_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : """Links to a Qt class ' s doc Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages . Both are allowed to be empty . : param name : The role name used in the docum...
base = 'http://qt-project.org/doc/qt-4.8/' match = re . search ( '([^<]+)(<[^<>]+>)?' , text ) if match is None : raise ValueError label = match . group ( 1 ) if match . lastindex == 2 : # remove the carots from second group clsmeth = match . group ( 2 ) [ 1 : - 1 ] # assumes single . separating a class and...
def check_version ( self , check , timeout = None , metadata = None , credentials = None ) : """Returns the version of the Dgraph instance ."""
return self . stub . CheckVersion ( check , timeout = timeout , metadata = metadata , credentials = credentials )
def reset ( self , name ) : """Reset assigned value for field . Resetting a field will return it to its default value or None . Args : name : Name of field to reset ."""
message_type = type ( self ) try : field = message_type . field_by_name ( name ) except KeyError : if name not in message_type . __by_name : raise AttributeError ( 'Message %s has no field %s' % ( message_type . __name__ , name ) ) if field . repeated : self . __tags [ field . number ] = FieldList (...
def before_scenario ( context , scenario ) : """Prepare a fresh environment for each scenario ."""
# Prepare a new temporary directory . context . directory = testfixtures . TempDirectory ( create = True ) context . old_cwd = os . getcwd ( ) context . new_cwd = context . directory . path # Move into our new working directory . os . chdir ( context . new_cwd )
def _open_file_obj ( f , mode = "r" ) : """A context manager that provides access to a file . : param f : the file to be opened : type f : a file - like object or path to file : param mode : how to open the file : type mode : string"""
if isinstance ( f , six . string_types ) : if f . startswith ( ( "http://" , "https://" ) ) : file_obj = _urlopen ( f ) yield file_obj file_obj . close ( ) else : with open ( f , mode ) as file_obj : yield file_obj else : yield f
def add_nodes ( self , node_name_list , dataframe = False ) : """Add new nodes to the network : param node _ name _ list : list of node names , e . g . [ ' a ' , ' b ' , ' c ' ] : param dataframe : If True , return a pandas dataframe instead of a dict . : return : A dict mapping names to SUIDs for the newly -...
res = self . session . post ( self . __url + 'nodes' , data = json . dumps ( node_name_list ) , headers = HEADERS ) check_response ( res ) nodes = res . json ( ) if dataframe : return pd . DataFrame ( nodes ) . set_index ( [ 'SUID' ] ) else : return { node [ 'name' ] : node [ 'SUID' ] for node in nodes }
async def verify ( self , message : bytes , signature : bytes , signer : str = None ) -> bool : """Verify signature with input signer verification key ( via lookup by DID first if need be ) . Raise WalletState if wallet is closed . : param message : Content to sign , as bytes : param signature : signature , a...
LOGGER . debug ( 'BaseAnchor.verify >>> signer: %s, message: %s, signature: %s' , signer , message , signature ) if not self . wallet . handle : LOGGER . debug ( 'BaseAnchor.verify <!< Wallet %s is closed' , self . name ) raise WalletState ( 'Wallet {} is closed' . format ( self . name ) ) verkey = None if sign...
def split ( self ) : """Split the : class : ` FileSequence ` into contiguous pieces and return them as a list of : class : ` FileSequence ` instances . Returns : list [ : class : ` FileSequence ` ] :"""
result = [ ] for frange in self . frameRange ( ) . split ( "," ) : result . append ( FileSequence ( '' . join ( ( self . _dir , self . _base , frange , self . _pad , self . _ext ) ) ) ) return result
def jsonify ( obj , status = 200 , headers = None , refs = False , encoder = JSONEncoder ) : """Custom JSONificaton to support obj . to _ dict protocol ."""
if encoder is JSONEncoder : data = encoder ( refs = refs ) . encode ( obj ) else : data = encoder ( ) . encode ( obj ) if 'callback' in request . args : cb = request . args . get ( 'callback' ) data = '%s && %s(%s)' % ( cb , cb , data ) return Response ( data , headers = headers , status = status , mime...
def next ( self ) : """Returns the next item in the cursor ."""
if self . _current_index < len ( self . _collection ) : value = self . _collection [ self . _current_index ] self . _current_index += 1 return value elif self . _next_cursor : self . __fetch_next ( ) return self . next ( ) else : self . _current_index = 0 raise StopIteration
def create_module ( self , spec ) : """Creates the module , and also insert it into sys . modules , adding this onto py2 import logic ."""
mod = sys . modules . setdefault ( spec . name , types . ModuleType ( spec . name ) ) # we are using setdefault to satisfy https : / / docs . python . org / 3 / reference / import . html # loaders return mod
def save ( self , filething = None , deleteid3 = False , padding = None ) : """Save metadata blocks to a file . Args : filething ( filething ) deleteid3 ( bool ) : delete id3 tags while at it padding ( : obj : ` mutagen . PaddingFunction ` ) If no filename is given , the one most recently loaded is used ....
self . _save ( filething , self . metadata_blocks , deleteid3 , padding )
def add_atlas_zonefile_data ( zonefile_text , zonefile_dir , fsync = True ) : """Add a zone file to the atlas zonefiles Return True on success Return False on error"""
rc = store_atlas_zonefile_data ( zonefile_text , zonefile_dir , fsync = fsync ) if not rc : zonefile_hash = get_zonefile_data_hash ( zonefile_text ) log . error ( "Failed to save zonefile {}" . format ( zonefile_hash ) ) rc = False return rc
def _format_trace ( trace ) : """Convert the ( stripped ) stack - trace to a nice readable format . The stack trace ` trace ` is a list of frame records as returned by * * inspect . stack * * but without the frame objects . Returns a string ."""
lines = [ ] for fname , lineno , func , src , _ in trace : if src : for line in src : lines . append ( ' ' + line . strip ( ) + '\n' ) lines . append ( ' %s:%4d in %s\n' % ( fname , lineno , func ) ) return '' . join ( lines )
def open ( self , * args , ** kwargs ) : """Works exactly like the Telnet . open ( ) call from the telnetlib module , except SSL / TLS may be transparently negotiated ."""
Telnet . open ( self , * args , ** kwargs ) if self . force_ssl : self . _start_tls ( )
def _execution ( self ) : """Context manager for executing some JavaScript inside a template ."""
did_start_executing = False if self . state == STATE_DEFAULT : did_start_executing = True self . state = STATE_EXECUTING def close ( ) : if did_start_executing and self . state == STATE_EXECUTING : self . state = STATE_DEFAULT yield close close ( )
def adapter_remove_nio_binding ( self , adapter_number ) : """Removes an adapter NIO binding . : param adapter _ number : adapter number : returns : NIO instance"""
try : adapter = self . _ethernet_adapters [ adapter_number ] except IndexError : raise VMwareError ( "Adapter {adapter_number} doesn't exist on VMware VM '{name}'" . format ( name = self . name , adapter_number = adapter_number ) ) nio = adapter . get_nio ( 0 ) if isinstance ( nio , NIOUDP ) : self . manage...
def to_madeline ( self ) : """Return the individual info in a madeline formated string"""
# Convert sex to madeleine type self . logger . debug ( "Returning madeline info" ) if self . sex == 1 : madeline_gender = 'M' elif self . sex == 2 : madeline_gender = 'F' else : madeline_gender = '.' # Convert father to madeleine type if self . father == '0' : madeline_father = '.' else : madeline_...
def get_text_content_for_pmids ( pmids ) : """Get text content for articles given a list of their pmids Parameters pmids : list of str Returns text _ content : list of str"""
pmc_pmids = set ( pmc_client . filter_pmids ( pmids , source_type = 'fulltext' ) ) pmc_ids = [ ] for pmid in pmc_pmids : pmc_id = pmc_client . id_lookup ( pmid , idtype = 'pmid' ) [ 'pmcid' ] if pmc_id : pmc_ids . append ( pmc_id ) else : pmc_pmids . discard ( pmid ) pmc_xmls = [ ] failed = ...
def generate_json_artifacts ( app , pagename , templatename , context , doctree ) : """Generate JSON artifacts for each page . This way we can skip generating this in other build step ."""
try : # We need to get the output directory where the docs are built # _ build / json . build_json = os . path . abspath ( os . path . join ( app . outdir , '..' , 'json' ) ) outjson = os . path . join ( build_json , pagename + '.fjson' ) outdir = os . path . dirname ( outjson ) if not os . path . exist...
def parse ( self , text , noprefix = False ) : """Parse date and time from given date string . : param text : Any human readable string : type date _ string : str | unicode : param noprefix : If set True than doesn ' t use prefix based date patterns filtering settings : type noprefix : bool : return :...
res = self . match ( text , noprefix ) if res : r = res [ 'values' ] p = res [ 'pattern' ] d = { 'month' : 0 , 'day' : 0 , 'year' : 0 } if 'noyear' in p and p [ 'noyear' ] == True : d [ 'year' ] = datetime . datetime . now ( ) . year for k , v in list ( r . items ( ) ) : d [ k ] = in...
def get_installed_version ( vcs ) : """Get the installed version for this project . Args : vcs ( easyci . vcs . base . Vcs ) Returns : str - version number Raises : VersionNotInstalledError"""
version_path = _get_version_path ( vcs ) if not os . path . exists ( version_path ) : raise VersionNotInstalledError with open ( version_path , 'r' ) as f : return f . read ( ) . strip ( )
def create ( self , name , ** kwds ) : """Endpoint : / album / create . json Creates a new album and returns it ."""
result = self . _client . post ( "/album/create.json" , name = name , ** kwds ) [ "result" ] return Album ( self . _client , result )
def add_outward_edge ( self , v , e ) : """Add an outward edge to a vertex : param v : The source vertex . : param e : The name of the outward edge ."""
self . add_vertex ( v ) self . graph . add_vertex ( e ) self . es . add ( e ) self . graph . add_edge ( e , v )
def _load_info_lbl ( self ) : """Load info on the image Note : If the image is from LOLA , the . LBL is parsed and the information is returned . If the image is from WAC , the . IMG file is parsed using the library ` pvl ` _ which provide nice method to extract the information in the header of the image...
if self . grid == 'WAC' : label = load_label ( self . img ) for key , val in label . iteritems ( ) : if type ( val ) == pvl . _collections . PVLObject : for key , value in val . iteritems ( ) : try : setattr ( self , key , value . value ) e...
def generate_config_set ( self , config ) : '''Generates a list of magnitude frequency distributions and renders as a tuple : param dict / list config : Configuration paramters of magnitude frequency distribution'''
if isinstance ( config , dict ) : # Configuration list contains only one element self . config = [ ( config , 1.0 ) ] elif isinstance ( config , list ) : # Multiple configurations with correscponding weights total_weight = 0. self . config = [ ] for params in config : weight = params [ 'Model_We...
def moveto ( self , x , y , scale = 1 ) : """Move and scale element . Parameters x , y : float displacement in x and y coordinates in user units ( ' px ' ) . scale : float scaling factor . To scale down scale < 1 , scale up scale > 1. For no scaling scale = 1."""
self . root . set ( "transform" , "translate(%s, %s) scale(%s) %s" % ( x , y , scale , self . root . get ( "transform" ) or '' ) )
def addUnexpectedSuccess ( self , test ) : """Register a test that passed unexpectedly . Parameters test : unittest . TestCase The test that has completed ."""
result = self . _handle_result ( test , TestCompletionStatus . unexpected_success ) self . unexpectedSuccesses . append ( result )
def render ( template_name , context = None , code = 200 , headers = None ) : """Render a response using standard Nikola templates . : param str template _ name : Template name : param dict context : Context ( variables ) to use in the template : param int code : HTTP status code : param headers : Headers t...
if context is None : context = { } if headers is None : headers = { } context [ 'g' ] = g context [ 'request' ] = request context [ 'session' ] = session context [ 'current_user' ] = current_user context [ '_author_get' ] = _author_get context [ '_author_uid_get' ] = _author_uid_get if app . config [ 'COIL_URL'...
def from_string ( cls , s ) : """Instantiate a ` Derivation ` from a UDF or UDX string representation . The UDF / UDX representations are as output by a processor like the ` LKB < http : / / moin . delph - in . net / LkbTop > ` _ or ` ACE < http : / / sweaglesw . org / linguistics / ace / > ` _ , or from the ...
if not ( s . startswith ( '(' ) and s . endswith ( ')' ) ) : raise ValueError ( 'Derivations must begin and end with parentheses: ( )' ) s_ = s [ 1 : ] # get rid of initial open - parenthesis stack = [ ] deriv = None try : matches = cls . udf_re . finditer ( s_ ) for match in matches : if match . gr...
def json ( self , attribs = None , recurse = True , ignorelist = False ) : """See : meth : ` AbstractElement . json `"""
if not attribs : attribs = { } if self . idref : attribs [ 'id' ] = self . idref return super ( AbstractTextMarkup , self ) . json ( attribs , recurse , ignorelist )
def _init_digit_argument ( self , keyinfo ) : """Initialize search prompt"""
c = self . console line = self . l_buffer . get_line_text ( ) self . _digit_argument_oldprompt = self . prompt queue = self . process_keyevent_queue queue = self . process_keyevent_queue queue . append ( self . _process_digit_argument_keyevent ) if keyinfo . char == "-" : self . argument = - 1 elif keyinfo . char i...
def _update_Frxy ( self ) : """Update ` Frxy ` from ` piAx _ piAy _ beta ` , ` ln _ piAx _ piAy _ beta ` , ` omega ` , ` beta ` ."""
self . Frxy . fill ( 1.0 ) self . Frxy_no_omega . fill ( 1.0 ) with scipy . errstate ( divide = 'raise' , under = 'raise' , over = 'raise' , invalid = 'ignore' ) : scipy . copyto ( self . Frxy_no_omega , - self . ln_piAx_piAy_beta / ( 1 - self . piAx_piAy_beta ) , where = scipy . logical_and ( CODON_NONSYN , scipy ...
def weather_at_coords ( self , lat , lon ) : """Queries the OWM Weather API for the currently observed weather at the specified geographic ( eg : 51.503614 , - 0.107331 ) . : param lat : the location ' s latitude , must be between - 90.0 and 90.0 : type lat : int / float : param lon : the location ' s longi...
geo . assert_is_lon ( lon ) geo . assert_is_lat ( lat ) params = { 'lon' : lon , 'lat' : lat , 'lang' : self . _language } uri = http_client . HttpClient . to_url ( OBSERVATION_URL , self . _API_key , self . _subscription_type , self . _use_ssl ) _ , json_data = self . _wapi . cacheable_get_json ( uri , params = params...
def parker_weighting ( ray_trafo , q = 0.25 ) : """Create parker weighting for a ` RayTransform ` . Parker weighting is a weighting function that ensures that oversampled fan / cone beam data are weighted such that each line has unit weight . It is useful in analytic reconstruction methods such as FBP to give...
# Note : Parameter names taken from WES2002 # Extract parameters src_radius = ray_trafo . geometry . src_radius det_radius = ray_trafo . geometry . det_radius ndim = ray_trafo . geometry . ndim angles = ray_trafo . range . meshgrid [ 0 ] min_rot_angle = ray_trafo . geometry . motion_partition . min_pt alen = ray_trafo ...
def _urn_to_db_refs ( urn ) : """Converts a Medscan URN to an INDRA db _ refs dictionary with grounding information . Parameters urn : str A Medscan URN Returns db _ refs : dict A dictionary with grounding information , mapping databases to database identifiers . If the Medscan URN is not recognized...
# Convert a urn to a db _ refs dictionary if urn is None : return { } , None m = URN_PATT . match ( urn ) if m is None : return None , None urn_type , urn_id = m . groups ( ) db_refs = { } db_name = None # TODO : support more types of URNs if urn_type == 'agi-cas' : # Identifier is CAS , convert to CHEBI ch...
def seek ( self , offset , whence = os . SEEK_SET ) : """Seeks to an offset within the file - like object . Args : offset ( int ) : offset to seek to . whence ( Optional ( int ) ) : value that indicates whether offset is an absolute or relative position within the file . Raises : IOError : if the seek f...
if not self . _is_open : raise IOError ( 'Not opened.' ) if self . _current_offset < 0 : raise IOError ( 'Invalid current offset: {0:d} value less than zero.' . format ( self . _current_offset ) ) if whence == os . SEEK_CUR : offset += self . _current_offset elif whence == os . SEEK_END : if self . _dec...
def set_defaults ( show_toolbar = None , precision = None , grid_options = None , column_options = None ) : """Set the default qgrid options . The options that you can set here are the same ones that you can pass into ` ` QgridWidget ` ` constructor , with the exception of the ` ` df ` ` option , for which a de...
defaults . set_defaults ( show_toolbar = show_toolbar , precision = precision , grid_options = grid_options , column_options = column_options )
def extract_orientation ( self ) : '''Extract image orientation'''
fields = [ 'Image Orientation' ] orientation , _ = self . _extract_alternative_fields ( fields , default = 1 , field_type = int ) if orientation not in range ( 1 , 9 ) : return 1 return orientation
def reload ( self ) : """Reloads current instance from DB store"""
self . _load_data ( self . objects . data ( ) . filter ( key = self . key ) [ 0 ] [ 0 ] , True )
def to ( self , unit ) : """Convert this angle to the given AstroPy unit ."""
from astropy . units import rad return ( self . radians * rad ) . to ( unit ) # Or should this do : from astropy . coordinates import Angle from astropy . units import rad return Angle ( self . radians , rad ) . to ( unit )
def const_factory ( value ) : """return an astroid node for a python value"""
# XXX we should probably be stricter here and only consider stuff in # CONST _ CLS or do better treatment : in case where value is not in CONST _ CLS , # we should rather recall the builder on this value than returning an empty # node ( another option being that const _ factory shouldn ' t be called with something # no...
def sameRegion ( self , e ) : """Check whether self represents the same DNA region as e . : param e : genomic region to compare against : return : True if self and e are for the same region ( ignores differences in non - region related fields , such as name or score - - but does consider strand )"""
if e is None : return False return ( self . chrom == e . chrom and self . start == e . start and self . end == e . end and self . name == e . name and self . strand == e . strand )
def add_netreg_api ( mock ) : '''Add org . ofono . NetworkRegistration API to a mock'''
# also add an emergency number which is not a real one , in case one runs a # test case against a production ofono : - ) mock . AddProperties ( 'org.ofono.NetworkRegistration' , { 'Mode' : 'auto' , 'Status' : 'registered' , 'LocationAreaCode' : _parameters . get ( 'LocationAreaCode' , 987 ) , 'CellId' : _parameters . g...
def plot ( q : np . ndarray , bodies : List [ str ] , plot_colors : Dict [ str , str ] , sim_name : str , fname : Optional [ str ] = None ) : """Plot the planetary orbits . Plot size limited to box of 10 AU around the sun . q is a Nx3B array . t indexes time points . 3B columns are ( x , y , z ) for the bodies in...
# Get N and number of dims N , dims = q . shape # Slices for x_slice = slice ( 0 , dims , 3 ) y_slice = slice ( 1 , dims , 3 ) # Convert all distances from meters to astronomical units ( AU ) plot_x = q [ : , x_slice ] / au2m plot_y = q [ : , y_slice ] / au2m # Set up chart title and scale fig , ax = plt . subplots ( f...
def from_native ( cls , regex ) : """Convert a Python regular expression into a ` ` Regex ` ` instance . Note that in Python 3 , a regular expression compiled from a : class : ` str ` has the ` ` re . UNICODE ` ` flag set . If it is undesirable to store this flag in a BSON regular expression , unset it first ...
if not isinstance ( regex , RE_TYPE ) : raise TypeError ( "regex must be a compiled regular expression, not %s" % type ( regex ) ) return Regex ( regex . pattern , regex . flags )
def requires_role ( role_s , logical_operator = all ) : """Requires that the calling Subject be authorized to the extent that is required to satisfy the role _ s specified and the logical operation upon them . : param role _ s : a collection of the role ( s ) required , specified by identifiers ( such as a ...
def outer_wrap ( fn ) : @ functools . wraps ( fn ) def inner_wrap ( * args , ** kwargs ) : subject = WebYosai . get_current_subject ( ) try : subject . check_role ( role_s , logical_operator ) except ValueError : msg = ( "Attempting to perform a user-only operatio...
def URLField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : """Create new UUID field on a model . : param default : any value : param bool required : whether or not the object is invalid if not provided . : param bool repr : include this field should appear in object ' s rep...
cls = ParseResult default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , cls ) return attrib ( default = default , converter = converters . str_to_url , validator = validator , repr = repr , cmp = cmp , metadata = dict ( key = key ) )
def _get_css_class ( self , ttype ) : """Return the css class of this token type prefixed with the classprefix option ."""
ttypeclass = _get_ttype_class ( ttype ) if ttypeclass : return self . classprefix + ttypeclass return ''
def get_portchannel_info_by_intf_output_lacp_oper_state ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) get_portchannel_info_by_intf = ET . Element ( "get_portchannel_info_by_intf" ) config = get_portchannel_info_by_intf output = ET . SubElement ( get_portchannel_info_by_intf , "output" ) lacp = ET . SubElement ( output , "lacp" ) oper_state = ET . SubElement ( lacp , "oper-state" ) ope...
def wkt_to_proj4 ( wkt ) : """Converts a well - known text string to a pyproj . Proj object"""
srs = osgeo . osr . SpatialReference ( ) srs . ImportFromWkt ( wkt ) return pyproj . Proj ( str ( srs . ExportToProj4 ( ) ) )
async def disconnect ( self , client_id , conn_string ) : """Disconnect from a device on behalf of a client . See : meth : ` AbstractDeviceAdapter . disconnect ` . Args : client _ id ( str ) : The client we are working for . conn _ string ( str ) : A connection string that will be passed to the underlying...
conn_id = self . _client_connection ( client_id , conn_string ) try : await self . adapter . disconnect ( conn_id ) finally : self . _hook_disconnect ( conn_string , client_id )
def calc_multi_exp_unc ( sys_unc , n , mean , std , dof , confidence = 0.95 ) : """Calculate expanded uncertainty using values from multiple runs . Note that this function assumes the statistic is a mean value , therefore the combined standard deviation is divided by ` sqrt ( N ) ` . Parameters sys _ unc : ...
sys_unc = sys_unc . mean ( ) std_combined = combine_std ( n , mean , std ) std_combined /= np . sqrt ( n . sum ( ) ) std_unc_combined = np . sqrt ( std_combined ** 2 + sys_unc ** 2 ) dof = dof . sum ( ) t_combined = scipy . stats . t . interval ( alpha = confidence , df = dof ) [ - 1 ] exp_unc_combined = t_combined * s...
def addFailure ( self , test : unittest . case . TestCase , exc_info : tuple ) -> None : """Transforms the test in a serializable version of it and sends it to a queue for further analysis : param test : the test to save : param exc _ info : tuple of the form ( Exception class , Exception instance , traceback )...
# noinspection PyTypeChecker self . add_result ( TestState . failure , test , exc_info )
def timerEvent ( self , event ) : """Trigger the focus manager and work off all queued macros . The main purpose of using this timer event is to postpone updating the visual layout of Qtmacs until all macro code has been fully executed . Furthermore , this GUI update needs to happen in between any two macro...
self . killTimer ( event . timerId ( ) ) if event . timerId ( ) == self . _qteTimerRunMacro : # Declare the macro execution timer event handled . self . _qteTimerRunMacro = None # If we are in this branch then the focus manager was just # executed , the event loop has updated all widgets and # cleared o...
def _rank_init ( self , unranked ) : """Computes rank of provided unranked list of vertices and all their children . A vertex will be asign a rank when all its inward edges have been * scanned * . When a vertex is asigned a rank , its outward edges are marked * scanned * ."""
assert self . dag scan = { } # set rank of unranked based on its in - edges vertices ranks : while len ( unranked ) > 0 : l = [ ] for v in unranked : self . setrank ( v ) # mark out - edges has scan - able : for e in v . e_out ( ) : scan [ e ] = True # check if out - ...
def main ( name , output , font ) : """Easily bootstrap an OS project to fool HR departments and pad your resume ."""
# The path of the directory where the final files will end up in bootstrapped_directory = os . getcwd ( ) + os . sep + name . lower ( ) . replace ( ' ' , '-' ) + os . sep # Copy the template files to the target directory copy_tree ( get_real_path ( os . sep + 'my-cool-os-template' ) , bootstrapped_directory ) # Create ...
def update_driver ( self , prompt ) : """Update driver based on new prompt ."""
prompt = prompt . lstrip ( ) self . chain . connection . log ( "({}): Prompt: '{}'" . format ( self . driver . platform , prompt ) ) self . prompt = prompt driver_name = self . driver . update_driver ( prompt ) if driver_name is None : self . chain . connection . log ( "New driver not detected. Using existing {} dr...