signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def validate_network_topology ( network_id , ** kwargs ) :
"""Check for the presence of orphan nodes in a network .""" | user_id = kwargs . get ( 'user_id' )
try :
net_i = db . DBSession . query ( Network ) . filter ( Network . id == network_id ) . one ( )
net_i . check_write_permission ( user_id = user_id )
except NoResultFound :
raise ResourceNotFoundError ( "Network %s not found" % ( network_id ) )
nodes = [ ]
for node_i i... |
def _treat_devices_added ( self ) :
"""Process the new devices .""" | try :
devices_details_list = self . _plugin_rpc . get_devices_details_list ( self . _context , self . _added_ports , self . _agent_id )
except Exception as exc :
LOG . debug ( "Unable to get ports details for " "devices %(devices)s: %(exc)s" , { 'devices' : self . _added_ports , 'exc' : exc } )
return
for d... |
def iter_xCharts ( self ) :
"""Generate each xChart child element in document .""" | plot_tags = ( qn ( 'c:area3DChart' ) , qn ( 'c:areaChart' ) , qn ( 'c:bar3DChart' ) , qn ( 'c:barChart' ) , qn ( 'c:bubbleChart' ) , qn ( 'c:doughnutChart' ) , qn ( 'c:line3DChart' ) , qn ( 'c:lineChart' ) , qn ( 'c:ofPieChart' ) , qn ( 'c:pie3DChart' ) , qn ( 'c:pieChart' ) , qn ( 'c:radarChart' ) , qn ( 'c:scatterCha... |
def attach_http_service ( cls , http_service : HTTPService ) :
"""Attaches a service for hosting
: param http _ service : A HTTPService instance""" | if cls . _http_service is None :
cls . _http_service = http_service
cls . _set_bus ( http_service )
else :
warnings . warn ( 'HTTP service is already attached' ) |
def _len_iter ( obj ) :
'''Length ( hint ) of an iterator .''' | n = getattr ( obj , '__length_hint__' , None )
if n :
n = n ( )
else : # try len ( )
n = _len ( obj )
return n |
def load_and_append ( probe_dict , probes , instruments = { } ) :
"""load probes from probe _ dict and append to probes , if additional instruments are required create them and add them to instruments
Args :
probe _ dict : dictionary of form
probe _ dict = {
instrument1 _ name : probe1 _ of _ instrument1 , ... | loaded_failed = { }
updated_probes = { }
updated_probes . update ( probes )
updated_instruments = { }
updated_instruments . update ( instruments )
# = = = = = load new instruments = = = = =
new_instruments = list ( set ( probe_dict . keys ( ) ) - set ( probes . keys ( ) ) )
if new_instruments != [ ] :
updated_instr... |
def get_parser ( ) :
"Specifies the arguments and defaults , and returns the parser ." | parser = argparse . ArgumentParser ( prog = "hiwenet" )
parser . add_argument ( "-f" , "--in_features_path" , action = "store" , dest = "in_features_path" , required = True , help = "Abs. path to file containing features for a given subject" )
parser . add_argument ( "-g" , "--groups_path" , action = "store" , dest = "... |
def add_channel_cb ( self , viewer , channel ) :
"""Called when a channel is added from the main interface .
Parameter is channel ( a bunch ) .""" | fitsimage = channel . fitsimage
fitssettings = fitsimage . get_settings ( )
for name in [ 'cuts' ] :
fitssettings . get_setting ( name ) . add_callback ( 'set' , self . cutset_cb , fitsimage )
fitsimage . add_callback ( 'transform' , self . transform_cb )
rgbmap = fitsimage . get_rgbmap ( )
rgbmap . add_callback ( ... |
def detect_components ( args , distro ) :
"""Since the package split , now there are various different Ceph components to
install like :
* ceph
* ceph - mon
* ceph - mgr
* ceph - osd
* ceph - mds
This helper function should parse the args that may contain specifics about
these flags and return the d... | # the flag that prevents all logic here is the ` - - repo ` flag which is used
# when no packages should be installed , just the repo files , so check for
# that here and return an empty list ( which is equivalent to say ' no
# packages should be installed ' )
if args . repo :
return [ ]
flags = { 'install_osd' : '... |
def parse ( self , line ) :
"""Returns tree objects from a sentence
Args :
line : Sentence to be parsed into a tree
Returns :
Tree object representing parsed sentence
None if parse fails""" | tree = list ( self . parser . raw_parse ( line ) ) [ 0 ]
tree = tree [ 0 ]
return tree |
def get_services ( ) :
"""Retrieve a list of all system services .
@ see : L { get _ active _ services } ,
L { start _ service } , L { stop _ service } ,
L { pause _ service } , L { resume _ service }
@ rtype : list ( L { win32 . ServiceStatusProcessEntry } )
@ return : List of service status descriptors ... | with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager :
try :
return win32 . EnumServicesStatusEx ( hSCManager )
except AttributeError :
return win32 . EnumServicesStatus ( hSCManager ) |
def validate_context_for_visiting_vertex_field ( parent_location , vertex_field_name , context ) :
"""Ensure that the current context allows for visiting a vertex field .""" | if is_in_fold_innermost_scope ( context ) :
raise GraphQLCompilationError ( u'Traversing inside a @fold block after filtering on {} or outputting fields ' u'is not supported! Parent location: {}, vertex field name: {}' . format ( COUNT_META_FIELD_NAME , parent_location , vertex_field_name ) ) |
def setBatchSize ( self , size ) :
"""Sets the batch size of records to look up for this record box .
: param size | < int >""" | self . _batchSize = size
try :
self . _worker . setBatchSize ( size )
except AttributeError :
pass |
def isfunc ( x ) :
"""Returns ` True ` if the given value is a function or method object .
Arguments :
x ( mixed ) : value to check .
Returns :
bool""" | return any ( [ inspect . isfunction ( x ) and not asyncio . iscoroutinefunction ( x ) , inspect . ismethod ( x ) and not asyncio . iscoroutinefunction ( x ) ] ) |
def restore_watched ( plex , opts ) :
"""Restore watched status from the specified filepath .""" | with open ( opts . filepath , 'r' ) as handle :
source = json . load ( handle )
# Find the differences
differences = defaultdict ( lambda : dict ( ) )
for section in _iter_sections ( plex , opts ) :
print ( 'Finding differences in %s..' % section . title )
skey = section . title . lower ( )
for item in ... |
def forest ( S = 3 , r1 = 4 , r2 = 2 , p = 0.1 , is_sparse = False ) :
"""Generate a MDP example based on a simple forest management scenario .
This function is used to generate a transition probability
( ` ` A ` ` × ` ` S ` ` × ` ` S ` ` ) array ` ` P ` ` and a reward ( ` ` S ` ` × ` ` A ` ` ) matrix
` ` R `... | assert S > 1 , "The number of states S must be greater than 1."
assert ( r1 > 0 ) and ( r2 > 0 ) , "The rewards must be non-negative."
assert 0 <= p <= 1 , "The probability p must be in [0; 1]."
# Definition of Transition matrix
if is_sparse :
P = [ ]
rows = list ( range ( S ) ) * 2
cols = [ 0 ] * S + list ... |
def putcell ( self , columnname , rownr , value ) :
"""Put a value into one or more table cells .
The columnname and ( 0 - relative ) rownrs indicate the table cells .
rownr can be a single row number or a sequence of row numbers .
If multiple rownrs are given , the given value is put in all those rows .
Th... | self . _putcell ( columnname , rownr , value ) |
def open_listing_page ( trailing_part_of_url ) :
"""Opens a BBC radio tracklisting page based on trailing part of url .
Returns a lxml ElementTree derived from that page .
trailing _ part _ of _ url : a string , like the pid or e . g . pid / segments . inc""" | base_url = 'http://www.bbc.co.uk/programmes/'
print ( "Opening web page: " + base_url + trailing_part_of_url )
try :
html = requests . get ( base_url + trailing_part_of_url ) . text
except ( IOError , NameError ) :
print ( "Error opening web page." )
print ( "Check network connection and/or programme id." )... |
def fs_obj_set_acl ( self , path , follow_symlinks , acl , mode ) :
"""Sets the access control list ( ACL ) of a file system object ( file ,
directory , etc ) in the guest .
in path of type str
Full path of the file system object which ACL to set
in follow _ symlinks of type bool
If @ c true symbolic link... | if not isinstance ( path , basestring ) :
raise TypeError ( "path can only be an instance of type basestring" )
if not isinstance ( follow_symlinks , bool ) :
raise TypeError ( "follow_symlinks can only be an instance of type bool" )
if not isinstance ( acl , basestring ) :
raise TypeError ( "acl can only b... |
def pad ( data , length ) :
"""This function returns a padded version of the input data to the
given length . this function will shorten the given data to the length
specified if necessary . post - condition : len ( data ) = length
: param data : the data byte array to pad
: param length : the length to pad... | if ( len ( data ) > length ) :
return data [ 0 : length ]
else :
return data + b"\0" * ( length - len ( data ) ) |
def _readGroupSetsGenerator ( self , request , numObjects , getByIndexMethod ) :
"""Returns a generator over the results for the specified request , which
is over a set of objects of the specified size . The objects are
returned by call to the specified method , which must take a single
integer as an argument... | currentIndex = 0
if request . page_token :
currentIndex , = paging . _parsePageToken ( request . page_token , 1 )
while currentIndex < numObjects :
obj = getByIndexMethod ( currentIndex )
include = True
rgsp = obj . toProtocolElement ( )
if request . name and request . name != obj . getLocalId ( ) :... |
def consolidate ( self ) :
"""Remove duplicate vertices and edges from this skeleton without
side effects .
Returns : new consolidated PrecomputedSkeleton""" | nodes = self . vertices
edges = self . edges
radii = self . radii
vertex_types = self . vertex_types
if self . empty ( ) :
return PrecomputedSkeleton ( )
eff_nodes , uniq_idx , idx_representative = np . unique ( nodes , axis = 0 , return_index = True , return_inverse = True )
edge_vector_map = np . vectorize ( lamb... |
def parse_tag_pattern ( self , sel , m , has_selector ) :
"""Parse tag pattern from regex match .""" | parts = [ css_unescape ( x ) for x in m . group ( 0 ) . split ( '|' ) ]
if len ( parts ) > 1 :
prefix = parts [ 0 ]
tag = parts [ 1 ]
else :
tag = parts [ 0 ]
prefix = None
sel . tag = ct . SelectorTag ( tag , prefix )
has_selector = True
return has_selector |
def log_message ( self , user , message ) :
"""Log a channel message .
This log acts as a sort of cache so that recent activity can be searched
by the bot and command modules without querying the database .""" | if isinstance ( user , SeshetUser ) :
user = user . nick
elif not isinstance ( user , IRCstr ) :
user = IRCstr ( user )
time = datetime . utcnow ( )
self . message_log . append ( ( time , user , message ) )
while len ( self . message_log ) > self . _log_size :
del self . message_log [ 0 ] |
def update_bounds_axes ( self ) :
"""Update the bounds axes of the render window""" | if ( hasattr ( self , '_box_object' ) and self . _box_object is not None and self . bounding_box_actor is not None ) :
if not np . allclose ( self . _box_object . bounds , self . bounds ) :
color = self . bounding_box_actor . GetProperty ( ) . GetColor ( )
self . remove_bounding_box ( )
self... |
def sensor ( self , name , config = None , inactive_sensor_expiration_time_seconds = sys . maxsize , parents = None ) :
"""Get or create a sensor with the given unique name and zero or
more parent sensors . All parent sensors will receive every value
recorded with this sensor .
Arguments :
name ( str ) : Th... | sensor = self . get_sensor ( name )
if sensor :
return sensor
with self . _lock :
sensor = self . get_sensor ( name )
if not sensor :
sensor = Sensor ( self , name , parents , config or self . config , inactive_sensor_expiration_time_seconds )
self . _sensors [ name ] = sensor
if par... |
def _write_passphrase ( stream , passphrase , encoding ) :
"""Write the passphrase from memory to the GnuPG process ' stdin .
: type stream : file , : class : ` ~ io . BytesIO ` , or : class : ` ~ io . StringIO `
: param stream : The input file descriptor to write the password to .
: param str passphrase : Th... | passphrase = '%s\n' % passphrase
passphrase = passphrase . encode ( encoding )
stream . write ( passphrase )
log . debug ( "Wrote passphrase on stdin." ) |
def address_exists ( name , addressname = None , vsys = 1 , ipnetmask = None , iprange = None , fqdn = None , description = None , commit = False ) :
'''Ensures that an address object exists in the configured state . If it does not exist or is not configured with the
specified attributes , it will be adjusted to ... | ret = _default_ret ( name )
if not addressname :
ret . update ( { 'comment' : "The service name field must be provided." } )
return ret
# Check if address object currently exists
address = __salt__ [ 'panos.get_address' ] ( addressname , vsys ) [ 'result' ]
if address and 'entry' in address :
address = addr... |
def _CompositeFoldByteStream ( self , mapped_value , context = None , ** unused_kwargs ) :
"""Folds the data type into a byte stream .
Args :
mapped _ value ( object ) : mapped value .
context ( Optional [ DataTypeMapContext ] ) : data type map context .
Returns :
bytes : byte stream .
Raises :
Foldin... | context_state = getattr ( context , 'state' , { } )
attribute_index = context_state . get ( 'attribute_index' , 0 )
subcontext = context_state . get ( 'context' , None )
if not subcontext :
subcontext = DataTypeMapContext ( values = { type ( mapped_value ) . __name__ : mapped_value } )
data_attributes = [ ]
for att... |
def merge_svg_layers ( svg_sources , share_transform = True ) :
'''Merge layers from input svg sources into a single XML document .
Args :
svg _ sources ( list ) : A list of file - like objects , each containing
one or more XML layers .
share _ transform ( bool ) : If exactly one layer has a transform , app... | # Get list of XML layers .
( width , height ) , layers = get_svg_layers ( svg_sources )
if share_transform :
transforms = [ layer_i . attrib [ 'transform' ] for layer_i in layers if 'transform' in layer_i . attrib ]
if len ( transforms ) > 1 :
raise ValueError ( 'Transform can only be shared if *exactly... |
def get_changes ( self , new_name , in_file = None , in_hierarchy = False , unsure = None , docs = False , resources = None , task_handle = taskhandle . NullTaskHandle ( ) ) :
"""Get the changes needed for this refactoring
Parameters :
- ` in _ hierarchy ` : when renaming a method this keyword forces
to renam... | if unsure in ( True , False ) :
warnings . warn ( 'unsure parameter should be a function that returns ' 'True or False' , DeprecationWarning , stacklevel = 2 )
def unsure_func ( value = unsure ) :
return value
unsure = unsure_func
if in_file is not None :
warnings . warn ( '`in_file` argument ha... |
def ellipticity_lens_light ( self , kwargs_lens_light , center_x = 0 , center_y = 0 , model_bool_list = None , deltaPix = None , numPix = None ) :
"""make sure that the window covers all the light , otherwise the moments may give to low answers .
: param kwargs _ lens _ light :
: param center _ x :
: param ce... | if model_bool_list is None :
model_bool_list = [ True ] * len ( kwargs_lens_light )
if numPix is None :
numPix = 100
if deltaPix is None :
deltaPix = 0.05
x_grid , y_grid = util . make_grid ( numPix = numPix , deltapix = deltaPix )
x_grid += center_x
y_grid += center_y
I_xy = self . _lens_light_internal ( x... |
def clone ( existing_compound , clone_of = None , root_container = None ) :
"""A faster alternative to deepcopying .
Does not resolve circular dependencies . This should be safe provided
you never try to add the top of a Compound hierarchy to a
sub - Compound .
Parameters
existing _ compound : mb . Compou... | if clone_of is None :
clone_of = dict ( )
newone = existing_compound . _clone ( clone_of = clone_of , root_container = root_container )
existing_compound . _clone_bonds ( clone_of = clone_of )
return newone |
def compute ( self , inputVector , learn , activeArray ) :
"""This method resembles the primary public method of the SpatialPooler class .
It takes a input vector and outputs the indices of the active columns . If ' learn '
is set to True , this method also performs weight updates and updates to the activity
... | x = inputVector
y = self . encode ( x )
active_units = np . where ( y == 1. ) [ 0 ]
if learn :
self . update_statistics ( [ y ] )
self . update_weights ( [ x ] , [ y ] )
activeArray [ active_units ] = 1.
return active_units |
def transpose ( self ) :
"""Create a matrix , transpose it , and then create a new FVM
: raise NotImplementedError : if all existing rows aren ' t keyed
: return : a new FVM rotated from self""" | if len ( self . _row_name_list ) != len ( self . _rows ) :
raise NotImplementedError ( "You can't rotate a FVM that doesn't have all rows keyed" )
fvm = FeatureVectorMatrix ( default_value = self . _default_value , default_to_hashed_rows = self . _default_to_hashed_rows )
fvm . _update_internal_column_state ( self ... |
def ready ( self ) :
"""Return 200 is ready , else 500.
Override is _ ready ( ) to change the readiness check .""" | try :
if self . is_ready ( ) :
return "OK" , 200
else :
return "FAIL" , 500
except Exception as e :
self . app . logger . exception ( )
return str ( e ) , 500 |
def get_ichrone ( models , bands = None , default = False , ** kwargs ) :
"""Gets Isochrone Object by name , or type , with the right bands
If ` default ` is ` True ` , then will set bands
to be the union of bands and default _ bands""" | if isinstance ( models , Isochrone ) :
return models
def actual ( bands , ictype ) :
if bands is None :
return list ( ictype . default_bands )
elif default :
return list ( set ( bands ) . union ( set ( ictype . default_bands ) ) )
else :
return bands
if type ( models ) is type ( ... |
def is_ini_file ( filename , show_warnings = False ) :
"""Check configuration file type is INI
Return a boolean indicating wheather the file is INI format or not""" | try :
config_dict = load_config ( filename , file_type = "ini" )
if config_dict == { } :
is_ini = False
else :
is_ini = True
except :
is_ini = False
return ( is_ini ) |
def CSVofIntegers ( msg = None ) :
'''Checks whether a value is list of integers .
Returns list of integers or just one integer in
list if there is only one element in given CSV string .''' | def fn ( value ) :
try :
if isinstance ( value , basestring ) :
if ',' in value :
value = list ( map ( int , filter ( bool , list ( map ( lambda x : x . strip ( ) , value . split ( ',' ) ) ) ) ) )
return value
else :
return [ int ( valu... |
def default_classification_value_maps ( classification ) :
"""Helper to get default value maps from classification .
: param classification : Classification definition .
: type classification : dict
: returns : Dictionary with key = the class key and value = default strings .
: rtype : dict""" | value_maps = { }
for hazard_class in classification [ 'classes' ] :
value_maps [ hazard_class [ 'key' ] ] = hazard_class . get ( 'string_defaults' , [ ] )
return value_maps |
def print_status ( self ) :
"""Print out the current tweet rate and reset the counter""" | tweets = self . received
now = time . time ( )
diff = now - self . since
self . since = now
self . received = 0
if diff > 0 :
logger . info ( "Receiving tweets at %s tps" , tweets / diff ) |
def add_project_name_or_id_arg ( arg_parser , required = True , help_text_suffix = "manage" ) :
"""Adds project name or project id argument . These two are mutually exclusive .
: param arg _ parser :
: param required :
: param help _ text :
: return :""" | project_name_or_id = arg_parser . add_mutually_exclusive_group ( required = required )
name_help_text = "Name of the project to {}." . format ( help_text_suffix )
add_project_name_arg ( project_name_or_id , required = False , help_text = name_help_text )
id_help_text = "ID of the project to {}." . format ( help_text_su... |
def unregister ( self , entry_point ) :
"""Unregister a provider
: param str entry _ point : provider to unregister ( entry point syntax ) .""" | if entry_point not in self . registered_extensions :
raise ValueError ( 'Extension not registered' )
ep = EntryPoint . parse ( entry_point )
self . registered_extensions . remove ( entry_point )
if self . _extensions_by_name is not None :
del self . _extensions_by_name [ ep . name ]
for i , ext in enumerate ( s... |
def vm_profiles_config ( path , providers , env_var = 'SALT_CLOUDVM_CONFIG' , defaults = None ) :
'''Read in the salt cloud VM config file''' | if defaults is None :
defaults = VM_CONFIG_DEFAULTS
overrides = salt . config . load_config ( path , env_var , os . path . join ( salt . syspaths . CONFIG_DIR , 'cloud.profiles' ) )
default_include = overrides . get ( 'default_include' , defaults [ 'default_include' ] )
include = overrides . get ( 'include' , [ ] )... |
def celery ( function , * args , ** kwargs ) :
'''Calls ` ` function ` ` asynchronously by creating a pickling it and
calling it in a task .''' | from . tasks import dill_callable
dilled_function = dill . dumps ( function )
dill_callable . delay ( dilled_function , * args , ** kwargs ) |
def _call_func ( self ) :
"""Call the wrapped function and return the result wrapped by
DataFrameWrapper .
Also updates attributes like columns , index , and length .""" | if _CACHING and self . cache and self . name in _TABLE_CACHE :
logger . debug ( 'returning table {!r} from cache' . format ( self . name ) )
return _TABLE_CACHE [ self . name ] . value
with log_start_finish ( 'call function to get frame for table {!r}' . format ( self . name ) , logger ) :
kwargs = _collect... |
def _utc_tuple ( self , offset = 0.0 ) :
"""Return UTC as ( year , month , day , hour , minute , second . fraction ) .
The ` offset ` is added to the UTC time before it is split into
its components . This is useful if the user is going to round
the result before displaying it . If the result is going to be
... | tai = self . tai + offset
leap_dates = self . ts . leap_dates
leap_offsets = self . ts . leap_offsets
leap_reverse_dates = leap_dates + leap_offsets / DAY_S
i = searchsorted ( leap_reverse_dates , tai , 'right' )
j = tai - leap_offsets [ i ] / DAY_S
whole , fraction = divmod ( j + 0.5 , 1.0 )
whole = whole . astype ( i... |
def then_no_model_exists ( context , model_name , key , value ) :
""": type model _ name : str
: type key : str
: type value : str
: type context : behave . runner . Context""" | model = apps . get_model ( model_name )
args = { key : value }
obj = model . objects . filter ( ** args )
assert len ( obj ) == 0 |
def flatten_matrix ( mat ) :
"""This function transforms a given 2D tuple matrix into a list of tuples ,
where each tuple represents a column from the original matrix .
Examples :
> > > flatten _ matrix ( [ [ ( 4 , 5 ) , ( 7 , 8 ) ] , [ ( 10 , 13 ) , ( 18 , 17 ) ] , [ ( 0 , 4 ) , ( 10 , 1 ) ] ] )
' [ ( 4 , ... | intermediate_list = [ element for sublist in mat for element in sublist ]
result_list = list ( zip ( * intermediate_list ) )
return str ( result_list ) |
def _restore_group ( self , group_id ) :
"""Get group metadata for a group by id .""" | meta = self . TaskSetModel . _default_manager . restore_taskset ( group_id )
if meta :
return meta . to_dict ( ) |
def entropy_calc ( item , POP ) :
"""Calculate reference and response likelihood .
: param item : TOP or P
: type item : dict
: param POP : population
: type POP : dict
: return : reference or response likelihood as float""" | try :
result = 0
for i in item . keys ( ) :
likelihood = item [ i ] / POP [ i ]
if likelihood != 0 :
result += likelihood * math . log ( likelihood , 2 )
return - result
except Exception :
return "None" |
def uma_rs_check_access ( self , rpt , path , http_method ) :
"""Function to be used in a UMA Resource Server to check access .
Parameters :
* * * rpt ( string ) : * * RPT or blank value if absent ( not send by RP )
* * * path ( string ) : * * Path of resource ( e . g . for http : / / rs . com / phones , / ph... | params = { "oxd_id" : self . oxd_id , "rpt" : rpt , "path" : path , "http_method" : http_method }
logger . debug ( "Sending command `uma_rs_check_access` with params %s" , params )
response = self . msgr . request ( "uma_rs_check_access" , ** params )
logger . debug ( "Received response: %s" , response )
if response [ ... |
def send_sticker ( self , peer : Peer , sticker : str , reply : int = None , on_success : callable = None , reply_markup : botapi . ReplyMarkup = None ) :
"""Send sticker to peer .
: param peer : Peer to send message to .
: param sticker : File path to sticker to send .
: param reply : Message object or messa... | if isinstance ( reply , Message ) :
reply = reply . id
sticker = botapi . InputFile ( 'sticker' , botapi . InputFileInfo ( sticker , open ( sticker , 'rb' ) , get_mimetype ( sticker ) ) )
botapi . send_sticker ( chat_id = peer . id , sticker = sticker , reply_to_message_id = reply , on_success = on_success , reply_... |
def transcript_to_gene ( gtf ) :
"""return a dictionary keyed by transcript _ id of the associated gene _ id""" | gene_lookup = { }
for feature in complete_features ( get_gtf_db ( gtf ) ) :
gene_id = feature . attributes . get ( 'gene_id' , [ None ] ) [ 0 ]
transcript_id = feature . attributes . get ( 'transcript_id' , [ None ] ) [ 0 ]
gene_lookup [ transcript_id ] = gene_id
return gene_lookup |
def cmd_async ( self , low ) :
'''Execute a function asynchronously ; eauth is respected
This function requires that : conf _ master : ` external _ auth ` is configured
and the user is authorized
. . code - block : : python
> > > wheel . cmd _ async ( {
' fun ' : ' key . finger ' ,
' match ' : ' jerry '... | fun = low . pop ( 'fun' )
return self . asynchronous ( fun , low ) |
def delete_agent ( self , pool_id , agent_id ) :
"""DeleteAgent .
[ Preview API ] Delete an agent . You probably don ' t want to call this endpoint directly . Instead , [ use the agent configuration script ] ( https : / / docs . microsoft . com / azure / devops / pipelines / agents / agents ) to remove an agent f... | route_values = { }
if pool_id is not None :
route_values [ 'poolId' ] = self . _serialize . url ( 'pool_id' , pool_id , 'int' )
if agent_id is not None :
route_values [ 'agentId' ] = self . _serialize . url ( 'agent_id' , agent_id , 'int' )
self . _send ( http_method = 'DELETE' , location_id = 'e298ef32-5878-4c... |
def transformer_moe_layer_v1 ( inputs , output_dim , hparams , train , variable_dtype , layout = None , mesh_shape = None , nonpadding = None ) :
"""Local mixture of experts that works well on TPU .
Adapted from the paper https : / / arxiv . org / abs / 1701.06538
Note : until the algorithm and inferface solidi... | orig_inputs = inputs
hidden_dim = mtf . Dimension ( "expert_hidden" , hparams . moe_hidden_size )
experts_dim = mtf . Dimension ( "experts" , hparams . moe_num_experts )
# We " cheat " here and look at the mesh shape and layout . This is to ensure
# that the number of groups is a multiple of the mesh dimension
# over w... |
def get_writer ( self ) :
"""Get a writer .
This method also makes the output filename be the same as the . track file but with . mpc .
( Currently only works on local filesystem )
: rtype MPCWriter""" | if self . _writer is None :
suffix = tasks . get_suffix ( tasks . TRACK_TASK )
try :
base_name = re . search ( "(?P<base_name>.*?)\.\d*{}" . format ( suffix ) , self . filename ) . group ( 'base_name' )
except :
base_name = os . path . splitext ( self . filename ) [ 0 ]
mpc_filename_patt... |
def to_phy ( self ) :
"""Convert this to the standard : class : ` pyparser . capture . common . PhyInfo `
class .""" | kwargs = { }
for attr in [ 'signal' , 'noise' , 'freq_mhz' , 'fcs_error' , 'rate' , 'mcs' , 'len' , 'caplen' , 'epoch_ts' , 'end_epoch_ts' ] :
kwargs [ attr ] = getattr ( self , attr , None )
kwargs [ 'has_fcs' ] = True
return PhyInfo ( ** kwargs ) |
def save_source ( driver , name ) :
"""Save the rendered HTML of the browser .
The location of the source can be configured
by the environment variable ` SAVED _ SOURCE _ DIR ` . If not set ,
this defaults to the current working directory .
Args :
driver ( selenium . webdriver ) : The Selenium - controlle... | source = driver . page_source
file_name = os . path . join ( os . environ . get ( 'SAVED_SOURCE_DIR' ) , '{name}.html' . format ( name = name ) )
try :
with open ( file_name , 'wb' ) as output_file :
output_file . write ( source . encode ( 'utf-8' ) )
except Exception : # pylint : disable = broad - except
... |
def assign_dict ( self , node , xml_dict ) :
"""Assigns a Python dict to a ` ` lxml ` ` node .
: param node : A node to assign the dict to .
: param xml _ dict : The dict with attributes / children to use .""" | new_node = etree . Element ( node . tag )
# Replaces the previous node with the new one
self . _xml . replace ( node , new_node )
# Copies # text and @ attrs from the xml _ dict
helpers . dict_to_etree ( xml_dict , new_node ) |
def _get_calculated_value ( self , value ) :
"""Get ' s the final value of the field and runs the lambda functions
recursively until a final value is derived .
: param value : The value to calculate / expand
: return : The final value""" | if isinstance ( value , types . LambdaType ) :
expanded_value = value ( self . structure )
return self . _get_calculated_value ( expanded_value )
else : # perform one final parsing of the value in case lambda value
# returned a different type
return self . _parse_value ( value ) |
def _neg_bounded_fun ( fun , bounds , x , args = ( ) ) :
"""Wrapper for bounding and taking the negative of ` fun ` for the
Nelder - Mead algorithm . JIT - compiled in ` nopython ` mode using Numba .
Parameters
fun : callable
The objective function to be minimized .
` fun ( x , * args ) - > float `
wher... | if _check_bounds ( x , bounds ) :
return - fun ( x , * args )
else :
return np . inf |
def Instance ( self ) :
"""Returns the singleton instance . Upon its first call , it creates a
new instance of the decorated class and calls its ` _ _ init _ _ ` method .
On all subsequent calls , the already created instance is returned .""" | try :
return self . _instance
except AttributeError :
self . _instance = self . _decorated ( )
return self . _instance |
def group_list ( ** kwargs ) :
"""Show available routing groups .""" | ctx = Context ( ** kwargs )
ctx . execute_action ( 'group:list' , ** { 'storage' : ctx . repo . create_secure_service ( 'storage' ) , } ) |
def toCSV ( pdl , out = None , write_field_names = True ) :
"""Conversion from the PyDbLite Base instance pdl to the file object out
open for writing in binary mode
If out is not specified , the field name is the same as the PyDbLite
file with extension . csv
If write _ field _ names is True , field names a... | import csv
if out is None :
file_name = os . path . splitext ( pdl . name ) [ 0 ] + ".csv"
out = open ( file_name , "wb" )
fields = [ "__id__" , "__version__" ] + pdl . fields
writer = csv . DictWriter ( out , fields )
# write field names
if write_field_names :
writer . writerow ( dict ( [ ( k , k ) for k i... |
def pagination_links ( paginator_page , show_pages , url_params = None , first_page_label = None , last_page_label = None , page_url = '' ) :
'''Django template tag to display pagination links for a paginated
list of items .
Expects the following variables :
* the current : class : ` ~ django . core . paginat... | return { 'items' : paginator_page , 'show_pages' : show_pages , 'url_params' : url_params , 'first_page_label' : first_page_label , 'last_page_label' : last_page_label , 'page_url' : page_url , } |
def postinit ( self , body = None , handlers = None , orelse = None ) :
"""Do some setup after initialisation .
: param body : The contents of the block to catch exceptions from .
: type body : list ( NodeNG ) or None
: param handlers : The exception handlers .
: type handlers : list ( ExceptHandler ) or No... | self . body = body
self . handlers = handlers
self . orelse = orelse |
def _loadServices ( self ) :
"""Load module services .
: return : < void >""" | servicesPath = os . path . join ( self . path , "service" )
if not os . path . isdir ( servicesPath ) :
return
self . _scanDirectoryForServices ( servicesPath ) |
def add_textbox ( self , left , top , width , height ) :
"""Return newly added text box shape appended to this shape tree .
The text box is of the specified size , located at the specified
position on the slide .""" | sp = self . _add_textbox_sp ( left , top , width , height )
self . _recalculate_extents ( )
return self . _shape_factory ( sp ) |
def add_matplotlib_cmap ( cm , name = None ) :
"""Add a matplotlib colormap .""" | global cmaps
cmap = matplotlib_to_ginga_cmap ( cm , name = name )
cmaps [ cmap . name ] = cmap |
def dispatch ( self , event : Event ) -> Iterator [ Any ] :
"""Yields handlers matching the routing of the incoming : class : ` slack . events . Event ` .
Args :
event : : class : ` slack . events . Event `
Yields :
handler""" | LOG . debug ( 'Dispatching event "%s"' , event . get ( "type" ) )
if event [ "type" ] in self . _routes :
for detail_key , detail_values in self . _routes . get ( event [ "type" ] , { } ) . items ( ) :
event_value = event . get ( detail_key , "*" )
yield from detail_values . get ( event_value , [ ] ... |
def _vad_collector ( self , sample_rate , frame_duration_ms , padding_duration_ms , vad , frames ) :
"""Filters out non - voiced audio frames .
Given a webrtcvad . Vad and a source of audio frames , yields only
the voiced audio .
Uses a padded , sliding window algorithm over the audio frames .
When more tha... | num_padding_frames = int ( padding_duration_ms / frame_duration_ms )
# We use a deque for our sliding window / ring buffer .
ring_buffer = collections . deque ( maxlen = num_padding_frames )
# We have two states : TRIGGERED and NOTTRIGGERED . We start in the
# NOTTRIGGERED state .
triggered = False
voiced_frames = [ ]
... |
def splitstatus ( a , statusfn ) :
'split sequence into subsequences based on binary condition statusfn . a is a list , returns list of lists' | groups = [ ] ;
mode = None
for elt , status in zip ( a , map ( statusfn , a ) ) :
assert isinstance ( status , bool )
if status != mode :
mode = status ;
group = [ mode ] ;
groups . append ( group )
group . append ( elt )
return groups |
def nifti_copy ( filename , prefix = None , gzip = True ) :
'''creates a ` ` . nii ` ` copy of the given dataset and returns the filename as a string''' | # I know , my argument ` ` prefix ` ` clobbers the global method . . . but it makes my arguments look nice and clean
if prefix == None :
prefix = filename
nifti_filename = globals ( ) [ 'prefix' ] ( prefix ) + ".nii"
if gzip :
nifti_filename += '.gz'
if not os . path . exists ( nifti_filename ) :
try :
... |
def detach ( self , auth_no_user_interaction = None ) :
"""Detach the device by e . g . powering down the physical port .""" | return self . _assocdrive . _M . Drive . PowerOff ( '(a{sv})' , filter_opt ( { 'auth.no_user_interaction' : ( 'b' , auth_no_user_interaction ) , } ) ) |
def _tostr ( self , obj ) :
"""converts a object to list , if object is a list , it creates a
comma seperated string .""" | if not obj :
return ''
if isinstance ( obj , list ) :
return ', ' . join ( map ( self . _tostr , obj ) )
return str ( obj ) |
def check_syntax ( string ) :
"""Check syntax of a string of PostgreSQL - dialect SQL""" | args = [ "ecpg" , "-o" , "-" , "-" ]
with open ( os . devnull , "w" ) as devnull :
try :
proc = subprocess . Popen ( args , shell = False , stdout = devnull , stdin = subprocess . PIPE , stderr = subprocess . PIPE , universal_newlines = True )
_ , err = proc . communicate ( string )
except OSErr... |
def get_valid_time_stamp ( ) :
"""Get a valid time stamp without illegal characters .
Adds time _ to make the time stamp a valid table name in sql .
: return : String , extracted timestamp""" | time_stamp = str ( datetime . datetime . now ( ) )
time_stamp = "time_" + time_stamp . replace ( "-" , "_" ) . replace ( ":" , "_" ) . replace ( " " , "_" ) . replace ( "." , "_" )
return time_stamp |
def annual_frequency_of_exceedence ( poe , t_haz ) :
""": param poe : array of probabilities of exceedence
: param t _ haz : hazard investigation time
: returns : array of frequencies ( with + inf values where poe = 1)""" | with warnings . catch_warnings ( ) :
warnings . simplefilter ( "ignore" )
# avoid RuntimeWarning : divide by zero encountered in log
return - numpy . log ( 1. - poe ) / t_haz |
def Convert ( self , metadata , stat_entry , token = None ) :
"""Converts StatEntry to ExportedFile .
Does nothing if StatEntry corresponds to a registry entry and not to a file .
Args :
metadata : ExportedMetadata to be used for conversion .
stat _ entry : StatEntry to be converted .
token : Security tok... | return self . BatchConvert ( [ ( metadata , stat_entry ) ] , token = token ) |
def to_byte ( stype ) :
"""Returns the instruction sequence for converting from
the given type to byte .""" | output = [ ]
if stype in ( 'i8' , 'u8' ) :
return [ ]
if is_int_type ( stype ) :
output . append ( 'ld a, l' )
elif stype == 'f16' :
output . append ( 'ld a, e' )
elif stype == 'f' : # Converts C ED LH to byte
output . append ( 'call __FTOU32REG' )
output . append ( 'ld a, l' )
REQUIRES . add ( ... |
def sign_extend ( self , new_length ) :
"""Unary operation : SignExtend
: param new _ length : New length after sign - extension
: return : A new StridedInterval""" | msb = self . extract ( self . bits - 1 , self . bits - 1 ) . eval ( 2 )
if msb == [ 0 ] : # All positive numbers
return self . zero_extend ( new_length )
if msb == [ 1 ] : # All negative numbers
si = self . copy ( )
si . _bits = new_length
mask = ( 2 ** new_length - 1 ) - ( 2 ** self . bits - 1 )
si... |
def _add_ticks ( xaxis : go . layout . XAxis , histogram : HistogramBase , kwargs : dict ) :
"""Customize ticks for an axis ( 1D histogram ) .""" | ticks = kwargs . pop ( "ticks" , None )
tick_handler = kwargs . pop ( "tick_handler" , None )
if tick_handler :
if ticks :
raise ValueError ( "Cannot specify both tick and tick_handler" )
ticks , labels = tick_handler ( histogram , histogram . min_edge , histogram . max_edge )
xaxis . tickvals = tic... |
def spectral_analysis ( dx , Ain , tapering = None , overlap = None , wsize = None , alpha = 3.0 , detrend = False , normalise = False , integration = True , average = True , ARspec = None ) :
"""Spectral _ Analysis :
This function performs a spatial spectral analysis with different options on a time series of SL... | A = Ain . copy ( )
# Check dimensions
sh = A . shape
ndims = len ( sh )
N = sh [ 0 ]
# Time series are found along the last dimension
# If vector , add one dimension
if ndims == 1 :
A = A . reshape ( ( N , 1 ) )
sh = A . shape
ndims = len ( sh )
nr = sh [ 1 ]
# Number of repeats
nt = nr
# gain = 1.0 # Scali... |
def one_mask ( self ) :
"""Return a mask to determine whether an array chunk has any ones .""" | accum = 0
for i in range ( self . data . itemsize ) :
accum += ( 0xAA << ( i << 3 ) )
return accum |
def bbox_rotate ( bbox , angle , rows , cols , interpolation ) :
"""Rotates a bounding box by angle degrees
Args :
bbox ( tuple ) : A tuple ( x _ min , y _ min , x _ max , y _ max ) .
angle ( int ) : Angle of rotation in degrees
rows ( int ) : Image rows .
cols ( int ) : Image cols .
interpolation ( int... | scale = cols / float ( rows )
x = np . array ( [ bbox [ 0 ] , bbox [ 2 ] , bbox [ 2 ] , bbox [ 0 ] ] )
y = np . array ( [ bbox [ 1 ] , bbox [ 1 ] , bbox [ 3 ] , bbox [ 3 ] ] )
x = x - 0.5
y = y - 0.5
angle = np . deg2rad ( angle )
x_t = ( np . cos ( angle ) * x * scale + np . sin ( angle ) * y ) / scale
y_t = ( - np . ... |
def users ( self , start = 1 , num = 10 , sortField = "fullName" , sortOrder = "asc" , role = None ) :
"""Lists all the members of the organization . The start and num paging
parameters are supported .
Inputs :
start - The number of the first entry in the result set response .
The index number is 1 - based ... | users = [ ]
url = self . _url + "/users"
params = { "f" : "json" , "start" : start , "num" : num }
if not role is None :
params [ 'role' ] = role
if not sortField is None :
params [ 'sortField' ] = sortField
if not sortOrder is None :
params [ 'sortOrder' ] = sortOrder
from . _community import Community
res... |
def do_show ( self , cmd , args ) :
"""Display content of a file .
cat Display current working directory .
cat < file > Display content of a file .""" | if not args :
self . stdout . write ( os . getcwd ( ) )
self . stdout . write ( '\n' )
return
fname = args [ 0 ]
with open ( fname , 'r' , encoding = 'utf8' ) as f :
self . stdout . write ( f . read ( ) )
self . stdout . write ( '\n' ) |
def get_colour_handler ( extranames : List [ str ] = None , with_process_id : bool = False , with_thread_id : bool = False , stream : TextIO = None ) -> logging . StreamHandler :
"""Gets a colour log handler using a standard format .
Args :
extranames : additional names to append to the logger ' s name
with _... | fmt = "%(white)s%(asctime)s.%(msecs)03d"
# this is dim white = grey
if with_process_id or with_thread_id :
procinfo = [ ]
# type : List [ str ]
if with_process_id :
procinfo . append ( "p%(process)d" )
if with_thread_id :
procinfo . append ( "t%(thread)d" )
fmt += " [{}]" . format ( ... |
def deploy_new_instance ( cls , w3 : Web3 ) -> "VyperReferenceRegistry" :
"""Returns a new instance of ` ` ` VyperReferenceRegistry ` ` representing a freshly deployed
instance on the given ` ` web3 ` ` instance of the Vyper Reference Registry implementation .""" | manifest = get_vyper_registry_manifest ( )
registry_package = Package ( manifest , w3 )
registry_factory = registry_package . get_contract_factory ( "registry" )
tx_hash = registry_factory . constructor ( ) . transact ( )
tx_receipt = w3 . eth . waitForTransactionReceipt ( tx_hash )
registry_address = to_canonical_addr... |
def merge_from_master ( git_action , study_id , auth_info , parent_sha ) :
"""merge from master into the WIP for this study / author
this is needed to allow a worker ' s future saves to
be merged seamlessly into master""" | return _merge_from_master ( git_action , doc_id = study_id , auth_info = auth_info , parent_sha = parent_sha , doctype_display_name = "study" ) |
def build_tri ( adf ) :
"""Looks at each column , and chooses the feed with the most recent data
point . Honours the Trump override / failsafe logic .""" | # just look at the capital ( price ) , in " feed one " , and income ( dividend ) , in " feed two "
cap , inc = adf . columns [ 1 : 3 ]
data = adf [ [ cap , inc ] ]
# find the feeds with the most recent data . . .
inc_pct = data [ inc ] . div ( data [ cap ] . shift ( 1 ) )
cap_pct = data [ cap ] . pct_change ( 1 )
pre_f... |
def contacts ( self , uid = 0 , ** kwargs ) :
"""Fetch user contacts by given group id .
A useful synonym for " contacts / search " command with provided ` groupId ` parameter .
: Example :
lists = client . lists . contacts ( 1901010)
: param int uid : The unique id of the List . Required .
: param int pa... | contacts = Contacts ( self . base_uri , self . auth )
return self . get_subresource_instances ( uid , instance = contacts , resource = "contacts" , params = kwargs ) |
def from_statement ( cls , statement , filename = '<expr>' ) :
"""A helper to construct a PythonFile from a triple - quoted string , for testing .
: param statement : Python file contents
: return : Instance of PythonFile""" | lines = textwrap . dedent ( statement ) . split ( '\n' )
if lines and not lines [ 0 ] : # Remove the initial empty line , which is an artifact of dedent .
lines = lines [ 1 : ]
blob = '\n' . join ( lines ) . encode ( 'utf-8' )
tree = cls . _parse ( blob , filename )
return cls ( blob = blob , tree = tree , root = N... |
def _StackSummary_extract ( frame_gen , limit = None , lookup_lines = True , capture_locals = False ) :
"""Replacement for : func : ` StackSummary . extract ` .
Create a StackSummary from a traceback or stack object .
Very simplified copy of the original StackSummary . extract ( ) .
We want always to capture ... | result = StackSummary ( )
for f , lineno in frame_gen :
co = f . f_code
filename = co . co_filename
name = co . co_name
result . append ( ExtendedFrameSummary ( frame = f , filename = filename , lineno = lineno , name = name , lookup_line = False ) )
return result |
def main_impl ( all_detector_classes , all_printer_classes ) :
""": param all _ detector _ classes : A list of all detectors that can be included / excluded .
: param all _ printer _ classes : A list of all printers that can be included .""" | args = parse_args ( all_detector_classes , all_printer_classes )
# Set colorization option
set_colorization_enabled ( not args . disable_color )
printer_classes = choose_printers ( args , all_printer_classes )
detector_classes = choose_detectors ( args , all_detector_classes )
default_log = logging . INFO if not args .... |
def set ( zpool , prop , value ) :
'''Sets the given property on the specified pool
zpool : string
Name of storage pool
prop : string
Name of property to set
value : string
Value to set for the specified property
. . versionadded : : 2016.3.0
CLI Example :
. . code - block : : bash
salt ' * ' zp... | ret = OrderedDict ( )
# set property
res = __salt__ [ 'cmd.run_all' ] ( __utils__ [ 'zfs.zpool_command' ] ( command = 'set' , property_name = prop , property_value = value , target = zpool , ) , python_shell = False , )
return __utils__ [ 'zfs.parse_command_result' ] ( res , 'set' ) |
def handle_url_build_error ( self , error : Exception , endpoint : str , values : dict ) -> str :
"""Handle a build error .
Ideally this will return a valid url given the error endpoint
and values .""" | for handler in self . url_build_error_handlers :
result = handler ( error , endpoint , values )
if result is not None :
return result
raise error |
def lapmod ( n , cc , ii , kk , fast = True , return_cost = True , fp_version = FP_DYNAMIC ) :
"""Solve sparse linear assignment problem using Jonker - Volgenant algorithm .
n : number of rows of the assignment cost matrix
cc : 1D array of all finite elements of the assignement cost matrix
ii : 1D array of in... | # log = logging . getLogger ( ' lapmod ' )
check_cost ( n , cc , ii , kk )
if fast is True : # log . debug ( ' [ - - - - CR & RT & ARR & augmentation - - - - ] ' )
x , y = _lapmod ( n , cc , ii , kk , fp_version = fp_version )
else :
cc = np . ascontiguousarray ( cc , dtype = np . float64 )
ii = np . ascont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.