signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _get_auth_from_keyring ( self ) :
"""Try to get credentials using ` keyring < https : / / github . com / jaraco / keyring > ` _ .""" | if not keyring :
return None
# Take user from URL if available , else the OS login name
password = self . _get_password_from_keyring ( self . user or getpass . getuser ( ) )
if password is not None :
self . user = self . user or getpass . getuser ( )
self . password = password
return 'keyring' |
def includeme ( configurator ) :
"""Add yaml configuration utilities .
: param pyramid . config . Configurator configurator : pyramid ' s app configurator""" | settings = configurator . registry . settings
# lets default it to running path
yaml_locations = settings . get ( 'yaml.location' , settings . get ( 'yml.location' , os . getcwd ( ) ) )
configurator . add_directive ( 'config_defaults' , config_defaults )
configurator . config_defaults ( yaml_locations )
# reading yml c... |
def instance_of ( target_type : Optional [ type ] = None , raise_ex : bool = False , summary : bool = True , ** items : Any ) -> ValidationReturn :
"""Tests if the given key - value pairs ( items ) are instances of the given ` ` target _ type ` ` .
Per default this function yields whether ` ` True ` ` or ` ` Fals... | if not target_type :
raise ValueError ( "Argument 'target_type' is None" )
return Validator . __test_all ( condition = lambda _ , val : isinstance ( val , cast ( type , target_type ) ) , formatter = ( lambda name , val : "'{varname}' ({actual}) is not an instance of type '{ttype}'" . format ( varname = name , actua... |
def has_file_changed ( directory , checksums , filetype = 'genbank' ) :
"""Check if the checksum of a given file has changed .""" | pattern = NgdConfig . get_fileending ( filetype )
filename , expected_checksum = get_name_and_checksum ( checksums , pattern )
full_filename = os . path . join ( directory , filename )
# if file doesn ' t exist , it has changed
if not os . path . isfile ( full_filename ) :
return True
actual_checksum = md5sum ( ful... |
def __setup ( ) :
"""Will be executed in the first time someone calls classes _ * ( )""" | global __collaborators , __flag_first
import f311
__flag_first = False
for pkgname in f311 . COLLABORATORS_C :
try :
pkg = importlib . import_module ( pkgname )
a99 . get_python_logger ( ) . info ( "Imported collaborator package '{}'" . format ( pkgname ) )
try :
if hasattr ( pkg... |
def main_loop ( self ) :
"""Runs the main game loop .""" | while True :
for e in pygame . event . get ( ) :
self . handle_event ( e )
self . step ( )
pygame . time . wait ( 5 ) |
def sigma_points ( self , x , P ) :
"""Computes the implex sigma points for an unscented Kalman filter
given the mean ( x ) and covariance ( P ) of the filter .
Returns tuple of the sigma points and weights .
Works with both scalar and array inputs :
sigma _ points ( 5 , 9 , 2 ) # mean 5 , covariance 9
si... | if self . n != np . size ( x ) :
raise ValueError ( "expected size(x) {}, but size is {}" . format ( self . n , np . size ( x ) ) )
n = self . n
if np . isscalar ( x ) :
x = np . asarray ( [ x ] )
x = x . reshape ( - 1 , 1 )
if np . isscalar ( P ) :
P = np . eye ( n ) * P
else :
P = np . atleast_2d ( P ... |
def init_file_mapping_store ( ) :
"""init _ file _ mapping _ store : creates log to keep track of downloaded files
Args : None
Returns : None""" | # Make storage directory for restore files if it doesn ' t already exist
path = os . path . join ( RESTORE_DIRECTORY , FILE_STORE_LOCATION )
if not os . path . exists ( path ) :
os . makedirs ( path ) |
def incoordination_score ( self , data_frame ) :
"""This method calculates the variance of the time interval in msec between taps
: param data _ frame : the data frame
: type data _ frame : pandas . DataFrame
: return is : incoordination score
: rtype is : float""" | diff = data_frame . td [ 1 : - 1 ] . values - data_frame . td [ 0 : - 2 ] . values
inc_s = np . var ( diff [ np . arange ( 1 , len ( diff ) , 2 ) ] , dtype = np . float64 ) * 1000.0
duration = math . ceil ( data_frame . td [ - 1 ] )
return inc_s , duration |
def add_scope ( self , scope_type , scope_name , scope_start , is_method = False ) :
"""we identified a scope and add it to positions .""" | if self . _curr is not None :
self . _curr [ 'end' ] = scope_start - 1
# close last scope
self . _curr = { 'type' : scope_type , 'name' : scope_name , 'start' : scope_start , 'end' : scope_start }
if is_method and self . _positions :
last = self . _positions [ - 1 ]
if not 'methods' in last :
la... |
def last_requestline ( sent_data ) :
"""Find the last line in sent _ data that can be parsed with parse _ requestline""" | for line in reversed ( sent_data ) :
try :
parse_requestline ( decode_utf8 ( line ) )
except ValueError :
pass
else :
return line |
def on_raise ( self , node ) : # ( ' type ' , ' inst ' , ' tback ' )
"""Raise statement : note difference for python 2 and 3.""" | if version_info [ 0 ] == 3 :
excnode = node . exc
msgnode = node . cause
else :
excnode = node . type
msgnode = node . inst
out = self . run ( excnode )
msg = ' ' . join ( out . args )
msg2 = self . run ( msgnode )
if msg2 not in ( None , 'None' ) :
msg = "%s: %s" % ( msg , msg2 )
self . raise_excep... |
def get_position ( self , user_id , track = False , confidence = False ) :
'''a method to retrieve the latest position of a user
: param user _ id : string with id of user
: param track : [ optional ] boolean to add user to self . positions
: param confidence : [ optional ] boolean to include the data model c... | title = '%s.get_position' % self . __class__ . __name__
# validate inputs
input_fields = { 'user_id' : user_id }
for key , value in input_fields . items ( ) :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
self . fields . validate ( value , '.%s' % key , object_title )
# construct empty response
p... |
def d_day ( self , time ) :
'''指定日期
: param datetime time : 欲判斷的日期
: rtype : bool
: returns : True 為開市 、 False 為休市''' | if type ( time ) == type ( TWTime ( ) . now ) :
self . twtime = TWTime ( ) . now
elif type ( time ) == type ( TWTime ( ) . date ) :
self . twtime = TWTime ( ) . date
else :
pass
return self . caldata ( time ) |
def sim ( adata , tmax_realization = None , as_heatmap = False , shuffle = False , show = None , save = None ) :
"""Plot results of simulation .
Parameters
as _ heatmap : bool ( default : False )
Plot the timeseries as heatmap .
tmax _ realization : int or None ( default : False )
Number of observations i... | from . . . import utils as sc_utils
if tmax_realization is not None :
tmax = tmax_realization
elif 'tmax_write' in adata . uns :
tmax = adata . uns [ 'tmax_write' ]
else :
tmax = adata . n_obs
n_realizations = adata . n_obs / tmax
if not shuffle :
if not as_heatmap :
timeseries ( adata . X , var... |
def readme_for ( self , subpath ) :
"""Returns the full path for the README file for the specified
subpath , or the root filename if subpath is None .
Raises ReadmeNotFoundError if a README for the specified subpath
does not exist .
Raises werkzeug . exceptions . NotFound if the resulting path
would fall ... | if subpath is None :
return self . root_filename
# Join for safety and to convert subpath to normalized OS - specific path
filename = os . path . normpath ( safe_join ( self . root_directory , subpath ) )
# Check for existence
if not os . path . exists ( filename ) :
raise ReadmeNotFoundError ( filename )
# Res... |
def convert ( cls , record ) :
"""Converts a single dictionary or list of dictionaries into converted list of dictionaries .""" | if isinstance ( record , list ) :
return [ cls . _convert ( r ) for r in record ]
else :
return [ cls . _convert ( record ) ] |
def random_get_int ( rnd : Optional [ tcod . random . Random ] , mi : int , ma : int ) -> int :
"""Return a random integer in the range : ` ` mi ` ` < = n < = ` ` ma ` ` .
The result is affected by calls to : any : ` random _ set _ distribution ` .
Args :
rnd ( Optional [ Random ] ) : A Random instance , or N... | return int ( lib . TCOD_random_get_int ( rnd . random_c if rnd else ffi . NULL , mi , ma ) ) |
def array_to_csv ( array_like ) : # type : ( np . array or Iterable or int or float ) - > str
"""Convert an array like object to CSV .
To understand better what an array like object is see :
https : / / docs . scipy . org / doc / numpy / user / basics . creation . html # converting - python - array - like - obj... | stream = StringIO ( )
np . savetxt ( stream , array_like , delimiter = ',' , fmt = '%s' )
return stream . getvalue ( ) |
def WriteVarBytes ( self , value , endian = "<" ) :
"""Write an integer value in a space saving way to the stream .
Read more about variable size encoding here : http : / / docs . neo . org / en - us / node / network - protocol . html # convention
Args :
value ( bytes ) :
endian ( str ) : specify the endian... | length = len ( value )
self . WriteVarInt ( length , endian )
return self . WriteBytes ( value , unhex = False ) |
def register ( self , params , target ) :
"""Append a point and its target value to the known data .
Parameters
x : ndarray
a single point , with len ( x ) = = self . dim
y : float
target function value
Raises
KeyError :
if the point is not unique
Notes
runs in ammortized constant time
Example... | x = self . _as_array ( params )
if x in self :
raise KeyError ( 'Data point {} is not unique' . format ( x ) )
# Insert data into unique dictionary
self . _cache [ _hashable ( x . ravel ( ) ) ] = target
self . _params = np . concatenate ( [ self . _params , x . reshape ( 1 , - 1 ) ] )
self . _target = np . concaten... |
def scale_edges ( self , multiplier ) :
'''Multiply all edges in this ` ` Tree ` ` by ` ` multiplier ` `''' | if not isinstance ( multiplier , int ) and not isinstance ( multiplier , float ) :
raise TypeError ( "multiplier must be an int or float" )
for node in self . traverse_preorder ( ) :
if node . edge_length is not None :
node . edge_length *= multiplier |
def _subscribe_resp ( self , data ) :
"""Handle a subscribe response .
: param data : Payload .
: returns : State ( ON / OFF )""" | if _is_subscribe_response ( data ) :
status = bytes ( [ data [ 23 ] ] )
_LOGGER . debug ( "Successfully subscribed to %s, state: %s" , self . host , ord ( status ) )
return status |
def base64_decode ( data ) :
"""Base 64 decoder""" | data = data . replace ( __enc64__ [ 64 ] , '' )
total = len ( data )
result = [ ]
mod = 0
for i in range ( total ) :
mod = i % 4
cur = __enc64__ . index ( data [ i ] )
if mod == 0 :
continue
elif mod == 1 :
prev = __enc64__ . index ( data [ i - 1 ] )
result . append ( chr ( prev ... |
def register_field ( mongo_field_cls , marshmallow_field_cls , available_params = ( ) ) :
"""Bind a marshmallow field to it corresponding mongoengine field
: param mongo _ field _ cls : Mongoengine Field
: param marshmallow _ field _ cls : Marshmallow Field
: param available _ params : List of : class marshma... | class Builder ( MetaFieldBuilder ) :
AVAILABLE_PARAMS = available_params
MARSHMALLOW_FIELD_CLS = marshmallow_field_cls
register_field_builder ( mongo_field_cls , Builder ) |
def substitute_str_in_file ( i ) :
"""Input : {
filename - file
string1 - string to be replaced
string2 - replace string
Output : {
return - return code = 0 , if successful
= 16 , if file not found
> 0 , if error
( error ) - error text if return > 0""" | fn = i [ 'filename' ]
s1 = i [ 'string1' ]
s2 = i [ 'string2' ]
# Load text file ( unicode )
r = load_text_file ( { 'text_file' : fn } )
if r [ 'return' ] > 0 :
return r
# Replace
x = r [ 'string' ]
x = x . replace ( s1 , s2 )
# Save text file ( unicode )
r = save_text_file ( { 'text_file' : fn , 'string' : x } )
i... |
def choose_colour ( self , title = "Select Colour" , ** kwargs ) :
"""Show a Colour Chooser dialog
Usage : C { dialog . choose _ colour ( title = " Select Colour " ) }
@ param title : window title for the dialog
@ return : a tuple containing the exit code and colour
@ rtype : C { DialogData ( int , str ) }"... | return_data = self . _run_kdialog ( title , [ "--getcolor" ] , kwargs )
if return_data . successful :
return DialogData ( return_data . return_code , ColourData . from_html ( return_data . data ) )
else :
return DialogData ( return_data . return_code , None ) |
def ColMap ( season ) :
"""Returns a dictionary mapping the type of information in the RTSS play row to the
appropriate column number . The column locations pre / post 2008 are different .
: param season : int for the season number
: returns : mapping of RTSS column to info type
: rtype : dict , keys are ` ... | if c . MIN_SEASON <= season <= c . MAX_SEASON :
return { "play_num" : 0 , "per" : 1 , "str" : 2 , "time" : 3 , "event" : 4 , "desc" : 5 , "vis" : 6 , "home" : 7 }
else :
raise ValueError ( "RTSSCol.MAP(season): Invalid season " + str ( season ) ) |
def new_set ( set = None , set_type = None , family = 'ipv4' , comment = False , ** kwargs ) :
'''. . versionadded : : 2014.7.0
Create new custom set
CLI Example :
. . code - block : : bash
salt ' * ' ipset . new _ set custom _ set list : set
salt ' * ' ipset . new _ set custom _ set list : set comment = ... | ipset_family = _IPSET_FAMILIES [ family ]
if not set :
return 'Error: Set needs to be specified'
if not set_type :
return 'Error: Set Type needs to be specified'
if set_type not in _IPSET_SET_TYPES :
return 'Error: Set Type is invalid'
# Check for required arguments
for item in _CREATE_OPTIONS_REQUIRED [ se... |
def mean ( data , n = 3 , ** kwargs ) :
"""The mean forecast for the next point is the mean value of the previous ` ` n ` ` points in
the series .
Args :
data ( np . array ) : Observed data , presumed to be ordered in time .
n ( int ) : period over which to calculate the mean
Returns :
float : a single ... | # don ' t start averaging until we ' ve seen n points
if len ( data [ - n : ] ) < n :
forecast = np . nan
else : # nb : we ' ll keep the forecast as a float
forecast = np . mean ( data [ - n : ] )
return forecast |
def draw_circuit_canvas ( circuit , hunit = HUNIT , vunit = VUNIT , rhmargin = RHMARGIN , rvmargin = RVMARGIN , rpermutation_length = RPLENGTH , draw_boxes = True , permutation_arrows = False ) :
"""Generate a PyX graphical representation of a circuit expression object .
: param circuit : The circuit expression
... | if not isinstance ( circuit , ca . Circuit ) :
raise ValueError ( )
nc = circuit . cdim
c = pyx . canvas . canvas ( )
if circuit is ca . CIdentity : # simply create a line going through
c . stroke ( pyx . path . line ( 0 , vunit / 2 , hunit , vunit / 2 ) )
return c , ( 1 , 1 ) , ( .5 , ) , ( .5 , )
elif isi... |
def detect_arbitrary_send ( self , contract ) :
"""Detect arbitrary send
Args :
contract ( Contract )
Returns :
list ( ( Function ) , ( list ( Node ) ) )""" | ret = [ ]
for f in [ f for f in contract . functions if f . contract == contract ] :
nodes = self . arbitrary_send ( f )
if nodes :
ret . append ( ( f , nodes ) )
return ret |
def show ( self , progress , msg = None ) :
"""Show the progress bar and set it to ` progress ` tuple or value .
Args :
progress ( tuple / int / float ) : Tuple ` ` ( done / len ( all ) ) ` ` or
the direct percentage value as int / float .
msg ( str , default None ) : Alternative background description .""" | if self . whole_tag . style . display == "none" :
self . whole_tag . style . display = "block"
# allow either direct percentage value , or ( done / len ( all ) ) pairs
if isinstance ( progress , int ) or isinstance ( progress , float ) :
percentage = progress
else :
percentage = self . __class__ . _compute_... |
def check_var_coverage_content_type ( self , ds ) :
'''Check coverage content type against valid ISO - 19115-1 codes
: param netCDF4 . Dataset ds : An open netCDF dataset''' | results = [ ]
for variable in cfutil . get_geophysical_variables ( ds ) :
msgs = [ ]
ctype = getattr ( ds . variables [ variable ] , 'coverage_content_type' , None )
check = ctype is not None
if not check :
msgs . append ( "coverage_content_type" )
results . append ( Result ( BaseCheck .... |
def _request ( self , method , identifier , key = None , value = None ) :
"""Perform request with identifier .""" | params = { 'id' : identifier }
if key is not None and value is not None :
params [ key ] = value
result = yield from self . _transact ( method , params )
return result . get ( key ) |
def setComponent ( self , component ) :
"""Re - implemented from : meth : ` AbstractComponentWidget < sparkle . gui . stim . abstract _ component _ editor . AbstractComponentWidget . setComponent > `""" | details = component . auto_details ( )
state = component . stateDict ( )
for field , detail in details . items ( ) :
val = state [ field ]
self . inputWidgets [ field ] . setValue ( val )
self . _component = component |
def log ( self ) :
"""Return recent log entries as a string .""" | logserv = self . system . request_service ( 'LogStoreService' )
return logserv . lastlog ( html = False ) |
def module ( self ) :
"""The module in which the Function is defined .
Python equivalent of the CLIPS deffunction - module command .""" | modname = ffi . string ( lib . EnvDeffunctionModule ( self . _env , self . _fnc ) )
defmodule = lib . EnvFindDefmodule ( self . _env , modname )
return Module ( self . _env , defmodule ) |
def cart2spher ( x , y , z ) :
"""Cartesian to Spherical coordinate conversion .""" | hxy = np . hypot ( x , y )
r = np . hypot ( hxy , z )
theta = np . arctan2 ( z , hxy )
phi = np . arctan2 ( y , x )
return r , theta , phi |
def process_resource ( self , req , resp , resource , uri_kwargs = None ) :
"""Process resource after routing to it .
This is basic falcon middleware handler .
Args :
req ( falcon . Request ) : request object
resp ( falcon . Response ) : response object
resource ( object ) : resource object matched by fal... | if 'user' in req . context :
return
identifier = self . identify ( req , resp , resource , uri_kwargs )
user = self . try_storage ( identifier , req , resp , resource , uri_kwargs )
if user is not None :
req . context [ 'user' ] = user
# if did not succeed then we need to add this to list of available
# challen... |
def connect_patch_namespaced_pod_proxy_with_path ( self , name , namespace , path , ** kwargs ) : # noqa : E501
"""connect _ patch _ namespaced _ pod _ proxy _ with _ path # noqa : E501
connect PATCH requests to proxy of Pod # noqa : E501
This method makes a synchronous HTTP request by default . To make an
as... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . connect_patch_namespaced_pod_proxy_with_path_with_http_info ( name , namespace , path , ** kwargs )
# noqa : E501
else :
( data ) = self . connect_patch_namespaced_pod_proxy_with_path_with_http_info ( name , namespace... |
def _copy_jsonsafe ( value ) :
"""Deep - copy a value into JSON - safe types .""" | if isinstance ( value , six . string_types + ( numbers . Number , ) ) :
return value
if isinstance ( value , collections_abc . Mapping ) :
return { six . text_type ( k ) : _copy_jsonsafe ( v ) for k , v in value . items ( ) }
if isinstance ( value , collections_abc . Iterable ) :
return [ _copy_jsonsafe ( v... |
def POP ( self , params ) :
"""POP { RPopList }
Pop from the stack into the list of registers
List must contain only low registers or PC""" | # TODO verify pop order
# TODO pop list is comma separate , right ?
# TODO what registeres are allowed to POP to ? Low Registers and PC
# TODO need to support ranges , ie { R2 , R5 - R7}
# TODO PUSH should reverse the list , not POP
RPopList = self . get_one_parameter ( r'\s*{(.*)}(.*)' , params ) . split ( ',' )
RPopL... |
def _get_longest_hit_at_ref_start ( self , nucmer_hits , hits_to_exclude = None ) :
'''Input : list of nucmer hits to the same reference . Returns the longest hit to the start of the reference , or None if there is no such hit''' | if hits_to_exclude is None :
hits_to_exclude = set ( )
hits_at_start = [ hit for hit in nucmer_hits if self . _is_at_ref_start ( hit ) and hit not in hits_to_exclude ]
return self . _get_longest_hit_by_ref_length ( hits_at_start ) |
def draw_texture ( tex ) :
"""Draw a 2D texture to the current viewport
Parameters
tex : instance of Texture2D
The texture to draw .""" | from . program import Program
program = Program ( vert_draw , frag_draw )
program [ 'u_texture' ] = tex
program [ 'a_position' ] = [ [ - 1. , - 1. ] , [ - 1. , 1. ] , [ 1. , - 1. ] , [ 1. , 1. ] ]
program [ 'a_texcoord' ] = [ [ 0. , 1. ] , [ 0. , 0. ] , [ 1. , 1. ] , [ 1. , 0. ] ]
program . draw ( 'triangle_strip' ) |
def select_delim ( self , delim ) :
'''Select desired delimeter
Args :
delim : The delimeter character you want .
Returns :
None
Raises :
RuntimeError : Delimeter too long .''' | size = len ( delim )
if size > 20 :
raise RuntimeError ( 'Delimeter too long' )
n1 = size / 10
n2 = size % 10
self . send ( '^SS' + chr ( n1 ) + chr ( n2 ) ) |
def components ( self , obj , fmt = None , comm = True , ** kwargs ) :
"""Returns data and metadata dictionaries containing HTML and JS
components to include render in app , notebook , or standalone
document . Depending on the backend the fmt defines the format
embedded in the HTML , e . g . png or svg . If c... | if isinstance ( obj , ( Plot , NdWidget ) ) :
plot = obj
else :
plot , fmt = self . _validate ( obj , fmt )
widget_id = None
data , metadata = { } , { }
if isinstance ( plot , NdWidget ) :
js , html = plot ( as_script = True )
plot_id = plot . plot_id
widget_id = plot . id
else :
html , js = sel... |
def _prepare_aggregate ( cls , * args , ** kw ) :
"""Generate and execute an aggregate query pipline using combined plain and parametric query generation .
Additionally , performs argument case normalization , refer to the ` _ prepare _ query ` method ' s docstring .
This provides a find - like interface for ge... | stages = [ ]
stage_args = [ ]
fragments = [ ]
for arg in args : # Split the positional arguments into filter fragments and projection stages .
( fragments if isinstance ( arg , Filter ) else stage_args ) . append ( arg )
cls , collection , query , options = cls . _prepare_query ( cls . AGGREGATE_MAPPING , cls . AGG... |
def register ( self , slug , bundle , order = 1 , title = None ) :
"""Registers the bundle for a certain slug .
If a slug is already registered , this will raise AlreadyRegistered .
: param slug : The slug to register .
: param bundle : The bundle instance being registered .
: param order : An integer that ... | if slug in self . _registry :
raise AlreadyRegistered ( 'The url %s is already registered' % slug )
# Instantiate the admin class to save in the registry .
self . _registry [ slug ] = bundle
self . _order [ slug ] = order
if title :
self . _titles [ slug ] = title
bundle . set_admin_site ( self ) |
def close ( self ) :
"""Destructor for this audio interface . Waits the threads to finish their
streams , if desired .""" | with self . halting : # Avoid simultaneous " close " threads
if not self . finished : # Ignore all " close " calls , but the first ,
self . finished = True
# and any call to play would raise ThreadError
# Closes all playing AudioThread instances
while True :
with self . l... |
def status ( self , job_id ) :
"""Gets the status of a previously - submitted job .""" | check_jobid ( job_id )
queue = self . _get_queue ( )
if queue is None :
raise QueueDoesntExist
ret , output = self . _call ( '%s %s' % ( shell_escape ( queue / 'commands/status' ) , job_id ) , True )
if ret == 0 :
directory , result = output . splitlines ( )
result = result . decode ( 'utf-8' )
return R... |
def selected_purpose ( self ) :
"""Obtain the layer purpose selected by user .
: returns : Metadata of the selected layer purpose .
: rtype : dict , None""" | item = self . lstCategories . currentItem ( )
try :
return definition ( item . data ( QtCore . Qt . UserRole ) )
except ( AttributeError , NameError ) :
return None |
def search ( self ) :
"""Execute solr search query""" | params = self . solr_params ( )
logging . info ( "PARAMS=" + str ( params ) )
results = self . solr . search ( ** params )
logging . info ( "Docs found: {}" . format ( results . hits ) )
return self . _process_search_results ( results ) |
def find_file_paths ( self ) :
"""A generator function that recursively finds all files in the upload directory .""" | paths = [ ]
for root , dirs , files in os . walk ( self . directory , topdown = True ) :
rel_path = os . path . relpath ( root , self . directory )
for f in files :
if rel_path == '.' :
path = ( f , os . path . join ( root , f ) )
else :
path = ( os . path . join ( rel_pa... |
def page ( self , beta = values . unset , friendly_name = values . unset , phone_number = values . unset , origin = values . unset , page_token = values . unset , page_number = values . unset , page_size = values . unset ) :
"""Retrieve a single page of LocalInstance records from the API .
Request is executed imm... | params = values . of ( { 'Beta' : beta , 'FriendlyName' : friendly_name , 'PhoneNumber' : phone_number , 'Origin' : origin , 'PageToken' : page_token , 'Page' : page_number , 'PageSize' : page_size , } )
response = self . _version . page ( 'GET' , self . _uri , params = params , )
return LocalPage ( self . _version , r... |
def get_entity_text_for_relation ( self , node , relation ) :
"""Looks for an edge from node to some other node , such that the edge is
annotated with the given relation . If there exists such an edge , and
the node at the other edge is an entity , return that entity ' s text .
Otherwise , returns None .""" | G = self . G
related_node = self . get_related_node ( node , relation )
if related_node is not None :
if not G . node [ related_node ] [ 'is_event' ] :
return G . node [ related_node ] [ 'text' ]
else :
return None
else :
return None |
def delete ( self ) :
"""Deletes the bucket .
Raises :
Exception if there was an error deleting the bucket .""" | if self . exists ( ) :
try :
self . _api . buckets_delete ( self . _name )
except Exception as e :
raise e |
def django_table_names ( self , only_existing = False , ** kwargs ) :
"""Returns a list of all table names that have associated cqlengine models
and are present in settings . INSTALLED _ APPS .""" | all_models = list ( chain . from_iterable ( self . cql_models . values ( ) ) )
tables = [ model . column_family_name ( include_keyspace = False ) for model in all_models ]
return tables |
def construct_survival_curves ( hazard_rates , timelines ) :
"""Given hazard rates , reconstruct the survival curves
Parameters
hazard _ rates : ( n , t ) array
timelines : ( t , ) the observational times
Returns
t : survial curves , ( n , t ) array""" | cumulative_hazards = cumulative_integral ( hazard_rates . values , timelines )
return pd . DataFrame ( np . exp ( - cumulative_hazards ) , index = timelines ) |
def submit ( self , service_id : str , data : dict = None ) :
"""Отправить задачу в запускатор
: param service _ id : ID службы . Например " meta . docs _ generate "
: param data : Полезная нагрузка задачи
: return : dict""" | if self . __app . starter_api_url == 'http://STUB_URL' :
self . log . info ( 'STARTER DEV. Задача условно поставлена' , { "service_id" : service_id , "data" : data , } )
return
task = { "serviceId" : service_id , "data" : data }
url = self . __app . starter_api_url + '/services/' + service_id + '/tasks'
last_e ... |
def get ( self , typ = "" , only_active = True ) :
"""Return a list of keys . Either all keys or only keys of a specific type
: param typ : Type of key ( rsa , ec , oct , . . )
: return : If typ is undefined all the keys as a dictionary
otherwise the appropriate keys in a list""" | self . _uptodate ( )
_typs = [ typ . lower ( ) , typ . upper ( ) ]
if typ :
_keys = [ k for k in self . _keys if k . kty in _typs ]
else :
_keys = self . _keys
if only_active :
return [ k for k in _keys if not k . inactive_since ]
else :
return _keys |
def start_daemon_thread ( * args , ** kwargs ) :
"""Starts a thread and marks it as a daemon thread .""" | thread = threading . Thread ( * args , ** kwargs )
thread . daemon = True
thread . start ( )
return thread |
def get_default_config_help ( self ) :
"""Returns the help text for the configuration options for this handler""" | config = super ( HostedGraphiteHandler , self ) . get_default_config_help ( )
config . update ( { 'apikey' : 'Api key to use' , 'host' : 'Hostname' , 'port' : 'Port' , 'proto' : 'udp or tcp' , 'timeout' : '' , 'batch' : 'How many to store before sending to the graphite server' , 'max_backlog_multiplier' : 'how many bat... |
def iter_setup_packages ( srcdir , packages ) :
"""A generator that finds and imports all of the ` ` setup _ package . py ` `
modules in the source packages .
Returns
modgen : generator
A generator that yields ( modname , mod ) , where ` mod ` is the module and
` modname ` is the module name for the ` ` s... | for packagename in packages :
package_parts = packagename . split ( '.' )
package_path = os . path . join ( srcdir , * package_parts )
setup_package = os . path . relpath ( os . path . join ( package_path , 'setup_package.py' ) )
if os . path . isfile ( setup_package ) :
module = import_file ( s... |
def rows ( self , csv = False ) :
"""Returns each row based on the selected criteria .""" | # Store the index of each field against its ID for building each
# entry row with columns in the correct order . Also store the IDs of
# fields with a type of FileField or Date - like for special handling of
# their values .
field_indexes = { }
file_field_ids = [ ]
date_field_ids = [ ]
for field in self . form_fields :... |
def topk ( arg , k , by = None ) :
"""Returns
topk : TopK filter expression""" | op = ops . TopK ( arg , k , by = by )
return op . to_expr ( ) |
def create_signed_entity_descriptor ( entity_descriptor , security_context , valid_for = None ) :
""": param entity _ descriptor : the entity descriptor to sign
: param security _ context : security context for the signature
: param valid _ for : number of hours the metadata should be valid
: return : the sig... | if valid_for :
entity_descriptor . valid_until = in_a_while ( hours = valid_for )
entity_desc , xmldoc = sign_entity_descriptor ( entity_descriptor , None , security_context )
if not valid_instance ( entity_desc ) :
raise ValueError ( "Could not construct valid EntityDescriptor tag" )
return xmldoc |
def codec_param ( self ) :
"""string""" | param = u".%X" % self . objectTypeIndication
info = self . decSpecificInfo
if info is not None :
param += u".%d" % info . audioObjectType
return param |
def _R2deriv ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ Rderiv
PURPOSE :
evaluate the second radial derivative for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the second radial derivative
HISTORY :
2013-09-08 - Writ... | r2 = R ** 2. + z ** 2.
rb = nu . sqrt ( r2 + self . b2 )
return - ( - self . b ** 3. - self . b * z ** 2. + ( 2. * R ** 2. - z ** 2. - self . b ** 2. ) * rb ) / rb ** 3. / ( self . b + rb ) ** 3. |
def base_query ( cls , db_session = None ) :
"""returns base query for specific service
: param db _ session :
: return : query""" | db_session = get_db_session ( db_session )
return db_session . query ( cls . model ) |
def make_script ( python_script , target_path = '' , target_name = '' , user = False , make_link = False , force = False , remove = False , no_check_shebang = False , no_check_path = False ) :
"""v { VERSION }
This script makes a command line script out of a python script .
For example , ' clingon script . py '... | if user and target_path :
raise RunnerErrorWithUsage ( "You cannot specify --path and --user at the same time" )
source = os . path . abspath ( python_script )
dest_dir = os . path . normpath ( os . path . expanduser ( '~/bin' if user else target_path or os . path . dirname ( sys . executable ) ) )
target = os . pa... |
def addProxyObject ( self , obj , proxied ) :
"""Stores a reference to the unproxied and proxied versions of C { obj } for
later retrieval .
@ since : 0.6""" | self . proxied_objects [ id ( obj ) ] = proxied
self . proxied_objects [ id ( proxied ) ] = obj |
def ampliconclear ( self ) :
"""Clear previously created amplicon files to prepare for the appending of data to fresh files""" | for sample in self . metadata : # Set the name of the amplicon FASTA file
sample [ self . analysistype ] . ampliconfile = os . path . join ( sample [ self . analysistype ] . outputdir , '{sn}_amplicons.fa' . format ( sn = sample . name ) )
try :
os . remove ( sample [ self . analysistype ] . ampliconfil... |
def load ( self , fname ) :
""". . todo : : REPO . load docstring""" | # Imports
import h5py as h5
from . . error import RepoError
# If repo not None , complain
if not self . _repo == None :
raise RepoError ( RepoError . STATUS , "Repository already open" , "File: {0}" . format ( self . fname ) )
# # end if
# If string passed , try opening h5 . File ; otherwise complain
if isinstance ... |
def get_api_versions ( self , ** kwargs ) : # noqa : E501
"""get _ api _ versions # noqa : E501
get available API versions # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . get _ api _ versions (... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_api_versions_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . get_api_versions_with_http_info ( ** kwargs )
# noqa : E501
return data |
def get_radius_normal ( lat_radians : float , ell : Ellipsoid = None ) -> float :
"""Compute normal radius of planetary body
Parameters
lat _ radians : float
latitude in radians
ell : Ellipsoid , optional
reference ellipsoid
Returns
radius : float
normal radius ( meters )""" | if ell is None :
ell = Ellipsoid ( )
a = ell . a
b = ell . b
return a ** 2 / sqrt ( a ** 2 * cos ( lat_radians ) ** 2 + b ** 2 * sin ( lat_radians ) ** 2 ) |
def use_plenary_sequence_rule_enabler_rule_view ( self ) :
"""Pass through to provider SequenceRuleEnablerRuleLookupSession . use _ plenary _ sequence _ rule _ enabler _ rule _ view""" | self . _object_views [ 'sequence_rule_enabler_rule' ] = PLENARY
# self . _ get _ provider _ session ( ' sequence _ rule _ enabler _ rule _ lookup _ session ' ) # To make sure the session is tracked
for session in self . _get_provider_sessions ( ) :
try :
session . use_plenary_sequence_rule_enabler_rule_view... |
def __view_add_actions ( self ) :
"""Sets the View actions .""" | self . __view . addAction ( self . __engine . actions_manager . register_action ( "Actions|Umbra|Components|addons.projects_explorer|Add Project ..." , slot = self . __view_add_project_action__triggered ) )
self . __view . addAction ( self . __engine . actions_manager . register_action ( "Actions|Umbra|Components|addon... |
def _assignRootname ( self , chip ) :
"""Assign a unique rootname for the image based in the expname .""" | extname = self . _image [ self . scienceExt , chip ] . header [ "EXTNAME" ] . lower ( )
extver = self . _image [ self . scienceExt , chip ] . header [ "EXTVER" ]
expname = self . _rootname
# record extension - based name to reflect what extension a mask file corresponds to
self . _image [ self . scienceExt , chip ] . r... |
def count_group ( group_id , failures = False , cached = Conf . CACHED ) :
"""Count the results in a group .
: param str group _ id : the group id
: param bool failures : Returns failure count if True
: param bool cached : run this against the cache backend
: return : the number of tasks / results in a grou... | if cached :
return count_group_cached ( group_id , failures )
return Task . get_group_count ( group_id , failures ) |
def mkdir ( self , children , mode = 0o0755 , return_node = True ) :
"""Creates child entities in directory .
Raises exception if the object is a file .
: param children : The list of children to be created .
: return : The child object , if one child is provided . None , otherwise .""" | result = None
if isinstance ( children , ( str , unicode ) ) :
if os . path . isabs ( children ) :
raise BadValueError ( 'Cannot mkdir an absolute path: {path}' . format ( path = self . _pyerarchy_path ) )
rel_path = os . path . join ( self . _pyerarchy_path , children )
os . makedirs ( rel_path , m... |
def check_all_local ( self ) :
"""Check or uncheck all local event parameters .""" | all_local_chk = self . event [ 'global' ] [ 'all_local' ] . isChecked ( )
for buttons in self . event [ 'local' ] . values ( ) :
buttons [ 0 ] . setChecked ( all_local_chk )
buttons [ 1 ] . setEnabled ( buttons [ 0 ] . isChecked ( ) ) |
def _call ( self , dx ) :
"""Return ` ` self ( x ) ` ` .""" | x = self . point
dx_norm = dx . norm ( )
if dx_norm == 0 :
return 0
scaled_dx = dx * ( self . step / dx_norm )
if self . method == 'backward' :
dAdx = self . operator ( x ) - self . operator ( x - scaled_dx )
elif self . method == 'forward' :
dAdx = self . operator ( x + scaled_dx ) - self . operator ( x )
... |
def decode ( self , obj , restype , raw_ptr = False ) :
"""Converts Weld object to Python object .
Args :
obj : Result of Weld computation that needs to be decoded
restype : Type of Weld computation result
raw _ ptr : Boolean indicating whether obj needs to be extracted
from WeldValue or not
Returns :
... | if raw_ptr :
data = obj
else :
data = cweld . WeldValue ( obj ) . data ( )
result = ctypes . cast ( data , ctypes . POINTER ( restype . ctype_class ) ) . contents
if restype == WeldInt16 ( ) :
data = cweld . WeldValue ( obj ) . data ( )
result = ctypes . cast ( data , ctypes . POINTER ( c_int16 ) ) . co... |
def valuefrompostdata ( self , postdata ) :
"""This parameter method searches the POST data and retrieves the values it needs . It does not set the value yet though , but simply returns it . Needs to be explicitly passed to parameter . set ( )""" | if self . multi : # multi parameters can be passed as parameterid = choiceid1 , choiceid2 or by setting parameterid [ choiceid ] = 1 ( or whatever other non - zero value )
found = False
if self . id in postdata :
found = True
passedvalues = postdata [ self . id ] . split ( ',' )
values =... |
def _create_blank_page ( self ) :
"""Create html page to show while the kernel is starting""" | loading_template = Template ( BLANK )
page = loading_template . substitute ( css_path = self . css_path )
return page |
def summarizePosition ( self , index ) :
"""Compute residue counts at a specific sequence index .
@ param index : an C { int } index into the sequence .
@ return : A C { dict } with the count of too - short ( excluded ) sequences ,
and a Counter instance giving the residue counts .""" | countAtPosition = Counter ( )
excludedCount = 0
for read in self :
try :
countAtPosition [ read . sequence [ index ] ] += 1
except IndexError :
excludedCount += 1
return { 'excludedCount' : excludedCount , 'countAtPosition' : countAtPosition } |
def truncate ( self , percentage ) :
"""Truncate ` ` percentage ` ` / 2 [ % ] of whole time from first and last time .
: param float percentage : Percentage of truncate .
: Sample Code :
. . code : : python
from datetimerange import DateTimeRange
time _ range = DateTimeRange (
"2015-03-22T10:00:00 + 090... | self . validate_time_inversion ( )
if percentage < 0 :
raise ValueError ( "discard_percent must be greater or equal to zero: " + str ( percentage ) )
if percentage == 0 :
return
discard_time = self . timedelta // int ( 100 ) * int ( percentage / 2 )
self . __start_datetime += discard_time
self . __end_datetime ... |
def normalize_geojson_featurecollection ( obj ) :
"""Takes a geojson - like mapping representing
geometry , Feature or FeatureCollection ( or a sequence of such objects )
and returns a FeatureCollection - like dict""" | if not isinstance ( obj , Sequence ) :
obj = [ obj ]
features = [ ]
for x in obj :
if not isinstance ( x , Mapping ) or 'type' not in x :
raise ValueError ( "Expecting a geojson-like mapping or sequence of them" )
if 'features' in x :
features . extend ( x [ 'features' ] )
elif 'geometry... |
def from_independent_strains ( cls , strains , stresses , eq_stress = None , vasp = False , tol = 1e-10 ) :
"""Constructs the elastic tensor least - squares fit of independent strains
Args :
strains ( list of Strains ) : list of strain objects to fit
stresses ( list of Stresses ) : list of stress objects to u... | strain_states = [ tuple ( ss ) for ss in np . eye ( 6 ) ]
ss_dict = get_strain_state_dict ( strains , stresses , eq_stress = eq_stress )
if not set ( strain_states ) <= set ( ss_dict . keys ( ) ) :
raise ValueError ( "Missing independent strain states: " "{}" . format ( set ( strain_states ) - set ( ss_dict ) ) )
i... |
def has_next_assessment_part ( self , assessment_part_id ) :
"""This supports the basic simple sequence case . Can be overriden in a record for other cases""" | if not self . supports_child_ordering or not self . supports_simple_child_sequencing :
raise AttributeError ( )
# Only available through a record extension
if 'childIds' in self . _my_map and str ( assessment_part_id ) in self . _my_map [ 'childIds' ] :
if self . _my_map [ 'childIds' ] [ - 1 ] != str ( asse... |
def query ( self , where = "1=1" , out_fields = "*" , timeFilter = None , geometryFilter = None , returnGeometry = True , returnCountOnly = False , returnIDsOnly = False , returnFeatureClass = False , returnDistinctValues = False , returnExtentOnly = False , groupByFieldsForStatistics = None , statisticFilter = None , ... | url = self . _url + "/query"
params = { "f" : "json" }
params [ 'where' ] = where
params [ 'outFields' ] = out_fields
params [ 'returnGeometry' ] = returnGeometry
params [ 'returnDistinctValues' ] = returnDistinctValues
params [ 'returnCentroid' ] = returnCentroid
params [ 'returnCountOnly' ] = returnCountOnly
params [... |
def filename ( self ) :
"""Filename of the attachment , without the full ' attachment ' path .""" | if self . value and 'value' in self . _json_data and self . _json_data [ 'value' ] :
return self . _json_data [ 'value' ] . split ( '/' ) [ - 1 ]
return None |
def get_top ( self ) :
'''Returns the high data derived from the top file''' | tops , errors = self . get_tops ( )
try :
merged_tops = self . merge_tops ( tops )
except TypeError as err :
merged_tops = OrderedDict ( )
errors . append ( 'Error encountered while rendering pillar top file.' )
return merged_tops , errors |
def listdir ( path , include = r'.' , exclude = r'\.pyc$|^\.' , show_all = False , folders_only = False ) :
"""List files and directories""" | namelist = [ ]
dirlist = [ to_text_string ( osp . pardir ) ]
for item in os . listdir ( to_text_string ( path ) ) :
if re . search ( exclude , item ) and not show_all :
continue
if osp . isdir ( osp . join ( path , item ) ) :
dirlist . append ( item )
elif folders_only :
continue
... |
def get_random_word ( dictionary , min_word_length = 3 , max_word_length = 8 ) :
"""Returns a random word from the dictionary""" | while True : # Choose a random word
word = choice ( dictionary )
# Stop looping as soon as we have a valid candidate
if len ( word ) >= min_word_length and len ( word ) <= max_word_length :
break
return word |
def deactivate ( self ) :
"""Deactivates the Component .
: return : Method success .
: rtype : bool""" | LOGGER . debug ( "> Deactivating '{0}' Component." . format ( self . __class__ . __name__ ) )
self . __engine = None
self . __settings = None
self . __settings_section = None
self . __script_editor = None
self . activated = False
return True |
def parse ( self , file = None , string = None ) :
"""SAX parse XML text .
@ param file : Parse a python I { file - like } object .
@ type file : I { file - like } object .
@ param string : Parse string XML .
@ type string : str""" | timer = metrics . Timer ( )
timer . start ( )
sax , handler = self . saxparser ( )
if file is not None :
sax . parse ( file )
timer . stop ( )
metrics . log . debug ( 'sax (%s) duration: %s' , file , timer )
return handler . nodes [ 0 ]
if string is not None :
if isinstance ( string , str ) :
... |
def process_result ( self , context , result_body , exc , content_type ) :
"""given an result body and an exception object ,
return the appropriate result object ,
or raise an exception .""" | return process_result ( self , context , result_body , exc , content_type ) |
def source ( self ) :
"""The source element this document element was created from .""" | if self . _source is not None :
return self . _source
elif self . parent is not None :
return self . parent . source
else :
return Location ( self ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.