signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def add_response_headers ( headers ) :
"""Add headers passed in to the response
Usage :
. . code : : py
@ app . route ( ' / ' )
@ add _ response _ headers ( { ' X - Robots - Tag ' : ' noindex ' } )
def not _ indexed ( ) :
# This will set ` ` X - Robots - Tag : noindex ` ` in the response headers
retur... | def decorator ( func ) :
@ wraps ( func )
def _ ( * args , ** kwargs ) :
rsp = make_response ( func ( * args , ** kwargs ) )
rsp_headers = rsp . headers
for header , value in headers . items ( ) :
rsp_headers [ header ] = value
return rsp
return _
return decorator |
def validate_env ( self , envname ) :
"""Check the name of the environment against the black list and the
whitelist . If a whitelist is specified only it is checked .""" | if self . whitelist_envs and envname in self . whitelist_envs :
return True
elif self . whitelist_envs :
return False
if self . blacklist_envs and envname not in self . blacklist_envs :
return True
elif self . blacklist_envs : # If there is just a True , all envs are blacklisted
return False
else :
... |
def read_tlv ( data ) :
"""Parse TLV8 bytes into a dict .
If value is larger than 255 bytes , it is split up in multiple chunks . So
the same tag might occurr several times .""" | def _parse ( data , pos , size , result = None ) :
if result is None :
result = { }
if pos >= size :
return result
tag = str ( data [ pos ] )
length = data [ pos + 1 ]
value = data [ pos + 2 : pos + 2 + length ]
if tag in result :
result [ tag ] += value
# value >... |
def copy ( self ) :
'''Returns a copy of this query .''' | if self . object_getattr is Query . object_getattr :
other = Query ( self . key )
else :
other = Query ( self . key , object_getattr = self . object_getattr )
other . limit = self . limit
other . offset = self . offset
other . offset_key = self . offset_key
other . filters = self . filters
other . orders = self... |
def make_application ( debug = None , apps_dir = 'apps' , project_dir = None , include_apps = None , debug_console = True , settings_file = None , local_settings_file = None , start = True , default_settings = None , dispatcher_cls = None , dispatcher_kwargs = None , debug_cls = None , debug_kwargs = None , reuse = Tru... | from uliweb . utils . common import import_attr
from uliweb . utils . whocallme import print_frame
from werkzeug . debug import DebuggedApplication
# is reuse , then create application only one
if reuse and hasattr ( SimpleFrame . __global__ , 'application' ) and SimpleFrame . __global__ . application :
return Simp... |
def user_lookup ( self , ids , id_type = "user_id" ) :
"""A generator that returns users for supplied user ids , screen _ names ,
or an iterator of user _ ids of either . Use the id _ type to indicate
which you are supplying ( user _ id or screen _ name )""" | if id_type not in [ 'user_id' , 'screen_name' ] :
raise RuntimeError ( "id_type must be user_id or screen_name" )
if not isinstance ( ids , types . GeneratorType ) :
ids = iter ( ids )
# TODO : this is similar to hydrate , maybe they could share code ?
lookup_ids = [ ]
def do_lookup ( ) :
ids_str = "," . jo... |
def ParseAgeSpecification ( cls , age ) :
"""Parses an aff4 age and returns a datastore age specification .""" | try :
return ( 0 , int ( age ) )
except ( ValueError , TypeError ) :
pass
if age == NEWEST_TIME :
return data_store . DB . NEWEST_TIMESTAMP
elif age == ALL_TIMES :
return data_store . DB . ALL_TIMESTAMPS
elif len ( age ) == 2 :
start , end = age
return ( int ( start ) , int ( end ) )
raise Value... |
def create ( self , asset_versions = values . unset , function_versions = values . unset , dependencies = values . unset ) :
"""Create a new BuildInstance
: param unicode asset _ versions : The asset _ versions
: param unicode function _ versions : The function _ versions
: param unicode dependencies : The de... | data = values . of ( { 'AssetVersions' : serialize . map ( asset_versions , lambda e : e ) , 'FunctionVersions' : serialize . map ( function_versions , lambda e : e ) , 'Dependencies' : dependencies , } )
payload = self . _version . create ( 'POST' , self . _uri , data = data , )
return BuildInstance ( self . _version ... |
def _check_cooling_parameters ( radiuscooling , scalecooling ) :
"""Helper function to verify the cooling parameters of the training .""" | if radiuscooling != "linear" and radiuscooling != "exponential" :
raise Exception ( "Invalid parameter for radiuscooling: " + radiuscooling )
if scalecooling != "linear" and scalecooling != "exponential" :
raise Exception ( "Invalid parameter for scalecooling: " + scalecooling ) |
def write_exon_children ( self , db , exon_id ) :
"""Write out the children records of the exon given by
the ID ( not including the exon record itself ) .""" | exon_children = db . children ( exon_id , order_by = 'start' )
for exon_child in exon_children :
self . write_rec ( exon_child ) |
def _delete_record ( self , identifier = None , rtype = None , name = None , content = None ) :
"""Delete record ( s ) matching the provided params . If there is no match , do
nothing .""" | ids = [ ]
if identifier :
ids . append ( identifier )
elif not identifier and rtype and name :
records = self . _list_records ( rtype , name , content )
if records :
ids = [ record [ "id" ] for record in records ]
if ids :
LOGGER . debug ( "delete_records: %s" , ids )
with localzone . manage... |
def set_verified ( self , msg_info ) :
"""expects " msg _ info " to have the field ' files _ containers _ id '
This call already executes " update _ last _ checked _ time " so it doesn ' t need to be called separately""" | assert hasattr ( msg_info , 'files_containers_id' )
with self . _session_resource as session :
session . execute ( update ( FilesDestinations ) . where ( FilesDestinations . file_containers_id == msg_info . files_containers_id ) . values ( verification_info = msg_info . msg_id ) )
self . update_last_checked_time ( ... |
def done ( self ) :
"""Check if we should stop returning objects""" | if self . _done :
return self . _done
if self . _limit is None :
self . _done = False
elif self . itemcount >= self . _limit :
self . _done = True
return self . _done |
def need_deployment ( ) :
'''Salt thin needs to be deployed - prep the target directory and emit the
delimiter and exit code that signals a required deployment .''' | if os . path . exists ( OPTIONS . saltdir ) :
shutil . rmtree ( OPTIONS . saltdir )
old_umask = os . umask ( 0o077 )
# pylint : disable = blacklisted - function
try :
os . makedirs ( OPTIONS . saltdir )
finally :
os . umask ( old_umask )
# pylint : disable = blacklisted - function
# Verify perms on salt... |
def model_counts_spectrum ( self , name , logemin , logemax , weighted = False ) :
"""Return the model counts spectrum of a source .
Parameters
name : str
Source name .""" | # EAC , we need this b / c older version of the ST don ' t have the right signature
try :
cs = np . array ( self . like . logLike . modelCountsSpectrum ( str ( name ) , weighted ) )
except ( TypeError , NotImplementedError ) :
cs = np . array ( self . like . logLike . modelCountsSpectrum ( str ( name ) ) )
imin... |
def all ( self , components_in_and = True ) :
'''Return all of the results of a query in a list''' | self . components_in_and = components_in_and
return [ obj for obj in iter ( self ) ] |
def _replace ( self , data , replacements ) :
"""Given a list of 2 - tuples ( find , repl ) this function performs all
replacements on the input and returns the result .""" | for find , repl in replacements :
data = data . replace ( find , repl )
return data |
def handle_finish ( self , obj ) :
"""Handle an incoming ` ` Data ` ` finished processing request .
: param obj : The Channels message object . Command object format :
. . code - block : : none
' command ' : ' finish ' ,
' data _ id ' : [ id of the : class : ` ~ resolwe . flow . models . Data ` object
thi... | data_id = obj [ ExecutorProtocol . DATA_ID ]
logger . debug ( __ ( "Finishing Data with id {} (handle_finish)." , data_id ) , extra = { 'data_id' : data_id , 'packet' : obj } )
spawning_failed = False
with transaction . atomic ( ) : # Spawn any new jobs in the request .
spawned = False
if ExecutorProtocol . FIN... |
def project_create_event ( self , proj_info ) :
"""Create project .""" | LOG . debug ( "Processing create %(proj)s event." , { 'proj' : proj_info } )
proj_id = proj_info . get ( 'resource_info' )
self . project_create_func ( proj_id ) |
def reading ( self , service ) :
"""get the data from the service and put theme in cache
: param service : service object to read
: type service : object""" | # counting the new data to store to display them in the log provider - the service that offer data
provider_token = service . provider . token
default_provider . load_services ( )
service_provider = default_provider . get_service ( str ( service . provider . name . name ) )
date_triggered = service . date_triggered if ... |
def answer ( self , signatory ) :
"""Respond to this request .
Given a L { Signatory } , I can check the validity of the signature and
the X { C { invalidate _ handle } } .
@ param signatory : The L { Signatory } to use to check the signature .
@ type signatory : L { Signatory }
@ returns : A response wit... | is_valid = signatory . verify ( self . assoc_handle , self . signed )
# Now invalidate that assoc _ handle so it this checkAuth message cannot
# be replayed .
signatory . invalidate ( self . assoc_handle , dumb = True )
response = OpenIDResponse ( self )
valid_str = ( is_valid and "true" ) or "false"
response . fields ... |
def loglevel ( level ) :
"""Convert any representation of ` level ` to an int appropriately .
: type level : int or str
: rtype : int
> > > loglevel ( ' DEBUG ' ) = = logging . DEBUG
True
> > > loglevel ( 10)
10
> > > loglevel ( None )
Traceback ( most recent call last ) :
ValueError : None is not... | if isinstance ( level , str ) :
level = getattr ( logging , level . upper ( ) )
elif isinstance ( level , int ) :
pass
else :
raise ValueError ( '{0!r} is not a proper log level.' . format ( level ) )
return level |
def raw_imu_send ( self , time_usec , xacc , yacc , zacc , xgyro , ygyro , zgyro , xmag , ymag , zmag , force_mavlink1 = False ) :
'''The RAW IMU readings for the usual 9DOF sensor setup . This message
should always contain the true raw values without any
scaling to allow data capture and system debugging .
t... | return self . send ( self . raw_imu_encode ( time_usec , xacc , yacc , zacc , xgyro , ygyro , zgyro , xmag , ymag , zmag ) , force_mavlink1 = force_mavlink1 ) |
def get_accept_list ( self , request ) :
"""Given the incoming request , return a tokenised list of media
type strings .""" | header = request . META . get ( 'HTTP_ACCEPT' , '*/*' )
return [ token . strip ( ) for token in header . split ( ',' ) ] |
def reverse_sequences ( records ) :
"""Reverse the order of sites in sequences .""" | logging . info ( 'Applying _reverse_sequences generator: ' 'reversing the order of sites in sequences.' )
for record in records :
rev_record = SeqRecord ( record . seq [ : : - 1 ] , id = record . id , name = record . name , description = record . description )
# Copy the annotations over
_reverse_annotation... |
def parse_components ( text , field_datatype = 'ST' , version = None , encoding_chars = None , validation_level = None , references = None ) :
"""Parse the given ER7 - encoded components and return a list of : class : ` Component < hl7apy . core . Component > `
instances .
: type text : ` ` str ` `
: param te... | version = _get_version ( version )
encoding_chars = _get_encoding_chars ( encoding_chars , version )
validation_level = _get_validation_level ( validation_level )
component_sep = encoding_chars [ 'COMPONENT' ]
components = [ ]
for index , component in enumerate ( text . split ( component_sep ) ) :
if is_base_dataty... |
def _construct_instance ( cls , values ) :
"""method used to construct instances from query results
this is where polymorphic deserialization occurs""" | # we ' re going to take the values , which is from the DB as a dict
# and translate that into our local fields
# the db _ map is a db _ field - > model field map
if cls . _db_map :
values = dict ( ( cls . _db_map . get ( k , k ) , v ) for k , v in values . items ( ) )
if cls . _is_polymorphic :
disc_key = value... |
def repo_id ( self , repo : str ) -> str :
"""Returns an unique identifier from a repo URL for the folder the repo is gonna be pulled in .""" | if repo . startswith ( "http" ) :
repo_id = re . sub ( r"https?://(.www)?" , "" , repo )
repo_id = re . sub ( r"\.git/?$" , "" , repo_id )
else :
repo_id = repo . replace ( "file://" , "" )
repo_id = re . sub ( r"\.git/?$" , "" , repo_id )
if repo_id . startswith ( "~" ) :
repo_id = str ( Pa... |
def setControl ( self , request_type , request , value , index , buffer_or_len , callback = None , user_data = None , timeout = 0 ) :
"""Setup transfer for control use .
request _ type , request , value , index
See USBDeviceHandle . controlWrite .
request _ type defines transfer direction ( see
ENDPOINT _ O... | if self . __submitted :
raise ValueError ( 'Cannot alter a submitted transfer' )
if self . __doomed :
raise DoomedTransferError ( 'Cannot reuse a doomed transfer' )
if isinstance ( buffer_or_len , ( int , long ) ) :
length = buffer_or_len
# pylint : disable = undefined - variable
string_buffer , tra... |
def is_relative ( modname , from_file ) :
"""return true if the given module name is relative to the given
file name
: type modname : str
: param modname : name of the module we are interested in
: type from _ file : str
: param from _ file :
path of the module from which modname has been imported
: r... | if not os . path . isdir ( from_file ) :
from_file = os . path . dirname ( from_file )
if from_file in sys . path :
return False
try :
stream , _ , _ = imp . find_module ( modname . split ( "." ) [ 0 ] , [ from_file ] )
# Close the stream to avoid ResourceWarnings .
if stream :
stream . clos... |
def Jobs ( ) :
"""Get the number of jobs that are running and finished , and the number of
total tools running and finished for those jobs""" | jobs = [ 0 , 0 , 0 , 0 ]
# get running jobs
try :
d_client = docker . from_env ( )
c = d_client . containers . list ( all = False , filters = { 'label' : 'vent-plugin' } )
files = [ ]
for container in c :
jobs [ 1 ] += 1
if 'file' in container . attrs [ 'Config' ] [ 'Labels' ] :
... |
def rst_to_pypi ( contents ) :
"""Convert the given GitHub RST contents to PyPi RST contents ( since some RST directives are not available in PyPi ) .
Args :
contents ( str ) : The GitHub compatible RST contents .
Returns :
str : The PyPi compatible RST contents .""" | # The PyPi description does not support the SVG file type .
contents = contents . replace ( ".svg?pypi=png.from.svg" , ".png" )
# Convert ` ` < br class = " title " > ` ` to a H1 title
asterisks_length = len ( PackageHelper . get_name ( ) )
asterisks = "*" * asterisks_length
title = asterisks + "\n" + PackageHelper . g... |
def build_journals_re_kb ( fpath ) :
"""Load journals regexps knowledge base
@ see build _ journals _ kb""" | def make_tuple ( match ) :
regexp = match . group ( 'seek' )
repl = match . group ( 'repl' )
return regexp , repl
kb = [ ]
with file_resolving ( fpath ) as fh :
for rawline in fh :
if rawline . startswith ( '#' ) :
continue
# Extract the seek - > replace terms from this KB li... |
def del_node ( self , char , node ) :
"""Remove a node from a character .""" | del self . _real . character [ char ] . node [ node ]
for cache in ( self . _char_nodes_rulebooks_cache , self . _node_stat_cache , self . _node_successors_cache ) :
try :
del cache [ char ] [ node ]
except KeyError :
pass
if char in self . _char_nodes_cache and node in self . _char_nodes_cache ... |
def prompt_for_project ( ctx , entity ) :
"""Ask the user for a project , creating one if necessary .""" | result = ctx . invoke ( projects , entity = entity , display = False )
try :
if len ( result ) == 0 :
project = click . prompt ( "Enter a name for your first project" )
# description = editor ( )
project = api . upsert_project ( project , entity = entity ) [ "name" ]
else :
proje... |
def decode ( value : str ) -> Union [ str , None , bool , int , float ] :
"""Decode encoded credential attribute value .
: param value : numeric string to decode
: return : decoded value , stringified if original was neither str , bool , int , nor float""" | assert value . isdigit ( ) or value [ 0 ] == '-' and value [ 1 : ] . isdigit ( )
if - I32_BOUND <= int ( value ) < I32_BOUND : # it ' s an i32 : it is its own encoding
return int ( value )
elif int ( value ) == I32_BOUND :
return None
( prefix , value ) = ( int ( value [ 0 ] ) , int ( value [ 1 : ] ) )
ival = i... |
def to_python ( self , value ) :
"""Strips any dodgy HTML tags from the input""" | if value in self . empty_values :
try :
return self . empty_value
except AttributeError : # CharField . empty _ value was introduced in Django 1.11 ; in prior
# versions a unicode string was returned for empty values in
# all cases .
return u''
return bleach . clean ( value , ** self . b... |
def fit ( self , X , y = None ) :
"""Determine the categorical columns to be dummy encoded .
Parameters
X : pandas . DataFrame or dask . dataframe . DataFrame
y : ignored
Returns
self""" | self . columns_ = X . columns
columns = self . columns
if columns is None :
columns = X . select_dtypes ( include = [ "category" ] ) . columns
else :
for column in columns :
assert is_categorical_dtype ( X [ column ] ) , "Must be categorical"
self . categorical_columns_ = columns
self . non_categorical_... |
def save ( self , commit = True ) :
"""Save model to database""" | db . session . add ( self )
if commit :
db . session . commit ( )
return self |
def batch ( byte_array , funcs ) :
"""Converts a batch to a list of values .
: param byte _ array : a byte array of length n * item _ length + 8
: return : a list of uuid objects""" | result = [ ]
length = bytes_to_int ( byte_array [ 0 : 4 ] )
item_size = bytes_to_int ( byte_array [ 4 : 8 ] )
for i in range ( 0 , length ) :
chunk = byte_array [ 8 + i * item_size : 8 + ( i + 1 ) * item_size ]
for f in funcs :
f ( chunk )
return result |
def password ( name , default = None ) :
"""Grabs hidden ( password ) input from command line .
: param name : prompt text
: param default : default value if no input provided .""" | prompt = name + ( default and ' [%s]' % default or '' )
prompt += name . endswith ( '?' ) and ' ' or ': '
while True :
rv = getpass . getpass ( prompt )
if rv :
return rv
if default is not None :
return default |
def read ( self , num_bytes = None ) :
"""Read and return the specified bytes from the buffer .""" | res = self . get_next ( num_bytes )
self . skip ( len ( res ) )
return res |
def _at_dump_options ( self , calculator , rule , scope , block ) :
"""Implements @ dump _ options""" | sys . stderr . write ( "%s\n" % repr ( rule . options ) ) |
def build_wxsfile ( target , source , env ) :
"""Compiles a . wxs file from the keywords given in env [ ' msi _ spec ' ] and
by analyzing the tree of source nodes and their tags .""" | file = open ( target [ 0 ] . get_abspath ( ) , 'w' )
try : # Create a document with the Wix root tag
doc = Document ( )
root = doc . createElement ( 'Wix' )
root . attributes [ 'xmlns' ] = 'http://schemas.microsoft.com/wix/2003/01/wi'
doc . appendChild ( root )
filename_set = [ ]
# this is to ci... |
def fill ( h1 : Histogram1D , ax : Axes , ** kwargs ) :
"""Fill plot of 1D histogram .""" | show_stats = kwargs . pop ( "show_stats" , False )
# show _ values = kwargs . pop ( " show _ values " , False )
density = kwargs . pop ( "density" , False )
cumulative = kwargs . pop ( "cumulative" , False )
kwargs [ "label" ] = kwargs . get ( "label" , h1 . name )
data = get_data ( h1 , cumulative = cumulative , densi... |
def eval_master_func ( opts ) :
'''Evaluate master function if master type is ' func '
and save it result in opts [ ' master ' ]''' | if '__master_func_evaluated' not in opts : # split module and function and try loading the module
mod_fun = opts [ 'master' ]
mod , fun = mod_fun . split ( '.' )
try :
master_mod = salt . loader . raw_mod ( opts , mod , fun )
if not master_mod :
raise KeyError
# we take w... |
def due ( self ) :
"""The amount due for this invoice . Takes into account all entities in the invoice .
Can be < 0 if the invoice was overpaid .""" | invoice_charges = Charge . objects . filter ( invoice = self )
invoice_transactions = Transaction . successful . filter ( invoice = self )
return total_amount ( invoice_charges ) - total_amount ( invoice_transactions ) |
def get_list_connections ( self , environment , product , unique_name_list = None , is_except = False ) :
"""Gets list of connections that satisfy the filter by environment , product and ( optionally ) unique DB names
: param environment : Environment name
: param product : Product name
: param unique _ name ... | return_list = [ ]
for item in self . connection_sets :
if unique_name_list :
if item [ 'unique_name' ] :
if is_except :
if item [ 'environment' ] == environment and item [ 'product' ] == product and ( item [ 'unique_name' ] not in unique_name_list ) :
return_l... |
def read_frame ( self ) :
"""Reads a frame and converts the color if needed .
In case no frame is available , i . e . self . capture . read ( ) returns False
as the first return value , the event _ source of the TimedAnimation is
stopped , and if possible the capture source released .
Returns :
None if st... | ret , frame = self . capture . read ( )
if not ret :
self . event_source . stop ( )
try :
self . capture . release ( )
except AttributeError : # has no release method , thus just pass
pass
return None
if self . convert_color != - 1 and is_color_image ( frame ) :
return cv2 . cvtColor... |
def render ( self , ** kwargs ) :
"""Renders the HTML representation of the element .""" | return self . _template . render ( this = self , kwargs = kwargs ) |
def get ( key , default = None ) :
'''Get a ( list of ) value ( s ) from the minion datastore
. . versionadded : : 2015.8.0
CLI Example :
. . code - block : : bash
salt ' * ' data . get key
salt ' * ' data . get ' [ " key1 " , " key2 " ] ' ''' | store = load ( )
if isinstance ( key , six . string_types ) :
return store . get ( key , default )
elif default is None :
return [ store [ k ] for k in key if k in store ]
else :
return [ store . get ( k , default ) for k in key ] |
def determine_plasma_store_config ( object_store_memory = None , plasma_directory = None , huge_pages = False ) :
"""Figure out how to configure the plasma object store .
This will determine which directory to use for the plasma store ( e . g . ,
/ tmp or / dev / shm ) and how much memory to start the store wit... | system_memory = ray . utils . get_system_memory ( )
# Choose a default object store size .
if object_store_memory is None :
object_store_memory = int ( system_memory * 0.3 )
# Cap memory to avoid memory waste and perf issues on large nodes
if ( object_store_memory > ray_constants . DEFAULT_OBJECT_STORE_MAX_... |
def find_problems ( cls ) :
"""Checks for problems in the tree structure , problems can occur when :
1 . your code breaks and you get incomplete transactions ( always
use transactions ! )
2 . changing the ` ` steplen ` ` value in a model ( you must
: meth : ` dump _ bulk ` first , change ` ` steplen ` ` and... | cls = get_result_class ( cls )
vendor = cls . get_database_vendor ( 'write' )
evil_chars , bad_steplen , orphans = [ ] , [ ] , [ ]
wrong_depth , wrong_numchild = [ ] , [ ]
for node in cls . objects . all ( ) :
found_error = False
for char in node . path :
if char not in cls . alphabet :
evil... |
def msg2subjective ( msg , processor , subject , ** config ) :
"""Return a human - readable text representation of a dict - like
fedmsg message from the subjective perspective of a user .
For example , if the subject viewing the message is " oddshocks "
and the message would normally translate into " oddshock... | text = processor . subjective ( msg , subject , ** config )
if not text :
text = processor . subtitle ( msg , ** config )
return text |
def get_nameid_format ( self ) :
"""Gets the NameID Format provided by the SAML Response from the IdP
: returns : NameID Format
: rtype : string | None""" | nameid_format = None
nameid_data = self . get_nameid_data ( )
if nameid_data and 'Format' in nameid_data . keys ( ) :
nameid_format = nameid_data [ 'Format' ]
return nameid_format |
async def filter_commands ( self , commands , * , sort = False , key = None ) :
"""| coro |
Returns a filtered list of commands and optionally sorts them .
This takes into account the : attr : ` verify _ checks ` and : attr : ` show _ hidden `
attributes .
Parameters
commands : Iterable [ : class : ` Comm... | if sort and key is None :
key = lambda c : c . name
iterator = commands if self . show_hidden else filter ( lambda c : not c . hidden , commands )
if not self . verify_checks : # if we do not need to verify the checks then we can just
# run it straight through normally without using await .
return sorted ( iter... |
def main ( arguments = None ) :
"""The main function used when ` ` yaml _ to _ database . py ` ` when installed as a cl tool""" | # setup the command - line util settings
su = tools ( arguments = arguments , docString = __doc__ , logLevel = "WARNING" , options_first = False , projectName = False )
arguments , settings , log , dbConn = su . setup ( )
# unpack remaining cl arguments using ` exec ` to setup the variable names
# automatically
for arg... |
def decode ( self , encoded ) :
"""Decodes a tensor into a sequence .
Args :
encoded ( torch . Tensor ) : Encoded sequence .
Returns :
str : Sequence decoded from ` ` encoded ` ` .""" | encoded = super ( ) . decode ( encoded )
return self . tokenizer . decode ( [ self . itos [ index ] for index in encoded ] ) |
def extract_public_key ( args ) :
"""Load an ECDSA private key and extract the embedded public key as raw binary data .""" | sk = _load_ecdsa_signing_key ( args )
vk = sk . get_verifying_key ( )
args . public_keyfile . write ( vk . to_string ( ) )
print ( "%s public key extracted to %s" % ( args . keyfile . name , args . public_keyfile . name ) ) |
def get_unique_connection_configs ( config = None ) :
"""Returns a list of unique Redis connections from config""" | if config is None :
from . settings import QUEUES
config = QUEUES
connection_configs = [ ]
for key , value in config . items ( ) :
value = filter_connection_params ( value )
if value not in connection_configs :
connection_configs . append ( value )
return connection_configs |
def nonce ( ) :
"""Returns a new nonce to be used with the Piazza API .""" | nonce_part1 = _int2base ( int ( _time ( ) * 1000 ) , 36 )
nonce_part2 = _int2base ( round ( _random ( ) * 1679616 ) , 36 )
return "{}{}" . format ( nonce_part1 , nonce_part2 ) |
def convert_to_ns ( self , value ) :
'''converts a value to the prefixed rdf ns equivalent . If not found
returns the value as is
args :
value : the value to convert''' | parsed = self . parse_uri ( value )
try :
rtn_val = "%s_%s" % ( self . uri_dict [ parsed [ 0 ] ] , parsed [ 1 ] )
except KeyError :
rtn_val = self . pyhttp ( value )
return rtn_val |
def Stop ( self , join_timeout = 600 ) :
"""This stops all the worker threads .""" | if not self . started :
logging . warning ( "Tried to stop a thread pool that was not running." )
return
# Remove all workers from the pool .
workers = list ( itervalues ( self . _workers ) )
self . _workers = { }
self . _workers_ro_copy = { }
# Send a stop message to all the workers . We need to be careful her... |
def _prep_clients ( self , clients ) :
"""Prep a client by tagging it with and id and wrapping methods .
Methods are wrapper to catch ConnectionError so that we can remove
it from the pool until the instance comes back up .
: returns : patched clients""" | for pool_id , client in enumerate ( clients ) : # Tag it with an id we ' ll use to identify it in the pool
if hasattr ( client , "pool_id" ) :
raise ValueError ( "%r is already part of a pool." , client )
setattr ( client , "pool_id" , pool_id )
# Wrap all public functions
self . _wrap_functions... |
def to_graphml ( graph : BELGraph , path : Union [ str , BinaryIO ] ) -> None :
"""Write this graph to GraphML XML file using : func : ` networkx . write _ graphml ` .
The . graphml file extension is suggested so Cytoscape can recognize it .""" | rv = nx . MultiDiGraph ( )
for node in graph :
rv . add_node ( node . as_bel ( ) , function = node . function )
for u , v , key , edge_data in graph . edges ( data = True , keys = True ) :
rv . add_edge ( u . as_bel ( ) , v . as_bel ( ) , interaction = edge_data [ RELATION ] , bel = graph . edge_to_bel ( u , v ... |
def fit_creatine ( self , reject_outliers = 3.0 , fit_lb = 2.7 , fit_ub = 3.5 ) :
"""Fit a model to the portion of the summed spectra containing the
creatine and choline signals .
Parameters
reject _ outliers : float or bool
If set to a float , this is the z score threshold for rejection ( on
any of the p... | # We fit a two - lorentz function to this entire chunk of the spectrum ,
# to catch both choline and creatine
model , signal , params = ana . fit_two_lorentzian ( self . sum_spectra , self . f_ppm , lb = fit_lb , ub = fit_ub )
# Use an array of ones to index everything but the outliers and nans :
ii = np . ones ( signa... |
def create_tag ( self , version , params ) :
"""Create VCS tag
: param version :
: param params :
: return :""" | cmd = self . _command . tag ( version , params )
( code , stdout , stderr ) = self . _exec ( cmd )
if code :
raise errors . VCSError ( 'Can\'t create VCS tag %s. Process exited with code %d and message: %s' % ( version , code , stderr or stdout ) ) |
def _create_vxr ( self , f , recStart , recEnd , currentVDR , priorVXR , vvrOffset ) :
'''Create a VXR AND use a VXR
Parameters :
f : file
The open CDF file
recStart : int
The start record of this block
recEnd : int
The ending record of this block
currentVDR : int
The byte location of the variable... | # add a VXR , use an entry , and link it to the prior VXR if it exists
vxroffset = self . _write_vxr ( f )
self . _use_vxrentry ( f , vxroffset , recStart , recEnd , vvrOffset )
if ( priorVXR == 0 ) : # VDR ' s VXRhead
self . _update_offset_value ( f , currentVDR + 28 , 8 , vxroffset )
else : # VXR ' s next
sel... |
def arducopter_arm ( self ) :
'''arm motors ( arducopter only )''' | if self . mavlink10 ( ) :
self . mav . command_long_send ( self . target_system , # target _ system
self . target_component , mavlink . MAV_CMD_COMPONENT_ARM_DISARM , # command
0 , # confirmation
1 , # param1 ( 1 to indicate arm )
0 , # param2 ( all other params meaningless )
0 , # param3
0 ... |
def _dispatch ( self , input_batch : List [ SingleQuery ] ) :
"""Helper method to dispatch a batch of input to self . serve _ method .""" | method = getattr ( self , self . serve_method )
if hasattr ( method , "ray_serve_batched_input" ) :
batch = [ inp . data for inp in input_batch ]
result = _execute_and_seal_error ( method , batch , self . serve_method )
for res , inp in zip ( result , input_batch ) :
ray . worker . global_worker . p... |
def add ( queue_name , payload = None , content_type = None , source = None , task_id = None , build_id = None , release_id = None , run_id = None ) :
"""Adds a work item to a queue .
Args :
queue _ name : Name of the queue to add the work item to .
payload : Optional . Payload that describes the work to do a... | if task_id :
task = WorkQueue . query . filter_by ( task_id = task_id ) . first ( )
if task :
return task . task_id
else :
task_id = uuid . uuid4 ( ) . hex
if payload and not content_type and not isinstance ( payload , basestring ) :
payload = json . dumps ( payload )
content_type = 'applica... |
def build ( self , filename , bytecode_compile = True ) :
"""Package the PEX into a zipfile .
: param filename : The filename where the PEX should be stored .
: param bytecode _ compile : If True , precompile . py files into . pyc files .
If the PEXBuilder is not yet frozen , it will be frozen by ` ` build ` ... | if not self . _frozen :
self . freeze ( bytecode_compile = bytecode_compile )
try :
os . unlink ( filename + '~' )
self . _logger . warn ( 'Previous binary unexpectedly exists, cleaning: %s' % ( filename + '~' ) )
except OSError : # The expectation is that the file does not exist , so continue
pass
if o... |
def add_data ( self , new_cols = None ) :
"""Adds a column with the requested data .
If you want to see for example the mass , the colormap used in
jmol and the block of the element , just use : :
[ ' mass ' , ' jmol _ color ' , ' block ' ]
The underlying ` ` pd . DataFrame ` ` can be accessed with
` ` co... | atoms = self [ 'atom' ]
data = constants . elements
if pd . api . types . is_list_like ( new_cols ) :
new_cols = set ( new_cols )
elif new_cols is None :
new_cols = set ( data . columns )
else :
new_cols = [ new_cols ]
new_frame = data . loc [ atoms , set ( new_cols ) - set ( self . columns ) ]
new_frame . ... |
def AsRegEx ( self ) :
"""Return the current glob as a simple regex .
Note : No interpolation is performed .
Returns :
A RegularExpression ( ) object .""" | parts = self . __class__ . REGEX_SPLIT_PATTERN . split ( self . _value )
result = u"" . join ( self . _ReplaceRegExPart ( p ) for p in parts )
return rdf_standard . RegularExpression ( u"(?i)\\A%s\\Z" % result ) |
def add_issue_status ( self , name , ** attrs ) :
"""Add a Issue status to the project and returns a
: class : ` IssueStatus ` object .
: param name : name of the : class : ` IssueStatus `
: param attrs : optional attributes for : class : ` IssueStatus `""" | return IssueStatuses ( self . requester ) . create ( self . id , name , ** attrs ) |
def find_unique_values ( input_file , property_name ) :
'''Find unique values of a given property in a geojson file .
Args
input _ file ( str ) : File name .
property _ name ( str ) : Property name .
Returns
List of distinct values of property . If property does not exist , it returns None .''' | with open ( input_file ) as f :
feature_collection = geojson . load ( f )
features = feature_collection [ 'features' ]
values = np . array ( [ feat [ 'properties' ] . get ( property_name ) for feat in features ] )
return np . unique ( values ) |
def ximshow_file ( singlefile , args_cbar_label = None , args_cbar_orientation = None , args_z1z2 = None , args_bbox = None , args_firstpix = None , args_keystitle = None , args_ds9reg = None , args_geometry = "0,0,640,480" , pdf = None , show = True , debugplot = None , using_jupyter = False ) :
"""Function to exe... | # read z1 , z2
if args_z1z2 is None :
z1z2 = None
elif args_z1z2 == "minmax" :
z1z2 = "minmax"
else :
tmp_str = args_z1z2 . split ( "," )
z1z2 = float ( tmp_str [ 0 ] ) , float ( tmp_str [ 1 ] )
# read geometry
if args_geometry is None :
geometry = None
else :
tmp_str = args_geometry . split ( "... |
def walk ( self , dag , walk_func ) :
"""Walks each node of the graph , in parallel if it can .
The walk _ func is only called when the nodes dependencies have been
satisfied""" | # First , we ' ll topologically sort all of the nodes , with nodes that
# have no dependencies first . We do this to ensure that we don ' t call
# . join on a thread that hasn ' t yet been started .
# TODO ( ejholmes ) : An alternative would be to ensure that Thread . join
# blocks if the thread has not yet been starte... |
def login ( access_code : str , client_id : str = CLIENT_ID , client_secret : str = CLIENT_SECRET , headers : dict = HEADERS , redirect_uri : str = REDIRECT_URI ) :
"""Get access _ token fron an user authorized code , the client id and the client secret key .
( See https : / / developer . google . com / v3 / oaut... | if not CLIENT_ID or not CLIENT_SECRET :
raise GoogleApiError ( { "error_message" : _ ( "Login with google account is disabled. Contact " "with the sysadmins. Maybe they're snoozing in a " "secret hideout of the data center." ) } )
url = _build_url ( "login" , "access-token" )
params = { "code" : access_code , "clie... |
def app_stop ( device_id , app_id ) :
"""stops an app with corresponding package name""" | if not is_valid_app_id ( app_id ) :
abort ( 403 )
if not is_valid_device_id ( device_id ) :
abort ( 403 )
if device_id not in devices :
abort ( 404 )
success = devices [ device_id ] . stop_app ( app_id )
return jsonify ( success = success ) |
def _get_rating ( self , entry ) :
"""Get the rating and share for a specific row""" | r_info = ''
for string in entry [ 2 ] . strings :
r_info += string
rating , share = r_info . split ( '/' )
return ( rating , share . strip ( '*' ) ) |
def code_constants ( self ) :
"""All of the constants that are used by this functions ' s code .""" | # TODO : remove link register values
return [ const . value for block in self . blocks for const in block . vex . constants ] |
def write_csvs ( dirname : PathLike , adata : AnnData , skip_data : bool = True , sep : str = ',' ) :
"""See : meth : ` ~ anndata . AnnData . write _ csvs ` .""" | dirname = Path ( dirname )
if dirname . suffix == '.csv' :
dirname = dirname . with_suffix ( '' )
logger . info ( "writing '.csv' files to %s" , dirname )
if not dirname . is_dir ( ) :
dirname . mkdir ( parents = True , exist_ok = True )
dir_uns = dirname / 'uns'
if not dir_uns . is_dir ( ) :
dir_uns . mkdi... |
def get_all_context_names ( context_num ) :
"""Based on the nucleotide base context number , return
a list of strings representing each context .
Parameters
context _ num : int
number representing the amount of nucleotide base context to use .
Returns
a list of strings containing the names of the base c... | if context_num == 0 :
return [ 'None' ]
elif context_num == 1 :
return [ 'A' , 'C' , 'T' , 'G' ]
elif context_num == 1.5 :
return [ 'C*pG' , 'CpG*' , 'TpC*' , 'G*pA' , 'A' , 'C' , 'T' , 'G' ]
elif context_num == 2 :
dinucs = list ( set ( [ d1 + d2 for d1 in 'ACTG' for d2 in 'ACTG' ] ) )
return dinuc... |
def get_content_string ( self ) :
"""Ge thet Clusterpoint response ' s content as a string .""" | return '' . join ( [ ET . tostring ( element , encoding = "utf-8" , method = "xml" ) for element in list ( self . _content ) ] ) |
def get_l ( self ) :
"""Get Galactic Longitude ( l ) corresponding to the current position
: return : Galactic Longitude""" | try :
return self . l . value
except AttributeError : # Transform from L , B to R . A . , Dec
return self . sky_coord . transform_to ( 'galactic' ) . l . value |
def optimize ( self , angles0 , target ) :
"""Calculate an optimum argument of an objective function .""" | def new_objective ( angles ) :
a = angles - angles0
if isinstance ( self . smooth_factor , ( np . ndarray , list ) ) :
if len ( a ) == len ( self . smooth_factor ) :
return ( self . f ( angles , target ) + np . sum ( self . smooth_factor * np . power ( a , 2 ) ) )
else :
... |
def declared_symbols ( self ) :
"""Return all local symbols here , and also of the parents""" | return self . local_declared_symbols | ( self . parent . declared_symbols if self . parent else set ( ) ) |
def refresh ( self ) :
"""Refresh an existing lock to prevent it from expiring .
Uses a LUA ( EVAL ) script to ensure only a lock which we own is being overwritten .
Returns True if refresh succeeded , False if not .""" | keys = [ self . name ]
args = [ self . value , self . timeout ]
# Redis docs claim EVALs are atomic , and I ' m inclined to believe it .
if hasattr ( self , '_refresh_script' ) :
return self . _refresh_script ( keys = keys , args = args ) == 1
else :
keys_and_args = keys + args
return self . redis . eval ( ... |
def camel_to_title ( name ) :
"""Takes a camelCaseFieldName and returns an Title Case Field Name
Args :
name ( str ) : E . g . camelCaseFieldName
Returns :
str : Title Case converted name . E . g . Camel Case Field Name""" | split = re . findall ( r"[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)" , name )
ret = " " . join ( split )
ret = ret [ 0 ] . upper ( ) + ret [ 1 : ]
return ret |
def handle_event ( self , package ) :
'''Handle an event from the epull _ sock ( all local minion events )''' | if not self . ready :
raise tornado . gen . Return ( )
tag , data = salt . utils . event . SaltEvent . unpack ( package )
log . debug ( 'Minion of \'%s\' is handling event tag \'%s\'' , self . opts [ 'master' ] , tag )
tag_functions = { 'beacons_refresh' : self . _handle_tag_beacons_refresh , 'environ_setenv' : sel... |
def multi ( children , quiet_exceptions = ( ) ) :
"""Runs multiple asynchronous operations in parallel .
` ` children ` ` may either be a list or a dict whose values are
yieldable objects . ` ` multi ( ) ` ` returns a new yieldable
object that resolves to a parallel structure containing their
results . If `... | if _contains_yieldpoint ( children ) :
return MultiYieldPoint ( children , quiet_exceptions = quiet_exceptions )
else :
return multi_future ( children , quiet_exceptions = quiet_exceptions ) |
def udf_signature ( input_type , pin , klass ) :
"""Compute the appropriate signature for a
: class : ` ~ ibis . expr . operations . Node ` from a list of input types
` input _ type ` .
Parameters
input _ type : List [ ibis . expr . datatypes . DataType ]
A list of : class : ` ~ ibis . expr . datatypes . ... | nargs = len ( input_type )
if not nargs :
return ( )
if nargs == 1 :
r , = input_type
result = ( klass , ) + rule_to_python_type ( r ) + nullable ( r )
return ( result , )
return tuple ( klass if pin is not None and pin == i else ( ( klass , ) + rule_to_python_type ( r ) + nullable ( r ) ) for i , r in ... |
def ExtractEvents ( self , parser_mediator , registry_key , ** kwargs ) :
"""Extracts events from a Windows Registry key .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
registry _ key ( dfwinreg . WinRegistryKey ) : Win... | version_value = registry_key . GetValueByName ( 'Version' )
count_subkey = registry_key . GetSubkeyByName ( 'Count' )
if not version_value :
parser_mediator . ProduceExtractionWarning ( 'missing version value' )
return
if not version_value . DataIsInteger ( ) :
parser_mediator . ProduceExtractionWarning ( '... |
def package_version ( ) :
"""Get the package version via Git Tag .""" | version_path = os . path . join ( os . path . dirname ( __file__ ) , 'version.py' )
version = read_version ( version_path )
write_version ( version_path , version )
return version |
def sign ( self , data : bytes , v : int = 27 ) -> Signature :
"""Sign data hash with local private key""" | assert v in ( 0 , 27 ) , 'Raiden is only signing messages with v in (0, 27)'
_hash = eth_sign_sha3 ( data )
signature = self . private_key . sign_msg_hash ( message_hash = _hash )
sig_bytes = signature . to_bytes ( )
# adjust last byte to v
return sig_bytes [ : - 1 ] + bytes ( [ sig_bytes [ - 1 ] + v ] ) |
def create_on_demand ( self , instance_type = 'default' , tags = None , root_device_type = 'ebs' , size = 'default' , vol_type = 'gp2' , delete_on_termination = False ) :
"""Create one or more EC2 on - demand instances .
: param size : Size of root device
: type size : int
: param delete _ on _ termination : ... | name , size = self . _get_default_name_size ( instance_type , size )
if root_device_type == 'ebs' :
self . images [ instance_type ] [ 'block_device_map' ] = self . _configure_ebs_volume ( vol_type , name , size , delete_on_termination )
reservation = self . ec2 . run_instances ( ** self . images [ instance_type ] )... |
def validate_pathname ( filepath ) :
'''检查路径中是否包含特殊字符 .
百度网盘对路径 / 文件名的要求很严格 :
1 . 路径长度限制为1000
2 . 路径中不能包含以下字符 : \\ ? | " > < : *
3 . 文件名或路径名开头结尾不能是 “ . ” 或空白字符 , 空白字符包括 : \r , \n , \t , 空格 , \0 , \x0B
@ return , 返回的状态码 : 0 表示正常''' | if filepath == '/' :
return ValidatePathState . OK
if len ( filepath ) > 1000 :
return ValidatePathState . LENGTH_ERROR
filter2 = '\\?|"><:*'
for c in filter2 :
if c in filepath :
return ValidatePathState . CHAR_ERROR2
paths = rec_split_path ( filepath )
filter3 = '.\r\n\t \0\x0b'
for path in paths ... |
def distribute_batches ( self , indices ) :
"""Assigns batches to workers .
Consecutive ranks are getting consecutive batches .
: param indices : torch . tensor with batch indices""" | assert len ( indices ) == self . num_samples
indices = indices . view ( - 1 , self . batch_size )
indices = indices [ self . rank : : self . world_size ] . contiguous ( )
indices = indices . view ( - 1 )
indices = indices . tolist ( )
assert len ( indices ) == self . num_samples // self . world_size
return indices |
def raxisa ( matrix ) :
"""Compute the axis of the rotation given by an input matrix
and the angle of the rotation about that axis .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / raxisa _ c . html
: param matrix : Rotation matrix .
: type matrix : 3x3 - Element Array of flo... | matrix = stypes . toDoubleMatrix ( matrix )
axis = stypes . emptyDoubleVector ( 3 )
angle = ctypes . c_double ( )
libspice . raxisa_c ( matrix , axis , ctypes . byref ( angle ) )
return stypes . cVectorToPython ( axis ) , angle . value |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.