signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def set_rcParams_scanpy ( fontsize = 14 , color_map = None , frameon = None ) :
"""Set matplotlib . rcParams to Scanpy defaults .""" | # dpi options
rcParams [ 'figure.dpi' ] = 100
rcParams [ 'savefig.dpi' ] = 150
# figure
rcParams [ 'figure.figsize' ] = ( 4 , 4 )
rcParams [ 'figure.subplot.left' ] = 0.18
rcParams [ 'figure.subplot.right' ] = 0.96
rcParams [ 'figure.subplot.bottom' ] = 0.15
rcParams [ 'figure.subplot.top' ] = 0.91
rcParams [ 'lines.li... |
def _assign_faucets ( self , faucets ) :
"""Assign RainCloudyFaucet objects to self . faucets .""" | if not faucets :
raise TypeError ( "Controller does not have a faucet assigned." )
for faucet_id in faucets :
self . faucets . append ( RainCloudyFaucet ( self . _parent , self , faucet_id ) ) |
def walk ( self , visitor ) :
"""Walk the branch and call the visitor function
on each node .
@ param visitor : A function .
@ return : self
@ rtype : L { Element }""" | visitor ( self )
for c in self . children :
c . walk ( visitor )
return self |
def render_template_directory ( deck , arguments ) :
"""Render a template directory""" | output_directory = dir_name_from_title ( deck . title )
if os . path . exists ( output_directory ) :
if sys . stdout . isatty ( ) :
if ask ( '%s already exists, shall I delete it?' % output_directory , arguments . get ( '--noinput' ) ) :
shutil . rmtree ( output_directory )
else :
sh... |
def dec2dec ( dec ) :
"""Convert sexegessimal RA string into a float in degrees .
Parameters
dec : string
A string separated representing the Dec .
Expected format is ` [ + - ] hh : mm [ : ss . s ] `
Colons can be replaced with any whit space character .
Returns
dec : float
The Dec in degrees .""" | d = dec . replace ( ':' , ' ' ) . split ( )
if len ( d ) == 2 :
d . append ( 0.0 )
if d [ 0 ] . startswith ( '-' ) or float ( d [ 0 ] ) < 0 :
return float ( d [ 0 ] ) - float ( d [ 1 ] ) / 60.0 - float ( d [ 2 ] ) / 3600.0
return float ( d [ 0 ] ) + float ( d [ 1 ] ) / 60.0 + float ( d [ 2 ] ) / 3600.0 |
def delete_agent_pool ( self , pool_id ) :
"""DeleteAgentPool .
[ Preview API ] Delete an agent pool .
: param int pool _ id : ID of the agent pool to delete""" | route_values = { }
if pool_id is not None :
route_values [ 'poolId' ] = self . _serialize . url ( 'pool_id' , pool_id , 'int' )
self . _send ( http_method = 'DELETE' , location_id = 'a8c47e17-4d56-4a56-92bb-de7ea7dc65be' , version = '5.1-preview.1' , route_values = route_values ) |
def remove_last_line ( self ) :
"""Removes the last line of the document .""" | editor = self . _editor
text_cursor = editor . textCursor ( )
text_cursor . movePosition ( text_cursor . End , text_cursor . MoveAnchor )
text_cursor . select ( text_cursor . LineUnderCursor )
text_cursor . removeSelectedText ( )
text_cursor . deletePreviousChar ( )
editor . setTextCursor ( text_cursor ) |
def _get_transitions ( self , expression : Any , expected_type : PredicateType ) -> Tuple [ List [ str ] , PredicateType ] :
"""This is used when converting a logical form into an action sequence . This piece
recursively translates a lisp expression into an action sequence , making sure we match the
expected ty... | if isinstance ( expression , ( list , tuple ) ) :
function_transitions , return_type , argument_types = self . _get_function_transitions ( expression [ 0 ] , expected_type )
if len ( argument_types ) != len ( expression [ 1 : ] ) :
raise ParsingError ( f'Wrong number of arguments for function in {expres... |
def read_frame_nowait ( self ) -> Optional [ DataFrame ] :
"""Read a single frame from the local buffer immediately .
If no frames are available but the stream is still open , returns None .
Otherwise , raises StreamConsumedError .""" | try :
frame = self . _data_frames . get_nowait ( )
except asyncio . QueueEmpty :
if self . closed :
raise StreamConsumedError ( self . id )
return None
self . _data_frames . task_done ( )
if frame is None :
raise StreamConsumedError ( self . id )
return frame |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'cell_id' ) and self . cell_id is not None :
_dict [ 'cell_id' ] = self . cell_id
if hasattr ( self , 'location' ) and self . location is not None :
_dict [ 'location' ] = self . location . _to_dict ( )
if hasattr ( self , 'text' ) and self . text is not None :
_dict [ 'text'... |
def get_user_metadata ( self , bucket : str , key : str ) -> typing . Dict [ str , str ] :
"""Retrieves the user metadata for a given object in a given bucket . If the platform has any mandatory prefixes or
suffixes for the metadata keys , they should be stripped before being returned .
: param bucket : the buc... | try :
response = self . get_all_metadata ( bucket , key )
metadata = response [ 'Metadata' ] . copy ( )
response = self . s3_client . get_object_tagging ( Bucket = bucket , Key = key , )
for tag in response [ 'TagSet' ] :
key , value = tag [ 'Key' ] , tag [ 'Value' ]
metadata [ key ] = v... |
def R_rot_3d ( th ) :
"""Return a 3 - dimensional rotation matrix .
Parameters
th : array , shape ( n , 3)
Angles about which to rotate along each axis .
Returns
R : array , shape ( n , 3 , 3)""" | sx , sy , sz = np . sin ( th ) . T
cx , cy , cz = np . cos ( th ) . T
R = np . empty ( ( len ( th ) , 3 , 3 ) , dtype = np . float )
R [ : , 0 , 0 ] = cy * cz
R [ : , 0 , 1 ] = - cy * sz
R [ : , 0 , 2 ] = sy
R [ : , 1 , 0 ] = sx * sy * cz + cx * sz
R [ : , 1 , 1 ] = - sx * sy * sz + cx * cz
R [ : , 1 , 2 ] = - sx * cy
... |
def default_bundle_config ( ) :
"""Return the default bundle config file as an AttrDict .""" | import os
from ambry . util import AttrDict
config = AttrDict ( )
f = os . path . join ( os . path . dirname ( os . path . realpath ( __file__ ) ) , 'bundle.yaml' )
config . update_yaml ( f )
return config |
def parse_JSON ( self , JSON_string ) :
"""Parses a list of * Station * instances out of raw JSON data . Only
certain properties of the data are used : if these properties are not
found or cannot be parsed , an error is issued .
: param JSON _ string : a raw JSON string
: type JSON _ string : str
: return... | if JSON_string is None :
raise ParseResponseError ( 'JSON data is None' )
d = json . loads ( JSON_string )
station_parser = StationParser ( )
return [ station_parser . parse_JSON ( json . dumps ( item ) ) for item in d ] |
def proxy_num ( self , protocol = None ) :
"""Get the number of proxies in the pool
Args :
protocol ( str , optional ) : ' http ' or ' https ' or None . ( default None )
Returns :
If protocol is None , return the total number of proxies , otherwise ,
return the number of proxies of corresponding protocol ... | http_num = len ( self . proxies [ 'http' ] )
https_num = len ( self . proxies [ 'https' ] )
if protocol == 'http' :
return http_num
elif protocol == 'https' :
return https_num
else :
return http_num + https_num |
def list_all ( self ) :
"""List all environment vips
: return : Following dictionary :
{ ' environment _ vip ' : [ { ' id ' : < id > ,
' finalidade _ txt ' : < finalidade _ txt > ,
' cliente _ txt ' : < cliente _ txt > ,
' ambiente _ p44 _ txt ' : < ambiente _ p44 _ txt > } { . . . other environments vip ... | url = 'environmentvip/all/'
code , xml = self . submit ( None , 'GET' , url )
key = 'environment_vip'
return get_list_map ( self . response ( code , xml , [ key ] ) , key ) |
def upload_identity_keys ( self ) :
"""Uploads this device ' s identity keys to HS .
This device must be the one used when logging in .""" | device_keys = { 'user_id' : self . user_id , 'device_id' : self . device_id , 'algorithms' : self . _algorithms , 'keys' : { '{}:{}' . format ( alg , self . device_id ) : key for alg , key in self . identity_keys . items ( ) } }
self . sign_json ( device_keys )
ret = self . api . upload_keys ( device_keys = device_keys... |
def convert_raw_tuple ( value_tuple , format_string ) :
"""Convert a tuple of raw values , according to the given line format .
: param tuple value _ tuple : the tuple of raw values
: param str format _ string : the format of the tuple
: rtype : list of tuples""" | values = [ ]
for v , c in zip ( value_tuple , format_string ) :
if v is None : # append None
values . append ( v )
elif c == u"s" : # string
values . append ( v )
elif c == u"S" : # string , split using space as delimiter
values . append ( [ s for s in v . split ( u" " ) if len ( s )... |
def do_reset ( self , line ) :
"""reset Set all session variables to their default values .""" | self . _split_args ( line , 0 , 0 )
self . _command_processor . get_session ( ) . reset ( )
self . _print_info_if_verbose ( "Successfully reset session variables" ) |
def _write_header ( self ) :
"""Write out the table header""" | self . _ostream . write ( len ( self . _header ) * "-" + "\n" )
self . _ostream . write ( self . _header )
self . _ostream . write ( "\n" )
self . _ostream . write ( len ( self . _header ) * "-" + "\n" ) |
def is_calculated_aes ( ae ) :
"""Return a True if of the aesthetics that are calculated
Parameters
ae : object
Aesthetic mapping
> > > is _ calculated _ aes ( ' density ' )
False
> > > is _ calculated _ aes ( 4)
False
> > > is _ calculated _ aes ( ' . . density . . ' )
True
> > > is _ calculate... | if not isinstance ( ae , str ) :
return False
for pattern in ( STAT_RE , DOTS_RE ) :
if pattern . search ( ae ) :
return True
return False |
def list ( self , parts : Any ) -> str :
"""Returns a comma - separated list for the given list of parts .
The format is , e . g . , " A , B and C " , " A and B " or just " A " for lists
of size 1.""" | _ = self . translate
if len ( parts ) == 0 :
return ""
if len ( parts ) == 1 :
return parts [ 0 ]
comma = u" \u0648 " if self . code . startswith ( "fa" ) else u", "
return _ ( "%(commas)s and %(last)s" ) % { "commas" : comma . join ( parts [ : - 1 ] ) , "last" : parts [ len ( parts ) - 1 ] , } |
def _trigger_job ( job ) :
"""trigger a job""" | if job . api_instance ( ) . is_running ( ) :
return "{0}, {1} is already running" . format ( job . host , job . name )
else :
requests . get ( job . api_instance ( ) . get_build_triggerurl ( ) )
return "triggering {0}, {1}..." . format ( job . host , job . name ) |
def match_config ( regex ) :
'''Display the current values of all configuration variables whose
names match the given regular expression .
. . versionadded : : 2016.11.0
. . code - block : : bash
salt ' * ' trafficserver . match _ config regex''' | if _TRAFFICCTL :
cmd = _traffic_ctl ( 'config' , 'match' , regex )
else :
cmd = _traffic_line ( '-m' , regex )
return _subprocess ( cmd ) |
def handle ( self , record ) :
"""Handle an item .
This just loops through the handlers offering them the record
to handle .""" | record = self . prepare ( record )
for handler in self . handlers :
handler ( record ) |
def remove_chunk_layer ( self ) :
"""Removes the chunk layer ( if exists ) of the object ( in memory )""" | if self . chunk_layer is not None :
this_node = self . chunk_layer . get_node ( )
self . root . remove ( this_node )
self . chunk_layer = None
if self . header is not None :
self . header . remove_lp ( 'chunks' ) |
def writeSentence ( self , cmd , * words ) :
"""Write encoded sentence .
: param cmd : Command word .
: param words : Aditional words .""" | encoded = self . encodeSentence ( cmd , * words )
self . log ( '<---' , cmd , * words )
self . transport . write ( encoded ) |
def count_rows ( self , table_name ) :
"""Return the number of entries in a table by counting them .""" | self . table_must_exist ( table_name )
query = "SELECT COUNT (*) FROM `%s`" % table_name . lower ( )
self . own_cursor . execute ( query )
return int ( self . own_cursor . fetchone ( ) [ 0 ] ) |
def _get_pgen_var ( self , generators , base_mva ) :
"""Returns the generator active power set - point variable .""" | Pg = array ( [ g . p / base_mva for g in generators ] )
Pmin = array ( [ g . p_min / base_mva for g in generators ] )
Pmax = array ( [ g . p_max / base_mva for g in generators ] )
return Variable ( "Pg" , len ( generators ) , Pg , Pmin , Pmax ) |
def create ( self , instance , cidr_mask , description , ** kwargs ) :
"""Create an ACL entry for the specified instance .
: param str instance : The name of the instance to associate the new ACL entry with .
: param str cidr _ mask : The IPv4 CIDR mask for the new ACL entry .
: param str description : A shor... | # Build up request data .
url = self . _url . format ( instance = instance )
request_data = { 'cidr_mask' : cidr_mask , 'description' : description }
request_data . update ( kwargs )
# Call to create an instance .
response = requests . post ( url , data = json . dumps ( request_data ) , ** self . _default_request_kwarg... |
def alts_columns_used ( self ) :
"""Columns from the alternatives table that are used for filtering .""" | return list ( tz . unique ( tz . concat ( m . alts_columns_used ( ) for m in self . models . values ( ) ) ) ) |
def get_feature_variable_integer ( self , feature_key , variable_key , user_id , attributes = None ) :
"""Returns value for a certain integer variable attached to a feature flag .
Args :
feature _ key : Key of the feature whose variable ' s value is being accessed .
variable _ key : Key of the variable whose ... | variable_type = entities . Variable . Type . INTEGER
return self . _get_feature_variable_for_type ( feature_key , variable_key , variable_type , user_id , attributes ) |
def _get_filters ( nodes , context ) :
"""Get filters to apply to a list of SqlNodes .
Args :
nodes : List [ SqlNode ] , the SqlNodes to get filters for .
context : CompilationContext , global compilation state and metadata .
Returns :
List [ Expression ] , list of SQLAlchemy expressions .""" | filters = [ ]
for node in nodes :
for filter_block in sql_context_helpers . get_filters ( node , context ) :
filter_sql_expression = _transform_filter_to_sql ( filter_block , node , context )
filters . append ( filter_sql_expression )
return filters |
def _requires_submission ( self ) :
"""Returns True if the time since the last submission is greater than the submission interval .
If no submissions have ever been made , check if the database last modified time is greater than the
submission interval .""" | if self . dbcon_part is None :
return False
tables = get_table_list ( self . dbcon_part )
nrows = 0
for table in tables :
if table == '__submissions__' :
continue
nrows += get_number_of_rows ( self . dbcon_part , table )
if nrows :
logger . debug ( '%d new statistics were added since the last su... |
async def newnations ( self , root ) :
"""Most recently founded nations , from newest .
Returns
an : class : ` ApiQuery ` of a list of : class : ` Nation `""" | return [ aionationstates . Nation ( n ) for n in root . find ( 'NEWNATIONS' ) . text . split ( ',' ) ] |
def get_wireframe ( viewer , x , y , z , ** kwargs ) :
"""Produce a compound object of paths implementing a wireframe .
x , y , z are expected to be 2D arrays of points making up the mesh .""" | # TODO : something like this would make a great utility function
# for ginga
n , m = x . shape
objs = [ ]
for i in range ( n ) :
pts = np . asarray ( [ ( x [ i ] [ j ] , y [ i ] [ j ] , z [ i ] [ j ] ) for j in range ( m ) ] )
objs . append ( viewer . dc . Path ( pts , ** kwargs ) )
for j in range ( m ) :
p... |
def get_renderer_from_definition ( config ) :
"""Returns a renderer object based on the configuration ( as a dictionary )""" | options = config . get ( 'options' , { } )
try :
renderer_type = config [ 'type' ]
renderer_colors = [ ( float ( x [ 0 ] ) , hex_to_color ( x [ 1 ] ) ) for x in config [ 'colors' ] ]
fill_value = options . get ( 'fill_value' )
if fill_value is not None :
fill_value = float ( fill_value )
except ... |
def parse_xml ( sentence , tab = "\t" , id = "" ) :
"""Returns the given Sentence object as an XML - string ( plain bytestring , UTF - 8 encoded ) .
The tab delimiter is used as indendation for nested elements .
The id can be used as a unique identifier per sentence for chunk id ' s and anchors .
For example ... | uid = lambda * parts : "" . join ( [ str ( id ) , _UID_SEPARATOR ] + [ str ( x ) for x in parts ] ) . lstrip ( _UID_SEPARATOR )
push = lambda indent : indent + tab
# push ( ) increases the indentation .
pop = lambda indent : indent [ : - len ( tab ) ]
# pop ( ) decreases the indentation .
indent = tab
xml = [ ]
# Start... |
def _init_cat_dict ( self , cat_dict_class , key_in_self , ** kwargs ) :
"""Initialize a CatDict object , checking for errors .""" | # Catch errors associated with crappy , but not unexpected data
try :
new_entry = cat_dict_class ( self , key = key_in_self , ** kwargs )
except CatDictError as err :
if err . warn :
self . _log . info ( "'{}' Not adding '{}': '{}'" . format ( self [ self . _KEYS . NAME ] , key_in_self , str ( err ) ) )... |
def add_condition ( self , condition : z3 . BoolRef ) -> None :
"""Add condition to the dependence map
: param condition : The condition that is to be added to the dependence map""" | variables = set ( _get_expr_variables ( condition ) )
relevant_buckets = set ( )
for variable in variables :
try :
bucket = self . variable_map [ str ( variable ) ]
relevant_buckets . add ( bucket )
except KeyError :
continue
new_bucket = DependenceBucket ( variables , [ condition ] )
se... |
def populate ( ) :
"""Creates and populates the Misc / NEWS . d directory tree .""" | os . chdir ( "Misc" )
safe_mkdir ( "NEWS.d/next" )
for section in sections :
dir_name = sanitize_section ( section )
dir_path = f ( "NEWS.d/next/{dir_name}" )
safe_mkdir ( dir_path )
readme_path = f ( "NEWS.d/next/{dir_name}/README.rst" )
with open ( readme_path , "wt" , encoding = "utf-8" ) as read... |
def get_groups ( self , query = None , exclude = None , limit = 20 ) :
"""REST endpoint for searching groups in a group picker
Returns groups with substrings matching a given query . This is mainly for use with the group picker ,
so the returned groups contain html to be used as picker suggestions . The groups ... | url = 'rest/api/2/groups/picker'
params = { }
if query :
params [ 'query' ] = query
else :
params [ 'query' ] = ''
if exclude :
params [ 'exclude' ] = exclude
if limit :
params [ 'maxResults' ] = limit
return self . get ( url , params = params ) |
def get_comments_of_letter_per_page ( self , letter_id , per_page = 1000 , page = 1 ) :
"""Get comments of letter per page
: param letter _ id : the letter id
: param per _ page : How many objects per page . Default : 1000
: param page : Which page . Default : 1
: return : list""" | return self . _get_resource_per_page ( resource = LETTER_COMMENTS , per_page = per_page , page = page , params = { 'letter_id' : letter_id } , ) |
def parse ( cls , querydict ) :
"""Parse querydict data .
There are expected agruments :
distinct , fields , filter , include , page , sort
Parameters
querydict : django . http . request . QueryDict
MultiValueDict with query arguments .
Returns
result : dict
dictionary in format { key : value } .
... | for key in querydict . keys ( ) :
if not any ( ( key in JSONAPIQueryDict . _fields , cls . RE_FIELDS . match ( key ) ) ) :
msg = "Query parameter {} is not known" . format ( key )
raise ValueError ( msg )
result = JSONAPIQueryDict ( distinct = cls . prepare_values ( querydict . getlist ( 'distinct' ... |
def deprecated ( func ) :
"""This is a decorator which can be used to mark functions as deprecated . It will result in a warning being emitted
when the function is used .
: param func : The function to run
: return : function""" | def deprecation_warning ( * args , ** kwargs ) :
warnings . warn ( 'Call to deprecated function {name}. Please consult our documentation at ' 'http://pyapi-gitlab.readthedocs.io/en/latest/#gitlab.Gitlab.{name}' . format ( name = func . __name__ ) , category = DeprecationWarning )
return func ( * args , ** kwarg... |
def get_option_labels ( self , typ , element ) :
"""Return labels for each level of the option model .
The options returned by : meth : ` RefobjInterface . fetch _ options ` is a treemodel
with ` ` n ` ` levels . Each level should get a label to describe what is displays .
E . g . if you organize your options... | inter = self . get_typ_interface ( typ )
return inter . get_option_labels ( element ) |
def recognize_verify_code ( image_path , broker = "ht" ) :
"""识别验证码 , 返回识别后的字符串 , 使用 tesseract 实现
: param image _ path : 图片路径
: param broker : 券商 [ ' ht ' , ' yjb ' , ' gf ' , ' yh ' ]
: return recognized : verify code string""" | if broker == "gf" :
return detect_gf_result ( image_path )
if broker in [ "yh_client" , "gj_client" ] :
return detect_yh_client_result ( image_path )
# 调用 tesseract 识别
return default_verify_code_detect ( image_path ) |
def get_complete_version ( version = None ) :
"""Returns a tuple of the promise version . If version argument is non - empty ,
then checks for correctness of the tuple provided .""" | if version is None :
from promise import VERSION
return VERSION
else :
assert len ( version ) == 5
assert version [ 3 ] in ( "alpha" , "beta" , "rc" , "final" )
return version |
def set_commit ( self , commit , logmsg = None ) :
"""As set _ object , but restricts the type of object to be a Commit
: raise ValueError : If commit is not a Commit object or doesn ' t point to
a commit
: return : self""" | # check the type - assume the best if it is a base - string
invalid_type = False
if isinstance ( commit , Object ) :
invalid_type = commit . type != Commit . type
elif isinstance ( commit , SymbolicReference ) :
invalid_type = commit . object . type != Commit . type
else :
try :
invalid_type = self ... |
def delete_dataset ( self , dataset ) :
"""Deletes a single dataset , including all of the features that it contains .
Parameters
dataset : str
The dataset id .
Returns
HTTP status code .""" | uri = URITemplate ( self . baseuri + '/{owner}/{id}' ) . expand ( owner = self . username , id = dataset )
return self . session . delete ( uri ) |
def p_declassign ( self , p ) :
'declassign : sigtypes declassign _ element SEMICOLON' | decllist = self . create_declassign ( p [ 1 ] , p [ 2 ] [ 0 ] , p [ 2 ] [ 1 ] , lineno = p . lineno ( 2 ) )
p [ 0 ] = Decl ( decllist , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def query_master ( filter_text = r'\napp\500' , max_servers = 20 , region = MSRegion . World , master = MSServer . Source , timeout = 2 ) :
r"""Generator that returns ( IP , port ) pairs of servers
. . warning : :
Valve ' s master servers seem to be heavily rate limited .
Queries that return a large numbers I... | if not isinstance ( region , MSRegion ) :
raise TypeError ( "region_code is not of type MSRegion" )
ms = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
ms . connect ( master )
ms . settimeout ( timeout )
next_ip = b'0.0.0.0:0'
req_prefix = b'1' + _pack ( '>B' , region )
req_suffix = b'\x00' + filter_tex... |
def create_poller ( self , ** kwargs ) :
"""Returns poller data structure
Kwargs :
cacheablesource : Elemtree . element object of cacheablesource
cachearea : Elemtree . element object of cachearea
Returns : ( ICachableSource , ICacheArea , poll )""" | cacheablesource = createObject ( kwargs [ 'cacheablesource' ] . attrib [ 'factory' ] , kwargs [ 'cacheablesource' ] )
cachearea = createObject ( kwargs [ 'cachearea' ] . attrib [ 'factory' ] , kwargs [ 'cachearea' ] )
poll = abs ( int ( kwargs [ 'cacheablesource' ] . attrib [ 'poll' ] ) )
logger . info ( "Poller create... |
def incrby ( self , fmt , offset , increment , overflow = None ) :
"""Increment a bitfield by a given amount .
: param fmt : format - string for the bitfield being updated , e . g . u8 for
an unsigned 8 - bit integer .
: param int offset : offset ( in number of bits ) .
: param int increment : value to incr... | bfo = BitFieldOperation ( self . database , self . key )
return bfo . incrby ( fmt , offset , increment , overflow ) |
def import_gmfs ( dstore , fname , sids ) :
"""Import in the datastore a ground motion field CSV file .
: param dstore : the datastore
: param fname : the CSV file
: param sids : the site IDs ( complete )
: returns : event _ ids , num _ rlzs""" | array = writers . read_composite_array ( fname ) . array
# has header rlzi , sid , eid , gmv _ PGA , . . .
imts = [ name [ 4 : ] for name in array . dtype . names [ 3 : ] ]
n_imts = len ( imts )
gmf_data_dt = numpy . dtype ( [ ( 'rlzi' , U16 ) , ( 'sid' , U32 ) , ( 'eid' , U64 ) , ( 'gmv' , ( F32 , ( n_imts , ) ) ) ] )... |
def licenses ( self ) :
"""Gets all the licenses
Returns :
List of licenses""" | if not self . __licenses :
self . __licenses = Licenses ( self . __connection )
return self . __licenses |
def dependencies ( project_name ) :
"""Get the dependencies for a project .""" | log = logging . getLogger ( 'ciu' )
log . info ( 'Locating dependencies for {}' . format ( project_name ) )
located = distlib . locators . locate ( project_name , prereleases = True )
if not located :
log . warning ( '{0} not found' . format ( project_name ) )
return None
return { packaging . utils . canonicali... |
def render_code ( code , filetype , pygments_style ) :
"""Renders a piece of code into HTML . Highlights syntax if filetype is specfied""" | if filetype :
lexer = pygments . lexers . get_lexer_by_name ( filetype )
formatter = pygments . formatters . HtmlFormatter ( style = pygments_style )
return pygments . highlight ( code , lexer , formatter )
else :
return "<pre><code>{}</code></pre>" . format ( code ) |
def PARAMLIMITS ( self , value ) :
"""Set new ` PARAMLIMITS ` dictionary .""" | assert set ( value . keys ( ) ) == set ( self . PARAMLIMITS . keys ( ) ) , "The \
new parameter limits are not defined for the same set \
of parameters as before."
for param in value . keys ( ) :
assert value [ param ] [ 0 ] < value [ param ] [ 1 ] , "The new \
mi... |
def get_mv_feeder_from_line ( line ) :
"""Determines MV feeder the given line is in .
MV feeders are identified by the first line segment of the half - ring .
Parameters
line : : class : ` ~ . grid . components . Line `
Line to find the MV feeder for .
Returns
: class : ` ~ . grid . components . Line ` ... | try : # get nodes of line
nodes = line . grid . graph . nodes_from_line ( line )
# get feeders
feeders = { }
for node in nodes : # if one of the nodes is an MV station the line is an MV feeder
# itself
if isinstance ( node , MVStation ) :
feeders [ repr ( node ) ] = None
... |
def normalize_codec_name ( name ) :
'''Return the Python name of the encoder / decoder
Returns :
str , None''' | name = UnicodeDammit . CHARSET_ALIASES . get ( name . lower ( ) , name )
try :
return codecs . lookup ( name ) . name
except ( LookupError , TypeError , ValueError ) : # TypeError occurs when name contains \ x00 ( ValueError in Py3.5)
pass |
def fundamental_frequency ( s , FS ) : # TODO : review fundamental frequency to guarantee that f0 exists
# suggestion peak level should be bigger
# TODO : explain code
"""Compute fundamental frequency along the specified axes .
Parameters
s : ndarray
input from which fundamental frequency is computed .
FS :... | s = s - mean ( s )
f , fs = plotfft ( s , FS , doplot = False )
# fs = smooth ( fs , 50.0)
fs = fs [ 1 : int ( len ( fs ) / 2 ) ]
f = f [ 1 : int ( len ( f ) / 2 ) ]
cond = find ( f > 0.5 ) [ 0 ]
bp = bigPeaks ( fs [ cond : ] , 0 )
if bp == [ ] :
f0 = 0
else :
bp = bp + cond
f0 = f [ min ( bp ) ]
return f0 |
def render_link ( self , template_pack = TEMPLATE_PACK , ** kwargs ) :
"""Render the link for the tab - pane . It must be called after render so css _ class is updated
with active if needed .""" | link_template = self . link_template % template_pack
return render_to_string ( link_template , { 'link' : self } ) |
def is_holiday_or_weekend ( holidays , dt ) :
"""Given a list of holidays , return whether dt is a holiday
or it is on a weekend .""" | one_day = timedelta ( days = 1 )
for h in holidays :
if dt in h . dates ( dt - one_day , dt + one_day ) or dt . weekday ( ) in WEEKENDS :
return True
return False |
def get_similar_entries ( context , number = 5 , template = 'zinnia/tags/entries_similar.html' ) :
"""Return similar entries .""" | entry = context . get ( 'entry' )
if not entry :
return { 'template' : template , 'entries' : [ ] }
vectors = EntryPublishedVectorBuilder ( )
entries = vectors . get_related ( entry , number )
return { 'template' : template , 'entries' : entries } |
def create_reader_of_type ( type_name ) :
"""Create an instance of the reader with the given name .
Args :
type _ name : The name of a reader .
Returns :
An instance of the reader with the given type .""" | readers = available_readers ( )
if type_name not in readers . keys ( ) :
raise UnknownReaderException ( 'Unknown reader: %s' % ( type_name , ) )
return readers [ type_name ] ( ) |
def validateBusName ( n ) :
"""Verifies that the supplied name is a valid DBus Bus name . Throws
an L { error . MarshallingError } if the format is invalid
@ type n : C { string }
@ param n : A DBus bus name""" | try :
if '.' not in n :
raise Exception ( 'At least two components required' )
if '..' in n :
raise Exception ( '".." not allowed in bus names' )
if len ( n ) > 255 :
raise Exception ( 'Name exceeds maximum length of 255' )
if n [ 0 ] == '.' :
raise Exception ( 'Names may... |
def find_consumers ( self , var_def , simplified_graph = True ) :
"""Find all consumers to the specified variable definition .
: param ProgramVariable var _ def : The variable definition .
: param bool simplified _ graph : True if we want to search in the simplified graph , False otherwise .
: return : A coll... | if simplified_graph :
graph = self . simplified_data_graph
else :
graph = self . data_graph
if var_def not in graph :
return [ ]
consumers = [ ]
srcs = [ var_def ]
traversed = set ( )
while srcs :
src = srcs . pop ( )
out_edges = graph . out_edges ( src , data = True )
for _ , dst , data in out_... |
def getTypeLastNode ( self , type_ ) :
"""Obtains the last node or leaf of the type specified
: param type _ :
Type we want to analize ( sementity , semtheme )
: return :
Last node of the type""" | lastNode = ""
if type_ and ( type ( type_ ) is not list ) and ( type ( type_ ) is not dict ) :
aType = type_ . split ( '>' )
lastNode = aType [ len ( aType ) - 1 ]
return lastNode |
def breadthdist ( CIJ ) :
'''The binary reachability matrix describes reachability between all pairs
of nodes . An entry ( u , v ) = 1 means that there exists a path from node u
to node v ; alternatively ( u , v ) = 0.
The distance matrix contains lengths of shortest paths between all
pairs of nodes . An en... | n = len ( CIJ )
D = np . zeros ( ( n , n ) )
for i in range ( n ) :
D [ i , : ] , _ = breadth ( CIJ , i )
D [ D == 0 ] = np . inf
R = ( D != np . inf )
return R , D |
def check_calibration ( self , calibration ) :
"""Check calibration quality by computing average reprojection error .
First , undistort detected points and compute epilines for each side .
Then compute the error between the computed epipolar lines and the
position of the points detected on the other side for ... | sides = "left" , "right"
which_image = { sides [ 0 ] : 1 , sides [ 1 ] : 2 }
undistorted , lines = { } , { }
for side in sides :
undistorted [ side ] = cv2 . undistortPoints ( np . concatenate ( self . image_points [ side ] ) . reshape ( - 1 , 1 , 2 ) , calibration . cam_mats [ side ] , calibration . dist_coefs [ s... |
def get_driver_status ( driver ) : # noqa : E501
"""Retrieve the status of a loaded driver
Retrieve the status of a loaded driver # noqa : E501
: param driver : The driver to use for the request . ie . github
: type driver : str
: rtype : Response""" | response = errorIfUnauthorized ( role = 'admin' )
if response :
return response
else :
response = ApitaxResponse ( )
driver : Driver = LoadedDrivers . getDriver ( driver )
response . body . add ( { 'name' : driver . getDriverName ( ) } )
response . body . add ( { 'description' : driver . getDriverDescription ( ... |
def shell ( config , type_ ) :
"""Open up a Python shell with Warehouse preconfigured in it .""" | # Imported here because we don ' t want to trigger an import from anything
# but warehouse . cli at the module scope .
from warehouse . db import Session
if type_ is None :
type_ = autodetect ( )
runner = { "bpython" : bpython , "ipython" : ipython , "plain" : plain } [ type_ ]
session = Session ( bind = config . r... |
def remove_metric ( self , metric_id ) :
"""Remove a metric from a monitored machine
: param metric _ id : Metric _ id ( provided by self . get _ stats ( ) )""" | payload = { 'metric_id' : metric_id }
data = json . dumps ( payload )
req = self . request ( self . mist_client . uri + "/clouds/" + self . cloud . id + "/machines/" + self . id + "/metrics" , data = data )
req . delete ( ) |
def _execute_forked ( self , tasks , log ) :
"""Executes the tasks in the forked process . Multiple tasks can be passed
for batch processing . However , they must all use the same function and
will share the execution entry .""" | success = False
execution = { }
assert len ( tasks )
task_func = tasks [ 0 ] . serialized_func
assert all ( [ task_func == task . serialized_func for task in tasks [ 1 : ] ] )
execution [ 'time_started' ] = time . time ( )
exc = None
exc_info = None
try :
func = tasks [ 0 ] . func
is_batch_func = getattr ( func... |
def beacon ( config ) :
'''Scan for the configured services and fire events
Example Config
. . code - block : : yaml
beacons :
service :
- services :
salt - master : { }
mysql : { }
The config above sets up beacons to check for
the salt - master and mysql services .
The config also supports two ... | ret = [ ]
_config = { }
list ( map ( _config . update , config ) )
for service in _config . get ( 'services' , { } ) :
ret_dict = { }
service_config = _config [ 'services' ] [ service ]
ret_dict [ service ] = { 'running' : __salt__ [ 'service.status' ] ( service ) }
ret_dict [ 'service_name' ] = service... |
def extract_tag_metadata ( self , el ) :
"""Extract meta data .""" | if self . type == 'odp' :
if el . namespace and el . namespace == self . namespaces [ 'draw' ] and el . name == 'page-thumbnail' :
name = el . attrs . get ( 'draw:page-number' , '' )
self . additional_context = 'slide{}:' . format ( name )
super ( ) . extract_tag_metadata ( el ) |
def _do_names ( names , fun , path = None ) :
'''Invoke a function in the lxc module with no args
path
path to the container parent
default : / var / lib / lxc ( system default )
. . versionadded : : 2015.8.0''' | ret = { }
hosts = find_guests ( names , path = path )
if not hosts :
return False
client = salt . client . get_local_client ( __opts__ [ 'conf_file' ] )
for host , sub_names in six . iteritems ( hosts ) :
cmds = [ ]
for name in sub_names :
cmds . append ( client . cmd_iter ( host , 'lxc.{0}' . forma... |
def galcenrect_to_XYZ ( X , Y , Z , Xsun = 1. , Zsun = 0. , _extra_rot = True ) :
"""NAME :
galcenrect _ to _ XYZ
PURPOSE :
transform rectangular Galactocentric to XYZ coordinates ( wrt Sun ) coordinates
INPUT :
X , Y , Z - Galactocentric rectangular coordinates
Xsun - cylindrical distance to the GC ( c... | dgc = nu . sqrt ( Xsun ** 2. + Zsun ** 2. )
costheta , sintheta = Xsun / dgc , Zsun / dgc
if isinstance ( Xsun , nu . ndarray ) :
zero = nu . zeros ( len ( Xsun ) )
one = nu . ones ( len ( Xsun ) )
Carr = nu . rollaxis ( nu . array ( [ [ - costheta , zero , - sintheta ] , [ zero , one , zero ] , [ - nu . si... |
def member_info ( self , member_id ) :
"""return information about member""" | server_id = self . _servers . host_to_server_id ( self . member_id_to_host ( member_id ) )
server_info = self . _servers . info ( server_id )
result = { '_id' : member_id , 'server_id' : server_id , 'mongodb_uri' : server_info [ 'mongodb_uri' ] , 'procInfo' : server_info [ 'procInfo' ] , 'statuses' : server_info [ 'sta... |
def contains ( self , point ) :
""": param point :
A Point object
: return :
Boolean if the point is on this curve""" | y2 = point . y * point . y
x3 = point . x * point . x * point . x
return ( y2 - ( x3 + self . a * point . x + self . b ) ) % self . p == 0 |
def _cursor ( self , * args , ** kwargs ) :
"""A " tough " version of the method cursor ( ) .""" | # The args and kwargs are not part of the standard ,
# but some database modules seem to use these .
transaction = self . _transaction
if not transaction :
self . _ping_check ( 2 )
try :
if self . _maxusage :
if self . _usage >= self . _maxusage : # the connection was used too often
raise se... |
def _cleanup ( self , lr_decay_opt_states_reset : str , process_manager : Optional [ 'DecoderProcessManager' ] = None , keep_training_state = False ) :
"""Cleans parameter files , training state directory and waits for remaining decoding processes .""" | utils . cleanup_params_files ( self . model . output_dir , self . max_params_files_to_keep , self . state . checkpoint , self . state . best_checkpoint , self . keep_initializations )
if process_manager is not None :
result = process_manager . collect_results ( )
if result is not None :
decoded_checkpoi... |
def process_dynesty_run ( results ) :
"""Transforms results from a dynesty run into the nestcheck dictionary
format for analysis . This function has been tested with dynesty v9.2.0.
Note that the nestcheck point weights and evidence will not be exactly
the same as the dynesty ones as nestcheck calculates logX... | samples = np . zeros ( ( results . samples . shape [ 0 ] , results . samples . shape [ 1 ] + 3 ) )
samples [ : , 0 ] = results . logl
samples [ : , 1 ] = results . samples_id
samples [ : , 3 : ] = results . samples
unique_th , first_inds = np . unique ( results . samples_id , return_index = True )
assert np . array_equ... |
def set_fluxinfo ( self ) :
"""Uses list of known flux calibrators ( with models in CASA ) to find full name given in scan .""" | knowncals = [ '3C286' , '3C48' , '3C147' , '3C138' ]
# find scans with knowncals in the name
sourcenames = [ self . sources [ source ] [ 'source' ] for source in self . sources ]
calsources = [ cal for src in sourcenames for cal in knowncals if cal in src ]
calsources_full = [ src for src in sourcenames for cal in know... |
def get_service ( station : str ) -> Service :
"""Returns the preferred service for a given station""" | for prefix in PREFERRED :
if station . startswith ( prefix ) :
return PREFERRED [ prefix ]
# type : ignore
return NOAA |
def getEncodableAttributes ( self , obj , ** kwargs ) :
"""Returns a C { tuple } containing a dict of static and dynamic attributes
for C { obj } .""" | attrs = pyamf . ClassAlias . getEncodableAttributes ( self , obj , ** kwargs )
if not self . exclude_sa_key : # primary _ key _ from _ instance actually changes obj . _ _ dict _ _ if
# primary key properties do not already exist in obj . _ _ dict _ _
attrs [ self . KEY_ATTR ] = self . mapper . primary_key_from_inst... |
def same_content ( ref_source , test_source , allow_removed_final_blank_line ) :
"""Is the content of two cells the same , except for an optional final blank line ?""" | if ref_source == test_source :
return True
if not allow_removed_final_blank_line :
return False
# Is ref identical to test , plus one blank line ?
ref_source = ref_source . splitlines ( )
test_source = test_source . splitlines ( )
if not ref_source :
return False
if ref_source [ : - 1 ] != test_source :
... |
def get_output_nodes ( G : nx . DiGraph ) -> List [ str ] :
"""Get all output nodes from a network .""" | return [ n for n , d in G . out_degree ( ) if d == 0 ] |
def _compute_fval ( X , A , R , P , Z , lmbdaA , lmbdaR , lmbdaZ , normX ) :
"""Compute fit for full slices""" | f = lmbdaA * norm ( A ) ** 2
for i in range ( len ( X ) ) :
ARAt = dot ( A , dot ( R [ i ] , A . T ) )
f += ( norm ( X [ i ] - ARAt ) ** 2 ) / normX [ i ] + lmbdaR * norm ( R [ i ] ) ** 2
return f |
def data ( self ) :
"""Read all of the documents from disk into an in - memory list .""" | def read ( path ) :
with open ( path , 'r' , encoding = 'UTF-8' ) as f :
return f . read ( )
return [ read ( f ) for f in self . files ] |
def _setup_images ( directory , brightness , saturation , hue , preserve_transparency ) :
"""Apply modifiers to the images of a theme
Modifies the images using the PIL . ImageEnhance module . Using
this function , theme images are modified to given them a
unique look and feel . Works best with PNG - based ima... | for file_name in os . listdir ( directory ) :
with open ( os . path . join ( directory , file_name ) , "rb" ) as fi :
image = Image . open ( fi ) . convert ( "RGBA" )
# Only perform required operations
if brightness != 1.0 :
enhancer = ImageEnhance . Brightness ( image )
image = enha... |
def patch ( originalfile , patchfile , options = '' , dry_run = False ) :
'''. . versionadded : : 0.10.4
Apply a patch to a file or directory .
Equivalent to :
. . code - block : : bash
patch < options > - i < patchfile > < originalfile >
Or , when a directory is patched :
. . code - block : : bash
pa... | patchpath = salt . utils . path . which ( 'patch' )
if not patchpath :
raise CommandExecutionError ( 'patch executable not found. Is the distribution\'s patch ' 'package installed?' )
cmd = [ patchpath ]
cmd . extend ( salt . utils . args . shlex_split ( options ) )
if dry_run :
if __grains__ [ 'kernel' ] in ( ... |
def eval_objfn ( self ) :
"""Compute components of regularisation function as well as total
contribution to objective function .""" | dfd = self . obfn_dfd ( )
prj = sp . proj_l1 ( self . obfn_gvar ( ) , self . gamma , axis = 0 )
cns = np . linalg . norm ( prj - self . obfn_gvar ( ) )
return ( dfd , cns ) |
def project_exists ( response : 'environ.Response' , path : str ) -> bool :
"""Determines whether or not a project exists at the specified path
: param response :
: param path :
: return :""" | if os . path . exists ( path ) :
return True
response . fail ( code = 'PROJECT_NOT_FOUND' , message = 'The project path does not exist' , path = path ) . console ( """
[ERROR]: Unable to open project. The specified path does not exist:
{path}
""" . format ( path = path ) )
return False |
def apply ( self ) :
"""Apply changes to the plots .""" | self . read_group_info ( )
if self . tabs . count ( ) == 0 : # disactivate buttons
self . button_color . setEnabled ( False )
self . button_del . setEnabled ( False )
self . button_apply . setEnabled ( False )
else : # activate buttons
self . button_color . setEnabled ( True )
self . button_del . se... |
def drinkAdmins ( self , objects = False ) :
"""Returns a list of drink admins uids""" | admins = self . group ( 'drink' , objects = objects )
return admins |
def work ( self , task , * args , ** kw ) :
"""Handles pushing out the task and getting the response . Can be called
directly to wait for the response .
task - - the server - side identifier for the desired task
* args and * * kw will be passed to the task on the server - side .
Return value is generally th... | package = self . _package ( task , * args , ** kw )
backends = sorted ( self . backends , key = self . _sorter )
for backend in backends :
try :
return self . _work ( backend , package , task )
except socket . error : # We want to just move onto the next backend if we couldn ' t
# connect to this on... |
def pull ( self , remote = None , revision = None ) :
"""Pull changes from a remote repository into the local repository .
: param remote : The location of a remote repository ( a string or : data : ` None ` ) .
: param revision : A specific revision to pull ( a string or : data : ` None ` ) .
If used in comb... | remote = remote or self . remote
# Make sure the local repository exists .
if self . create ( ) and ( remote == self . remote or not remote ) : # Don ' t waste time pulling from a remote repository that we just cloned .
logger . info ( "Skipping pull from default remote because we just created the local %s reposito... |
def release ( self , message_id , reservation_id , delay = 0 ) :
"""Release locked message after specified time . If there is no message with such id on the queue .
Arguments :
message _ id - - The ID of the message .
reservation _ id - - Reservation Id of the message .
delay - - The time after which the me... | url = "queues/%s/messages/%s/release" % ( self . name , message_id )
body = { 'reservation_id' : reservation_id }
if delay > 0 :
body [ 'delay' ] = delay
body = json . dumps ( body )
response = self . client . post ( url , body = body , headers = { 'Content-Type' : 'application/json' } )
return response [ 'body' ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.