signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_logger ( name = None , level = logging . DEBUG , stream = None ) :
"""returns a colorized logger . This function can be used just like
: py : func : ` logging . getLogger ` except you can set the level right
away .""" | logger = logging . getLogger ( name )
colored = colorize_logger ( logger , stream = stream , level = level )
return colored |
def get_label_vocab ( vocab_path ) :
"""Returns a list of label strings loaded from the provided path .""" | if vocab_path :
try :
with tf . io . gfile . GFile ( vocab_path , 'r' ) as f :
return [ line . rstrip ( '\n' ) for line in f ]
except tf . errors . NotFoundError as err :
tf . logging . error ( 'error reading vocab file: %s' , err )
return [ ] |
def rbinomial ( n , p , size = None ) :
"""Random binomial variates .""" | if not size :
size = None
return np . random . binomial ( np . ravel ( n ) , np . ravel ( p ) , size ) |
def new_edge ( self , node_a , node_b , cost = 1 ) :
"""Adds a new edge from node _ a to node _ b that has a cost .
Returns the edge id of the new edge .""" | # Verify that both nodes exist in the graph
try :
self . nodes [ node_a ]
except KeyError :
raise NonexistentNodeError ( node_a )
try :
self . nodes [ node_b ]
except KeyError :
raise NonexistentNodeError ( node_b )
# Create the new edge
edge_id = self . generate_edge_id ( )
edge = { 'id' : edge_id , 'v... |
def show_key ( self , value ) :
"""Get a specific canned key
: type value : str
: param value : Canned key to show
: rtype : dict
: return : A dictionnary containing canned key description""" | keys = self . get_keys ( )
keys = [ x for x in keys if x [ 'label' ] == value ]
if len ( keys ) == 0 :
raise Exception ( "Unknown key" )
else :
return keys [ 0 ] |
def _folder_to_dict ( self , path ) :
"""Recursively reads the files from the directory given by ` path ` and
writes their contents to a nested dictionary , which is then returned .""" | res = { }
for key in os . listdir ( path ) :
if key . startswith ( '.' ) :
continue
key_path = os . path . join ( path , key )
if os . path . isfile ( key_path ) :
val = open ( key_path ) . read ( )
key = key . split ( '.' ) [ 0 ]
res [ key ] = val
else :
res [ ke... |
def average ( old_avg , current_value , count ) :
"""Calculate the average . Count must start with 0
> > > average ( None , 3.23 , 0)
3.23
> > > average ( 0 , 1 , 0)
1.0
> > > average ( 2.5 , 5 , 4)
3.0""" | if old_avg is None :
return current_value
return ( float ( old_avg ) * count + current_value ) / ( count + 1 ) |
def groups_kick ( self , room_id , user_id , ** kwargs ) :
"""Removes a user from the private group .""" | return self . __call_api_post ( 'groups.kick' , roomId = room_id , userId = user_id , kwargs = kwargs ) |
def _validate_lists ( sa , allowed_types = [ str ] , require_same_type = True , require_equal_length = False , num_to_check = 10 ) :
"""For a list - typed SArray , check whether the first elements are lists that
- contain only the provided types
- all have the same lengths ( optionally )
Parameters
sa : SAr... | if len ( sa ) == 0 :
return True
first_elements = sa . head ( num_to_check )
if first_elements . dtype != list :
raise ValueError ( "Expected an SArray of lists when type-checking lists." )
# Check list lengths
list_lengths = list ( first_elements . item_length ( ) )
same_length = _check_elements_equal ( list_l... |
def QA_fetch_stock_list ( collections = DATABASE . stock_list ) :
'获取股票列表' | return pd . DataFrame ( [ item for item in collections . find ( ) ] ) . drop ( '_id' , axis = 1 , inplace = False ) . set_index ( 'code' , drop = False ) |
def docpie ( self , argv = None ) :
"""match the argv for each usages , return dict .
if argv is None , it will use sys . argv instead .
if argv is str , it will call argv . split ( ) first .
this function will check the options in self . extra and handle it first .
Which means it may not try to match any u... | token = self . _prepare_token ( argv )
# check first , raise after
# so ` - hwhatever ` can trigger ` - h ` first
self . check_flag_and_handler ( token )
if token . error is not None : # raise DocpieExit ( ' % s \ n \ n % s ' % ( token . error , help _ msg ) )
self . exception_handler ( token . error )
try :
re... |
def get_index_from_alias ( alias_name , index_client = None ) :
"""Retrieve the base index name from an alias
Args :
alias _ name ( str ) Name of the alias
index _ client ( Elasticsearch . IndicesClient ) an Elasticsearch index
client . Optional , will create one if not given
Returns : ( str ) Name of ind... | index_client = index_client or indices_client ( )
if not index_client . exists_alias ( name = alias_name ) :
return None
return list ( index_client . get_alias ( name = alias_name ) . keys ( ) ) [ 0 ] |
def get_sum ( hdf5_file , path , array_out , out_lock , rows_slice ) :
"""Access an array at node ' path ' of the ' hdf5 _ file ' , compute the sums
along a slice of rows specified by ' rows _ slice ' and add the resulting
vector to ' array _ out ' .
Parameters
hdf5 _ file : string or file handle
The loca... | Worker . hdf5_lock . acquire ( )
with tables . open_file ( hdf5_file , 'r+' ) as fileh :
hdf5_array = fileh . get_node ( path )
tmp = hdf5_array [ rows_slice , ... ]
Worker . hdf5_lock . release ( )
szum = np . sum ( tmp , axis = 0 )
with out_lock :
array_out += szum
del tmp |
def _select_server ( self , server_selector , session , address = None ) :
"""Select a server to run an operation on this client .
: Parameters :
- ` server _ selector ` : The server selector to use if the session is
not pinned and no address is given .
- ` session ` : The ClientSession for the next operati... | try :
topology = self . _get_topology ( )
address = address or ( session and session . _pinned_address )
if address : # We ' re running a getMore or this session is pinned to a mongos .
server = topology . select_server_by_address ( address )
if not server :
raise AutoReconnect (... |
def quatInv ( q ) :
"""Returns QBar such that Q * QBar = 1""" | qConj = - q
qConj [ 0 ] = - qConj [ 0 ]
normSqr = multiplyQuats ( q , qConj ) [ 0 ]
return qConj / normSqr |
def __get_config ( self ) :
"""Really connect""" | if not self . name :
room_resp = self . conn . get ( BASE_URL + "/new" )
room_resp . raise_for_status ( )
url = room_resp . url
try :
self . name = re . search ( r"r/(.+?)$" , url ) . group ( 1 )
except Exception :
raise IOError ( "Failed to create room" )
params = { "room" : self . ... |
def list_metafeatures ( cls , group = "all" ) :
"""Returns a list of metafeatures computable by the Metafeatures class .""" | # todo make group for intractable metafeatures for wide datasets or
# datasets with high cardinality categorical columns :
# PredPCA1 , PredPCA2 , PredPCA3 , PredEigen1 , PredEigen2 , PredEigen3,
# PredDet , kNN1NErrRate , kNN1NKappa , LinearDiscriminantAnalysisKappa ,
# LinearDiscriminantAnalysisErrRate
if group == "a... |
def write_flows_to_gssha_time_series_ihg ( self , path_to_output_file , connection_list_file , date_search_start = None , date_search_end = None , daily = False , filter_mode = "mean" ) : # pylint : disable = line - too - long
"""Write out RAPID output to GSSHA time series ihg file
. . note : : See : http : / / w... | # noqa
self . raise_time_valid ( )
# analyze and write
with open_csv ( path_to_output_file , 'w' ) as out_ts : # HEADER SECTION EXAMPLE :
# NUMPT 3
# POINT 1 599 0.0
# POINT 1 603 0.0
# POINT 1 605 0.0
connection_list = np . loadtxt ( connection_list_file , skiprows = 1 , ndmin = 1 , delimiter = ',' , usecols = ( 0... |
def max_spline_jumps ( self , convert_to_muC_per_cm2 = True , all_in_polar = True ) :
"""Get maximum difference between spline and same branch polarization data .""" | tot = self . get_same_branch_polarization_data ( convert_to_muC_per_cm2 = convert_to_muC_per_cm2 , all_in_polar = all_in_polar )
sps = self . same_branch_splines ( convert_to_muC_per_cm2 = convert_to_muC_per_cm2 , all_in_polar = all_in_polar )
max_jumps = [ None , None , None ]
for i , sp in enumerate ( sps ) :
if ... |
def format ( self , record ) :
"""Print out any ' extra ' data provided in logs .""" | if hasattr ( record , 'data' ) :
return "%s. DEBUG DATA=%s" % ( logging . Formatter . format ( self , record ) , record . __dict__ [ 'data' ] )
return logging . Formatter . format ( self , record ) |
def export ( self , nidm_version , export_dir ) :
"""Create prov entities and activities .""" | # In FSL we have a single thresholding ( extent , height ) applied to all
# contrasts
# FIXME : Deal with two - tailed inference ?
atts = ( ( PROV [ 'type' ] , self . type ) , ( PROV [ 'label' ] , self . label ) , ( NIDM_HAS_ALTERNATIVE_HYPOTHESIS , self . tail ) )
if self . partial_degree is not None :
atts += ( (... |
def parser ( format_name , ext_names = None ) :
"""Decorate a parser class to register it .
: param format _ name : standard format name
: param ext _ names : supported extension name""" | def decorator ( cls ) :
format_name_lower = format_name . lower ( )
if ext_names is None :
_ext_format_mapping [ format_name_lower ] = format_name_lower
else :
for ext in to_list ( ext_names ) :
_ext_format_mapping [ ext . lower ( ) ] = format_name_lower
_format_parser_mappin... |
def join_lines ( lines_enum ) : # type : ( ReqFileLines ) - > ReqFileLines
"""Joins a line ending in ' \' with the previous line ( except when following
comments ) . The joined line takes on the index of the first line .""" | primary_line_number = None
new_line = [ ]
# type : List [ Text ]
for line_number , line in lines_enum :
if not line . endswith ( '\\' ) or COMMENT_RE . match ( line ) :
if COMMENT_RE . match ( line ) : # this ensures comments are always matched later
line = ' ' + line
if new_line :
... |
def filter_contents_translations ( generator ) :
'''Filter the content and translations lists of a generator
Filters out
1 ) translations which will be generated in a different site
2 ) content that is not in the language of the currently
generated site but in that of a different site , content in a
langu... | inspector = GeneratorInspector ( generator )
current_lang = generator . settings [ 'DEFAULT_LANG' ]
langs_with_sites = _SITE_DB . keys ( )
removed_contents = _GENERATOR_DB [ generator ]
for translations in inspector . translations_lists ( ) :
for translation in translations [ : ] : # copy to be able to remove
... |
def handle ( self , t_input : inference . TranslatorInput , t_output : inference . TranslatorOutput , t_walltime : float = 0. ) :
"""Outputs a JSON object of the fields in the ` TranslatorOutput ` object .""" | d_ = t_output . json ( self . align_threshold )
self . stream . write ( "%s\n" % json . dumps ( d_ , sort_keys = True ) )
self . stream . flush ( ) |
def diff_write_only ( resource ) :
"""A different implementation of diff that is
used for those Vault resources that are write - only
such as AWS root configs""" | if resource . present and not resource . existing :
return ADD
elif not resource . present and resource . existing :
return DEL
elif resource . present and resource . existing :
return OVERWRITE
return NOOP |
def get_bucket_notification_config ( self , bucket ) :
"""Get the notification configuration of a bucket .
@ param bucket : The name of the bucket .
@ return : A C { Deferred } that will request the bucket ' s notification
configuration .""" | details = self . _details ( method = b"GET" , url_context = self . _url_context ( bucket = bucket , object_name = "?notification" ) , )
d = self . _submit ( self . _query_factory ( details ) )
d . addCallback ( self . _parse_notification_config )
return d |
def set ( self , name , value , ** kwargs ) :
"""Dict - like set ( ) that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains .""" | # support client code that unsets cookies by assignment of a None value :
if value is None :
remove_cookie_by_name ( self , name , domain = kwargs . get ( 'domain' ) , path = kwargs . get ( 'path' ) )
return
if isinstance ( value , Morsel ) :
c = morsel_to_cookie ( value )
else :
c = create_cookie ( nam... |
def disenriched ( self , thresh = 0.05 , idx = True ) :
"""Disenriched features .
{ threshdoc }""" | return self . downregulated ( thresh = thresh , idx = idx ) |
def files_with_exts ( root = '.' , suffix = '' ) :
"""Returns generator that contains filenames
from root directory and ends with suffix""" | return ( os . path . join ( rootdir , filename ) for rootdir , dirnames , filenames in os . walk ( root ) for filename in filenames if filename . endswith ( suffix ) ) |
def add_site ( self , name , site_elements = None ) :
"""Add a VPN site with site elements to this engine .
VPN sites identify the sites with protected networks
to be included in the VPN .
Add a network and new VPN site : :
> > > net = Network . get _ or _ create ( name = ' wireless ' , ipv4 _ network = ' 1... | site_elements = site_elements if site_elements else [ ]
return self . sites . create ( name , site_elements ) |
def errReceived ( self , data ) :
""": api : ` twisted . internet . protocol . ProcessProtocol < ProcessProtocol > ` API""" | if self . stderr :
self . stderr . write ( data )
if self . kill_on_stderr :
self . transport . loseConnection ( )
raise RuntimeError ( "Received stderr output from slave Tor process: " + data . decode ( 'utf8' ) ) |
def _create_html_file_content ( translations ) :
"""Create html string out of translation dict .
Parameters
tralnslations : dict
Dictionary of word translations .
Returns
str :
html string of translation""" | content = [ ]
for i1 , t in enumerate ( translations ) :
if i1 > 0 :
content . append ( "<br>" )
content . append ( '<div class="translation">' )
content . append ( '<div class="word">' )
for w in t . word :
content . append ( "<h2>{word}</h2>" . format ( word = w ) )
content . appen... |
def full_url ( self ) :
"""Taken from
http : / / legacy . python . org / dev / peps / pep - 3333 / # url - reconstruction
: return : Reconstructed URL from WSGI environment .""" | environ = self . wsgi_environ
url = environ [ 'wsgi.url_scheme' ] + '://'
if environ . get ( 'HTTP_HOST' ) :
url += environ [ 'HTTP_HOST' ]
else :
url += environ [ 'SERVER_NAME' ]
if environ [ 'wsgi.url_scheme' ] == 'https' :
if environ [ 'SERVER_PORT' ] != '443' :
url += ':' + environ [... |
def get_mcc ( self , ip ) :
'''Get mcc''' | rec = self . get_all ( ip )
return rec and rec . mcc |
def detached_signature_for ( plaintext_str , keys ) :
"""Signs the given plaintext string and returns the detached signature .
A detached signature in GPG speak is a separate blob of data containing
a signature for the specified plaintext .
: param bytes plaintext _ str : bytestring to sign
: param keys : l... | ctx = gpg . core . Context ( armor = True )
ctx . signers = keys
( sigblob , sign_result ) = ctx . sign ( plaintext_str , mode = gpg . constants . SIG_MODE_DETACH )
return sign_result . signatures , sigblob |
def _append_array ( self , value , _file ) :
"""Call this function to write array contents .
Keyword arguments :
* value - dict , content to be dumped
* _ file - FileIO , output file""" | _tabs = '\t' * self . _tctr
_labs = '{tabs}<array>\n' . format ( tabs = _tabs )
_file . write ( _labs )
self . _tctr += 1
for _item in value :
if _item is None :
continue
_item = self . object_hook ( _item )
_type = type ( _item ) . __name__
_MAGIC_TYPES [ _type ] ( self , _item , _file )
self .... |
def wind_send ( self , direction , speed , speed_z , force_mavlink1 = False ) :
'''Wind estimation
direction : wind direction that wind is coming from ( degrees ) ( float )
speed : wind speed in ground plane ( m / s ) ( float )
speed _ z : vertical wind speed ( m / s ) ( float )''' | return self . send ( self . wind_encode ( direction , speed , speed_z ) , force_mavlink1 = force_mavlink1 ) |
def commodity_channel_index ( close_data , high_data , low_data , period ) :
"""Commodity Channel Index .
Formula :
CCI = ( TP - SMA ( TP ) ) / ( 0.015 * Mean Deviation )""" | catch_errors . check_for_input_len_diff ( close_data , high_data , low_data )
catch_errors . check_for_period_error ( close_data , period )
tp = typical_price ( close_data , high_data , low_data )
cci = ( ( tp - sma ( tp , period ) ) / ( 0.015 * np . mean ( np . absolute ( tp - np . mean ( tp ) ) ) ) )
return cci |
def templates ( self , name = None , params = None ) :
"""` < https : / / www . elastic . co / guide / en / elasticsearch / reference / current / cat - templates . html > ` _
: arg name : A pattern that returned template names must match
: arg format : a short version of the Accept header , e . g . json , yaml ... | return self . transport . perform_request ( 'GET' , _make_path ( '_cat' , 'templates' , name ) , params = params ) |
def delete_records ( keep = 20 ) :
"""Clean up files on server and mark the record as deleted""" | sql = "SELECT * from records where is_deleted<>1 ORDER BY id desc LIMIT -1 offset {}" . format ( keep )
assert isinstance ( g . db , sqlite3 . Connection )
c = g . db . cursor ( )
c . execute ( sql )
rows = c . fetchall ( )
for row in rows :
name = row [ 1 ]
xmind = join ( app . config [ 'UPLOAD_FOLDER' ] , nam... |
def propose ( self ) :
"""This method is called by step ( ) to generate proposed values
if self . proposal _ distribution is " Normal " ( i . e . no proposal specified ) .""" | prop_dist = self . proposal_distribution . lower ( )
if prop_dist == "normal" :
self . stochastic . value = rnormal ( self . stochastic . value , self . adaptive_scale_factor * self . proposal_sd , size = self . stochastic . value . shape )
elif prop_dist == "prior" :
self . stochastic . random ( ) |
def _handle_subscription ( self , topics ) :
"""Handle subscription of topics .""" | if not isinstance ( topics , list ) :
topics = [ topics ]
for topic in topics :
topic_levels = topic . split ( '/' )
try :
qos = int ( topic_levels [ - 2 ] )
except ValueError :
qos = 0
try :
_LOGGER . debug ( 'Subscribing to: %s, qos: %s' , topic , qos )
self . _sub_... |
def mw ( mol , ndigits = 2 ) :
"""Return standard molecular weight
: param ndigits : number of digits""" | mol . require ( "Valence" )
return round ( sum ( a . mw ( ) for _ , a in mol . atoms_iter ( ) ) , ndigits ) |
def _wordAfterCursor ( self ) :
"""Get word , which is located before cursor""" | cursor = self . _qpart . textCursor ( )
textAfterCursor = cursor . block ( ) . text ( ) [ cursor . positionInBlock ( ) : ]
match = _wordAtStartRegExp . search ( textAfterCursor )
if match :
return match . group ( 0 )
else :
return '' |
def makesubatoffset ( self , bitoffset , * , _offsetideal = None ) :
"""Create a copy of this PromiseCollection with an offset applied to each contained promise and register each with their parent .
If this promise ' s primitive is being merged with another
primitive , a new subpromise may be required to keep t... | if _offsetideal is None :
_offsetideal = bitoffset
if bitoffset is 0 :
return self
newpromise = TDOPromiseCollection ( self . _chain )
for promise in self . _promises :
newpromise . add ( promise , bitoffset , _offsetideal = _offsetideal )
return newpromise |
def send_direct_message_new ( self , messageobject ) :
""": reference : https : / / developer . twitter . com / en / docs / direct - messages / sending - and - receiving / api - reference / new - event . html""" | headers , post_data = API . _buildmessageobject ( messageobject )
return bind_api ( api = self , path = '/direct_messages/events/new.json' , method = 'POST' , require_auth = True ) ( self , post_data = post_data , headers = headers ) |
def dip_direction2strike ( azimuth ) :
"""Converts a planar measurment of dip direction using the dip - azimuth
convention into a strike using the right - hand - rule .
Parameters
azimuth : number or string
The dip direction of the plane in degrees . This can be either a
numerical azimuth in the 0-360 ran... | azimuth = parse_azimuth ( azimuth )
strike = azimuth - 90
if strike < 0 :
strike += 360
return strike |
def create_groups ( self , container ) :
"""CreateGroups .
: param : class : ` < object > < azure . devops . v5_0 . identity . models . object > ` container :
: rtype : [ Identity ]""" | content = self . _serialize . body ( container , 'object' )
response = self . _send ( http_method = 'POST' , location_id = '5966283b-4196-4d57-9211-1b68f41ec1c2' , version = '5.0' , content = content )
return self . _deserialize ( '[Identity]' , self . _unwrap_collection ( response ) ) |
def unixtime_to_datetime ( ut ) :
"""Convert a unixtime timestamp to a datetime object .
The function converts a timestamp in Unix format to a
datetime object . UTC timezone will also be set .
: param ut : Unix timestamp to convert
: returns : a datetime object
: raises InvalidDateError : when the given t... | try :
dt = datetime . datetime . utcfromtimestamp ( ut )
dt = dt . replace ( tzinfo = dateutil . tz . tzutc ( ) )
return dt
except Exception :
raise InvalidDateError ( date = str ( ut ) ) |
def slistFloat ( slist ) :
"""Converts signed list to float .""" | values = [ v / 60 ** ( i ) for ( i , v ) in enumerate ( slist [ 1 : ] ) ]
value = sum ( values )
return - value if slist [ 0 ] == '-' else value |
def consume ( self , callback = None , queue = '' , consumer_tag = '' , exclusive = False , no_ack = False , no_local = False , arguments = None ) :
"""Start a queue consumer .
: param function callback : Message callback
: param str queue : Queue name
: param str consumer _ tag : Consumer tag
: param bool ... | if not compatibility . is_string ( queue ) :
raise AMQPInvalidArgument ( 'queue should be a string' )
elif not compatibility . is_string ( consumer_tag ) :
raise AMQPInvalidArgument ( 'consumer_tag should be a string' )
elif not isinstance ( exclusive , bool ) :
raise AMQPInvalidArgument ( 'exclusive should... |
def get ( cls , pid_type , pid_value , pid_provider = None ) :
"""Get persistent identifier .
: param pid _ type : Persistent identifier type .
: param pid _ value : Persistent identifier value .
: param pid _ provider : Persistent identifier provider . ( default : None ) .
: raises : : exc : ` invenio _ pi... | try :
args = dict ( pid_type = pid_type , pid_value = six . text_type ( pid_value ) )
if pid_provider :
args [ 'pid_provider' ] = pid_provider
return cls . query . filter_by ( ** args ) . one ( )
except NoResultFound :
raise PIDDoesNotExistError ( pid_type , pid_value ) |
def projection_error ( nodes , projected ) :
"""Compute the error between ` ` nodes ` ` and the projected nodes .
. . note : :
This is a helper for : func : ` maybe _ reduce ` , which is in turn a helper
for : func : ` _ full _ reduce ` . Hence there is no corresponding Fortran
speedup .
For now , just co... | relative_err = np . linalg . norm ( nodes - projected , ord = "fro" )
if relative_err != 0.0 :
relative_err /= np . linalg . norm ( nodes , ord = "fro" )
return relative_err |
def _parse_methods ( cls , list_string ) :
"""Return HTTP method list . Use json for security reasons .""" | if list_string is None :
return APIServer . DEFAULT_METHODS
# json requires double quotes
json_list = list_string . replace ( "'" , '"' )
return json . loads ( json_list ) |
def bundle ( self , * arguments , ** extra ) :
"""Bundle the given arguments in a C { dict } with EC2 - style format .
@ param arguments : L { Arguments } instances to bundle . Keys in
later objects will override those in earlier objects .
@ param extra : Any number of additional parameters . These will overr... | params = { }
for argument in arguments :
params . update ( argument )
params . update ( extra )
result = { }
for name , value in params . iteritems ( ) :
if value is None :
continue
segments = name . split ( '.' )
first = segments [ 0 ]
parameter = self . get_parameter ( first )
if param... |
def array_bytes ( array ) :
"""Estimates the memory of the supplied array in bytes""" | return np . product ( array . shape ) * np . dtype ( array . dtype ) . itemsize |
def forwards ( self , orm ) :
"Write your forwards methods here ." | orm [ 'avocado.DataField' ] . objects . filter ( app_name = 'samples' , model_name = 'cohort' , field_name__in = [ 'investigator' , 'notes' ] ) . delete ( ) |
def finalize ( self ) :
"""Is called when the editor is closed . Disconnect signals .""" | self . pickButton . clicked . disconnect ( self . openColorDialog )
super ( ColorCtiEditor , self ) . finalize ( ) |
def remove_header ( self , name ) :
"""Remove a field from the header""" | if name in self . info_dict :
self . info_dict . pop ( name )
logger . info ( "Removed '{0}' from INFO" . format ( name ) )
if name in self . filter_dict :
self . filter_dict . pop ( name )
logger . info ( "Removed '{0}' from FILTER" . format ( name ) )
if name in self . format_dict :
self . format_... |
def _limit_and_df ( self , query , limit , as_df = False ) :
"""adds a limit ( limit = = None : = no limit ) to any query and allow a return as pandas . DataFrame
: param bool as _ df : if is set to True results return as pandas . DataFrame
: param ` sqlalchemy . orm . query . Query ` query : SQL Alchemy query ... | if limit :
if isinstance ( limit , int ) :
query = query . limit ( limit )
if isinstance ( limit , Iterable ) and len ( limit ) == 2 and [ int , int ] == [ type ( x ) for x in limit ] :
page , page_size = limit
query = query . limit ( page_size )
query = query . offset ( page * p... |
def load_mutation_rates ( path = None ) :
"""load sequence context - based mutation rates
Args :
path : path to table of sequence context - based mutation rates . If None ,
this defaults to per - trinucleotide rates provided by Kaitlin Samocha
( Broad Institute ) .
Returns :
list of [ initial , changed ... | if path is None :
path = resource_filename ( __name__ , "data/rates.txt" )
rates = [ ]
with open ( path ) as handle :
for line in handle :
if line . startswith ( "from" ) : # ignore the header line
continue
line = [ x . encode ( 'utf8' ) for x in line . strip ( ) . split ( ) ]
... |
def _generate_grid ( self ) :
"""Get the all possible values for each of the tunables .""" | grid_axes = [ ]
for _ , param in self . tunables :
grid_axes . append ( param . get_grid_axis ( self . grid_width ) )
return grid_axes |
def check_minmax ( plotman , cid , xmin , xmax , zmin , zmax , vmin , vmax ) :
'''Get min and max values for axes and colorbar if not given''' | if xmin is None :
xmin = plotman . grid . grid [ 'x' ] . min ( )
if xmax is None :
xmax = plotman . grid . grid [ 'x' ] . max ( )
if zmin is None :
zmin = plotman . grid . grid [ 'z' ] . min ( )
if zmax is None :
zmax = plotman . grid . grid [ 'z' ] . max ( )
if isinstance ( cid , int ) :
subdata = ... |
def non_transactional ( func , args , kwds , allow_existing = True ) :
"""A decorator that ensures a function is run outside a transaction .
If there is an existing transaction ( and allow _ existing = True ) , the
existing transaction is paused while the function is executed .
Args :
allow _ existing : If ... | from . import tasklets
ctx = tasklets . get_context ( )
if not ctx . in_transaction ( ) :
return func ( * args , ** kwds )
if not allow_existing :
raise datastore_errors . BadRequestError ( '%s cannot be called within a transaction.' % func . __name__ )
save_ctx = ctx
while ctx . in_transaction ( ) :
ctx = ... |
def combine_uncertainties ( op , unc1 , unc2 , nom1 = None , nom2 = None , rho = 0. ) :
"""Combines two uncertainties * unc1 * and * unc2 * according to an operator * op * which must be either
` ` " + " ` ` , ` ` " - " ` ` , ` ` " * " ` ` , ` ` " / " ` ` , or ` ` " * * " ` ` . The three latter operators require t... | # operator valid ?
if op in _op_map :
f = _op_map [ op ]
elif op in _op_map_reverse :
f = op
op = _op_map_reverse [ op ]
else :
raise ValueError ( "unknown operator: {}" . format ( op ) )
# prepare values for combination , depends on operator
if op in ( "*" , "/" , "**" ) :
if nom1 is None or nom2 i... |
def list_user_access ( self , user ) :
"""Returns a list of all database names for which the specified user
has access rights .""" | user = utils . get_name ( user )
uri = "/%s/%s/databases" % ( self . uri_base , user )
try :
resp , resp_body = self . api . method_get ( uri )
except exc . NotFound as e :
raise exc . NoSuchDatabaseUser ( "User '%s' does not exist." % user )
dbs = resp_body . get ( "databases" , { } )
return [ CloudDatabaseDat... |
def _systemctl_status ( name ) :
'''Helper function which leverages _ _ context _ _ to keep from running ' systemctl
status ' more than once .''' | contextkey = 'systemd._systemctl_status.%s' % name
if contextkey in __context__ :
return __context__ [ contextkey ]
__context__ [ contextkey ] = __salt__ [ 'cmd.run_all' ] ( _systemctl_cmd ( 'status' , name ) , python_shell = False , redirect_stderr = True , ignore_retcode = True )
return __context__ [ contextkey ] |
def _complete_last_byte ( self , packet ) :
"""Pad until the packet length is a multiple of 8 ( bytes ) .""" | padded_size = self . get_size ( )
padding_bytes = padded_size - len ( packet )
if padding_bytes > 0 :
packet += Pad ( padding_bytes ) . pack ( )
return packet |
def run ( self ) :
"""Reimplements the : meth : ` QThread . run ` method .""" | self . __timer = QTimer ( )
self . __timer . moveToThread ( self )
self . __timer . start ( Constants . default_timer_cycle * self . __timer_cycle_multiplier )
self . __timer . timeout . connect ( self . __watch_file_system , Qt . DirectConnection )
self . exec_ ( ) |
def list_pages_ajax ( request , invalid_move = False ) :
"""Render pages table for ajax function .""" | language = get_language_from_request ( request )
pages = Page . objects . root ( )
context = { 'invalid_move' : invalid_move , 'language' : language , 'pages' : pages , }
return render_to_response ( "admin/basic_cms/page/change_list_table.html" , context , context_instance = RequestContext ( request ) ) |
def cite_mini ( self ) :
"""Return string with a citation for the record , formatted as :
' { first _ author } - { year } - { journal } '""" | citation_data = [ self . first_author ]
if len ( self . _author_list ) > 1 :
citation_data . append ( self . last_author )
citation_data . extend ( [ self . year , self . journal ] )
return " - " . join ( citation_data ) |
def fetch_protein_gene_map ( self , taxon_id ) :
"""Fetch a list of proteins for a species in biomart
: param taxid :
: return : dict""" | protein_dict = dict ( )
# col = self . columns [ ' ensembl _ biomart ' ]
col = [ 'ensembl_peptide_id' , 'ensembl_gene_id' ]
raw_query = self . _build_biomart_gene_query ( taxon_id , col )
params = urllib . parse . urlencode ( { 'query' : raw_query } )
conn = http . client . HTTPConnection ( ENS_URL )
conn . request ( "... |
def get_loss ( self , logits : mx . sym . Symbol , labels : mx . sym . Symbol ) -> mx . sym . Symbol :
"""Returns loss and softmax output symbols given logits and integer - coded labels .
: param logits : Shape : ( batch _ size * target _ seq _ len , target _ vocab _ size ) .
: param labels : Shape : ( batch _ ... | raise NotImplementedError ( ) |
def split_genotype ( genotype , gt_format , alternative_number , allele_symbol = '0' ) :
"""Take a genotype call and make a new one that is working for the new
splitted variant
Arguments :
genotype ( str ) : The original genotype call
gt _ format ( str ) : The format of the gt call
alternative _ number ( ... | logger = getLogger ( __name__ )
logger . info ( "Allele symbol {0}" . format ( allele_symbol ) )
splitted_genotype = genotype . split ( ':' )
logger . debug ( "Parsing genotype {0}" . format ( splitted_genotype ) )
splitted_gt_format = gt_format . split ( ':' )
logger . debug ( "Parsing gt format {0}" . format ( splitt... |
def GetDictToFormat ( self ) :
"""Return a copy of self as a dict , suitable for passing to FormatProblem""" | d = { }
for k , v in self . __dict__ . items ( ) : # TODO : Better handling of unicode / utf - 8 within Schedule objects .
# Concatinating a unicode and utf - 8 str object causes an exception such
# as " UnicodeDecodeError : ' ascii ' codec can ' t decode byte . . . " as python
# tries to convert the str to a unicode .... |
def getProvIden ( self , provstack ) :
'''Returns the iden corresponding to a provenance stack and stores if it hasn ' t seen it before''' | iden = _providen ( provstack )
misc , frames = provstack
# Convert each frame back from ( k , v ) tuples to a dict
dictframes = [ ( typ , { k : v for ( k , v ) in info } ) for ( typ , info ) in frames ]
bytz = s_msgpack . en ( ( misc , dictframes ) )
didwrite = self . slab . put ( iden , bytz , overwrite = False , db =... |
def create ( self , key , value = None , dir = False , ttl = None , timeout = None ) :
"""Creates a new key .""" | return self . adapter . set ( key , value , dir = dir , ttl = ttl , prev_exist = False , timeout = timeout ) |
def obj_to_txt ( self , file_path = None , deliminator = None , tab = None , quote_numbers = True , quote_empty_str = False ) :
"""This will return a simple str table .
: param file _ path : str of the path to the file
: param keys : list of str of the order of keys to use
: param tab : string of offset of th... | return self . obj_to_str ( file_path = file_path , deliminator = deliminator , tab = tab , quote_numbers = quote_numbers , quote_empty_str = quote_empty_str ) |
def ignore_comments ( lines_enum ) : # type : ( ReqFileLines ) - > ReqFileLines
"""Strips comments and filter empty lines .""" | for line_number , line in lines_enum :
line = COMMENT_RE . sub ( '' , line )
line = line . strip ( )
if line :
yield line_number , line |
def chk_goids ( goids , msg = None , raise_except = True ) :
"""check that all GO IDs have the proper format .""" | for goid in goids :
if not goid_is_valid ( goid ) :
if raise_except :
raise RuntimeError ( "BAD GO({GO}): {MSG}" . format ( GO = goid , MSG = msg ) )
else :
return goid |
def namedb_get_all_blockstack_ops_at ( db , block_id , offset = None , count = None ) :
"""Get the states that each name , namespace , and account record
passed through in the given block . Note that this only concerns
operations written on - chain , for use in SNV and database verification
( i . e . does not... | assert ( count is None and offset is None ) or ( count is not None and offset is not None ) , 'Invalid arguments: expect both offset/count or neither offset/count'
ret = [ ]
cur = db . cursor ( )
# how many preorders at this block ?
offset_count_query , offset_count_args = namedb_offset_count_predicate ( offset = offse... |
def session ( self , create = True ) :
"""Used to created default session""" | if hasattr ( self . local , 'session' ) :
return self . local . session
else :
if create :
s = Session ( self . name )
self . local . session = s
return s |
def get_repo_revision ( ) :
'''Returns mercurial revision string somelike ` hg identify ` does .
Format is rev1 : short - id1 + ; rev2 : short - id2 +
Returns an empty string if anything goes wrong , such as missing
. hg files or an unexpected format of internal HG files or no
mercurial repository found .''... | repopath = _findrepo ( )
if not repopath :
return ''
# first try to use mercurial itself
try :
import mercurial . hg , mercurial . ui , mercurial . scmutil
from mercurial . node import short as hexfunc
except ImportError :
pass
else :
ui = mercurial . ui . ui ( )
repo = mercurial . hg . reposito... |
def _get_tag ( self , url , tag , print_warn = True ) :
"""Check if url is available and returns given tag type
: param url : url to content relative to base url
: param anchor : anchor type to return
: param print _ warn : if True print warn when url is unavailable""" | # construct complete url
complete_url = urljoin ( self . base_url , url )
# check if exists
if requests . get ( 'http:' + complete_url ) . ok : # construct tag
if tag == 'script' :
return '<script src="{0}"></script>' . format ( complete_url )
elif tag == 'stylesheet' :
return '<link rel="styles... |
def _generate ( ) :
"""Generate a new SSH key pair .""" | privateKey = rsa . generate_private_key ( public_exponent = 65537 , key_size = 4096 , backend = default_backend ( ) )
return Key ( privateKey ) . toString ( 'openssh' ) |
def _get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ Any ] , logger : Logger ) -> Dict [ str , Any ] :
"""Simply inspects the required type to find the base type expected for items of the collection ,
and relies on the ParserFinder to find the parsing plan
: ... | # nb of file children
n_children = len ( obj_on_fs . get_multifile_children ( ) )
# first extract base collection type
subtypes , key_type = _extract_collection_base_type ( desired_type )
if isinstance ( subtypes , tuple ) : # - - check the tuple length
if n_children != len ( subtypes ) :
raise FolderAndFil... |
def _force_joinall_to_use_set ( self , node ) :
"""This detect usages of the form :
> > > from gevent import joinall
> > > joinall ( . . . )
or :
> > > import gevent
> > > gevent . joinall ( . . . )""" | for inferred_func in node . func . infer ( ) :
if is_joinall ( inferred_func ) :
is_every_value_a_set = all ( inferred_first_arg . pytype ( ) == 'builtins.set' for inferred_first_arg in node . args [ 0 ] . infer ( ) )
if not is_every_value_a_set :
self . add_message ( JOINALL_ID , node =... |
def det_n ( x ) :
'''given N matrices , return N determinants''' | assert x . ndim == 3
assert x . shape [ 1 ] == x . shape [ 2 ]
if x . shape [ 1 ] == 1 :
return x [ : , 0 , 0 ]
result = np . zeros ( x . shape [ 0 ] )
for permutation in permutations ( np . arange ( x . shape [ 1 ] ) ) :
sign = parity ( permutation )
result += np . prod ( [ x [ : , i , permutation [ i ] ] ... |
def _batch_to_stdin ( process , in_record_sep , in_column_sep , in_batches , batch_to_file_s ) :
"""Write in - batch contents to ` process ` ' s stdin ( if necessary )""" | for i , b2f in enumerate ( batch_to_file_s ) :
if b2f . is_stdin ( ) :
input_str = BaseShellOperator . _input_str ( in_batches [ i ] , in_record_sep , in_column_sep )
b2f . write_stdin ( process . stdin , input_str )
break |
def _check ( self ) :
"""Check that spectrum has legal combination of attributes .""" | # Run the super method
super ( Spectrum , self ) . _check ( )
err_str = None
has_data = self . _KEYS . DATA in self
has_wave = self . _KEYS . WAVELENGTHS in self
has_flux = self . _KEYS . FLUXES in self
has_filename = self . _KEYS . FILENAME in self
if not has_data :
if ( not has_wave or not has_flux ) and not has_... |
def _align_hydrogen_atoms ( mol1 , mol2 , heavy_indices1 , heavy_indices2 ) :
"""Align the label of topologically identical atoms of second molecule
towards first molecule
Args :
mol1 : First molecule . OpenBabel OBMol object
mol2 : Second molecule . OpenBabel OBMol object
heavy _ indices1 : inchi label m... | num_atoms = mol2 . NumAtoms ( )
all_atom = set ( range ( 1 , num_atoms + 1 ) )
hydrogen_atoms1 = all_atom - set ( heavy_indices1 )
hydrogen_atoms2 = all_atom - set ( heavy_indices2 )
label1 = heavy_indices1 + tuple ( hydrogen_atoms1 )
label2 = heavy_indices2 + tuple ( hydrogen_atoms2 )
cmol1 = ob . OBMol ( )
for i in l... |
def reqfile ( filepath ) :
"""Turns a text file into a list ( one element per line )""" | result = [ ]
import re
url_re = re . compile ( ".+:.+#egg=(.+)" )
with open ( filepath , "r" ) as f :
for line in f :
line = line . strip ( )
if not line or line . startswith ( "#" ) :
continue
mo = url_re . match ( line )
if mo is not None :
line = mo . group... |
def list_workspace_configs ( namespace , workspace , allRepos = False ) :
"""List method configurations in workspace .
Args :
namespace ( str ) : project to which workspace belongs
workspace ( str ) : Workspace name
Swagger :
https : / / api . firecloud . org / # ! / Method _ Configurations / listWorkspac... | uri = "workspaces/{0}/{1}/methodconfigs" . format ( namespace , workspace )
return __get ( uri , params = { 'allRepos' : allRepos } ) |
def extensionResponse ( self , namespace_uri , require_signed ) :
"""Return response arguments in the specified namespace .
@ param namespace _ uri : The namespace URI of the arguments to be
returned .
@ param require _ signed : True if the arguments should be among
those signed in the response , False if y... | if require_signed :
return self . getSignedNS ( namespace_uri )
else :
return self . message . getArgs ( namespace_uri ) |
def unregister ( self , name : str ) :
'''Unregister hook .''' | del self . _callbacks [ name ]
if self . _event_dispatcher is not None :
self . _event_dispatcher . unregister ( name ) |
def compute_trajectories ( self ) :
"""Compute the N trajectories that constitute the current genealogy .
Compute and add attribute ` ` B ` ` to ` ` self ` ` where ` ` B ` ` is an array
such that ` ` B [ t , n ] ` ` is the index of ancestor at time t of particle X _ T ^ n ,
where T is the current length of hi... | self . B = np . empty ( ( self . T , self . N ) , 'int' )
self . B [ - 1 , : ] = self . A [ - 1 ]
for t in reversed ( range ( self . T - 1 ) ) :
self . B [ t , : ] = self . A [ t + 1 ] [ self . B [ t + 1 ] ] |
def _get_files ( self ) :
"""Walk the project directory for tests and returns a list .
: return : list""" | excludes = [ '.git' , '.tox' , '.vagrant' , '.venv' , os . path . basename ( self . _config . verifier . directory ) , ]
generators = [ util . os_walk ( self . _config . project_directory , '*.yml' , excludes ) , util . os_walk ( self . _config . project_directory , '*.yaml' , excludes ) , ]
return [ f for g in generat... |
def gen_rows_from_csv_binfiles ( csv_files : Iterable [ BinaryIO ] , encoding : str = UTF8 , skip_header : bool = False , ** csv_reader_kwargs ) -> Generator [ Iterable [ str ] , None , None ] :
"""Iterate through binary file - like objects that are CSV files in a specified
encoding . Yield each row .
Args :
... | dialect = csv_reader_kwargs . pop ( 'dialect' , None )
for csv_file_bin in csv_files : # noinspection PyTypeChecker
csv_file = io . TextIOWrapper ( csv_file_bin , encoding = encoding )
thisfile_dialect = dialect
if thisfile_dialect is None :
thisfile_dialect = csv . Sniffer ( ) . sniff ( csv_file . ... |
def touch_project ( ) :
"""Touches the project to trigger refreshing its cauldron . json state .""" | r = Response ( )
project = cd . project . get_internal_project ( )
if project :
project . refresh ( )
else :
r . fail ( code = 'NO_PROJECT' , message = 'No open project to refresh' )
return r . update ( sync_time = sync_status . get ( 'time' , 0 ) ) . flask_serialize ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.