signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _load_items_from_file ( keychain , path ) :
"""Given a single file , loads all the trust objects from it into arrays and
the keychain .
Returns a tuple of lists : the first list is a list of identities , the
second a list of certs .""" | certificates = [ ]
identities = [ ]
result_array = None
with open ( path , 'rb' ) as f :
raw_filedata = f . read ( )
try :
filedata = CoreFoundation . CFDataCreate ( CoreFoundation . kCFAllocatorDefault , raw_filedata , len ( raw_filedata ) )
result_array = CoreFoundation . CFArrayRef ( )
result = Secur... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : SyncListItemContext for this SyncListItemInstance
: rtype : twilio . rest . preview . sync . service . sync _ list . sync ... | if self . _context is None :
self . _context = SyncListItemContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , list_sid = self . _solution [ 'list_sid' ] , index = self . _solution [ 'index' ] , )
return self . _context |
def update ( self , event_or_list ) :
"""Update the text and position of cursor according to the event passed .""" | event_or_list = super ( ) . update ( event_or_list )
for e in event_or_list :
if e . type == KEYDOWN :
if e . key == K_RIGHT :
if e . mod * KMOD_CTRL :
self . move_cursor_one_word ( self . RIGHT )
else :
self . move_cursor_one_letter ( self . RIGHT )
... |
def penn_treebank_dataset ( directory = 'data/penn-treebank' , train = False , dev = False , test = False , train_filename = 'ptb.train.txt' , dev_filename = 'ptb.valid.txt' , test_filename = 'ptb.test.txt' , check_files = [ 'ptb.train.txt' ] , urls = [ 'https://raw.githubusercontent.com/wojzaremba/lstm/master/data/ptb... | download_files_maybe_extract ( urls = urls , directory = directory , check_files = check_files )
ret = [ ]
splits = [ ( train , train_filename ) , ( dev , dev_filename ) , ( test , test_filename ) ]
splits = [ f for ( requested , f ) in splits if requested ]
for filename in splits :
full_path = os . path . join ( d... |
def com_adobe_fonts_check_cff_call_depth ( ttFont ) :
"""Is the CFF subr / gsubr call depth > 10?""" | any_failures = False
cff = ttFont [ 'CFF ' ] . cff
for top_dict in cff . topDictIndex :
if hasattr ( top_dict , 'FDArray' ) :
for fd_index , font_dict in enumerate ( top_dict . FDArray ) :
if hasattr ( font_dict , 'Private' ) :
private_dict = font_dict . Private
else ... |
def relieve_state_machines ( self , model , prop_name , info ) :
"""The method relieves observed models before those get removed from the list of state _ machines hold by
observed StateMachineMangerModel . The method register as observer of observable
StateMachineMangerModel . state _ machines .""" | if info [ 'method_name' ] == '__setitem__' :
pass
elif info [ 'method_name' ] == '__delitem__' :
self . relieve_model ( self . state_machine_manager_model . state_machines [ info [ 'args' ] [ 0 ] ] )
self . logger . info ( NotificationOverview ( info ) )
else :
self . logger . warning ( NotificationOver... |
def get_symmetry ( cell , symprec = 1e-5 , angle_tolerance = - 1.0 ) :
"""This gives crystal symmetry operations from a crystal structure .
Args :
cell : Crystal structrue given either in Atoms object or tuple .
In the case given by a tuple , it has to follow the form below ,
( Lattice parameters in a 3x3 a... | _set_no_error ( )
lattice , positions , numbers , magmoms = _expand_cell ( cell )
if lattice is None :
return None
multi = 48 * len ( positions )
rotation = np . zeros ( ( multi , 3 , 3 ) , dtype = 'intc' )
translation = np . zeros ( ( multi , 3 ) , dtype = 'double' )
# Get symmetry operations
if magmoms is None :
... |
def get_next ( self ) :
"""Returns the next : obj : ` Gtk . TreeModelRow ` or None""" | next_iter = self . model . iter_next ( self . iter )
if next_iter :
return TreeModelRow ( self . model , next_iter ) |
def id ( opts ) :
'''Return a unique ID for this proxy minion . This ID MUST NOT CHANGE .
If it changes while the proxy is running the salt - master will get
really confused and may stop talking to this minion''' | r = salt . utils . http . query ( opts [ 'proxy' ] [ 'url' ] + 'id' , decode_type = 'json' , decode = True )
return r [ 'dict' ] [ 'id' ] . encode ( 'ascii' , 'ignore' ) |
def on_palette_name_changed ( self , combo ) :
"""Changes the value of palette in dconf""" | palette_name = combo . get_active_text ( )
if palette_name not in PALETTES :
return
self . settings . styleFont . set_string ( 'palette' , PALETTES [ palette_name ] )
self . settings . styleFont . set_string ( 'palette-name' , palette_name )
self . set_palette_colors ( PALETTES [ palette_name ] )
self . update_demo... |
def day_interval ( year , month , day , milliseconds = False , return_string = False ) :
"""Return a start datetime and end datetime of a day .
: param milliseconds : Minimum time resolution .
: param return _ string : If you want string instead of datetime , set True
Usage Example : :
> > > start , end = r... | if milliseconds : # pragma : no cover
delta = timedelta ( milliseconds = 1 )
else :
delta = timedelta ( seconds = 1 )
start = datetime ( year , month , day )
end = datetime ( year , month , day ) + timedelta ( days = 1 ) - delta
if not return_string :
return start , end
else :
return str ( start ) , str... |
def gen_challenge ( self , state ) :
"""This function generates a challenge for given state . It selects a
random number and sets that as the challenge key . By default , v _ max
is set to the prime , and the number of chunks to challenge is the
number of chunks in the file . ( this doesn ' t guarantee that t... | state . decrypt ( self . key )
chal = Challenge ( state . chunks , self . prime , Random . new ( ) . read ( 32 ) )
return chal |
def activate_pipeline ( self ) :
"""Activates a deployed pipeline , useful for OnDemand pipelines""" | self . client . activate_pipeline ( pipelineId = self . pipeline_id )
LOG . info ( "Activated Pipeline %s" , self . pipeline_id ) |
def make_url ( self , path , api_root = u'/v2/' ) :
"""Gets a full URL from just path .""" | return urljoin ( urljoin ( self . url , api_root ) , path ) |
def update_resource_properties ( r , orig_columns = { } , force = False ) :
"""Get descriptions and other properties from this , or upstream , packages , and add them to the schema .""" | added = [ ]
schema_term = r . schema_term
if not schema_term :
warn ( "No schema term for " , r . name )
return
rg = r . raw_row_generator
# Get columns information from the schema , or , if it is a package reference ,
# from the upstream schema
upstream_columns = { e [ 'name' ] . lower ( ) if e [ 'name' ] else... |
def build_url_field ( self , field_name , model_class ) :
"""Create a field representing the object ' s own URL .""" | field_class = self . serializer_url_field
field_kwargs = rest_framework . serializers . get_url_kwargs ( model_class )
field_kwargs . update ( { "parent_lookup_field" : self . get_parent_lookup_field ( ) } )
return field_class , field_kwargs |
def publish_topology_description_changed ( self , previous_description , new_description , topology_id ) :
"""Publish a TopologyDescriptionChangedEvent to all topology listeners .
: Parameters :
- ` previous _ description ` : The previous topology description .
- ` new _ description ` : The new topology descr... | event = TopologyDescriptionChangedEvent ( previous_description , new_description , topology_id )
for subscriber in self . __topology_listeners :
try :
subscriber . description_changed ( event )
except Exception :
_handle_exception ( ) |
def has_chess960_castling_rights ( self ) -> bool :
"""Checks if there are castling rights that are only possible in Chess960.""" | # Get valid Chess960 castling rights .
chess960 = self . chess960
self . chess960 = True
castling_rights = self . clean_castling_rights ( )
self . chess960 = chess960
# Standard chess castling rights can only be on the standard
# starting rook squares .
if castling_rights & ~ BB_CORNERS :
return True
# If there are... |
def filter_publication ( publication , cache = _CACHE ) :
"""Deduplication function , which compares ` publication ` with samples stored in
` cache ` . If the match NOT is found , ` publication ` is returned , else None .
Args :
publication ( obj ) : : class : ` . Publication ` instance .
cache ( obj ) : Ca... | if cache is None :
cache = load_cache ( )
if publication . _get_hash ( ) in cache :
return None
cache . update ( [ publication . _get_hash ( ) ] )
save_cache ( cache )
return publication |
def inherit_doc ( cls ) :
"""A decorator that makes a class inherit documentation from its parents .""" | for name , func in vars ( cls ) . items ( ) : # only inherit docstring for public functions
if name . startswith ( "_" ) :
continue
if not func . __doc__ :
for parent in cls . __bases__ :
parent_func = getattr ( parent , name , None )
if parent_func and getattr ( parent_f... |
def report_sections ( self ) :
"""Add results from Qualimap BamQC parsing to the report""" | # Append to self . sections list
if len ( self . qualimap_bamqc_coverage_hist ) > 0 : # Chew back on histogram to prevent long flat tail
# ( find a sensible max x - lose 1 % of longest tail )
max_x = 0
total_bases_by_sample = dict ( )
for s_name , d in self . qualimap_bamqc_coverage_hist . items ( ) :
... |
def calculate_fitness ( self ) :
"""Calculcate your fitness .""" | if self . fitness is not None :
raise Exception ( "You are calculating the fitness of agent {}, " . format ( self . id ) + "but they already have a fitness" )
said_blue = self . infos ( type = Meme ) [ 0 ] . contents == "blue"
proportion = float ( max ( self . network . nodes ( type = RogersEnvironment ) [ 0 ] . in... |
def RegisterTextKey ( cls , key , frameid ) :
"""Register a text key .
If the key you need to register is a simple one - to - one mapping
of ID3 frame name to EasyID3 key , then you can use this
function : :
EasyID3 . RegisterTextKey ( " title " , " TIT2 " )""" | def getter ( id3 , key ) :
return list ( id3 [ frameid ] )
def setter ( id3 , key , value ) :
try :
frame = id3 [ frameid ]
except KeyError :
id3 . add ( mutagen . id3 . Frames [ frameid ] ( encoding = 3 , text = value ) )
else :
frame . encoding = 3
frame . text = value
... |
def date_range ( cls , start_time , end_time , freq ) :
'''Returns a new SArray that represents a fixed frequency datetime index .
Parameters
start _ time : datetime . datetime
Left bound for generating dates .
end _ time : datetime . datetime
Right bound for generating dates .
freq : datetime . timedel... | if not isinstance ( start_time , datetime . datetime ) :
raise TypeError ( "The ``start_time`` argument must be from type datetime.datetime." )
if not isinstance ( end_time , datetime . datetime ) :
raise TypeError ( "The ``end_time`` argument must be from type datetime.datetime." )
if not isinstance ( freq , d... |
def match_or ( self , tokens , item ) :
"""Matches or .""" | for x in range ( 1 , len ( tokens ) ) :
self . duplicate ( ) . match ( tokens [ x ] , item )
with self . only_self ( ) :
self . match ( tokens [ 0 ] , item ) |
def pack ( self , grads ) :
"""Args :
grads ( list ) : list of gradient tensors
Returns :
packed list of gradient tensors to be aggregated .""" | for i , g in enumerate ( grads ) :
assert g . shape == self . _shapes [ i ]
with cached_name_scope ( "GradientPacker" , top_level = False ) :
concat_grads = tf . concat ( [ tf . reshape ( g , [ - 1 ] ) for g in grads ] , 0 , name = 'concatenated_grads' )
# concat _ grads = tf . cast ( concat _ grads , tf . ... |
def encode_properties ( parameters ) :
"""Performs encoding of url parameters from dictionary to a string . It does
not escape backslash because it is not needed .
See : http : / / www . jfrog . com / confluence / display / RTF / Artifactory + REST + API # ArtifactoryRESTAPI - SetItemProperties""" | result = [ ]
for param in iter ( sorted ( parameters ) ) :
if isinstance ( parameters [ param ] , ( list , tuple ) ) :
value = ',' . join ( [ escape_chars ( x ) for x in parameters [ param ] ] )
else :
value = escape_chars ( parameters [ param ] )
result . append ( "%s=%s" % ( param , value ... |
def flush ( bank , key = None ) :
'''Remove the key from the cache bank with all the key content .''' | if key is None :
c_key = bank
else :
c_key = '{0}/{1}' . format ( bank , key )
try :
return api . kv . delete ( c_key , recurse = key is None )
except Exception as exc :
raise SaltCacheError ( 'There was an error removing the key, {0}: {1}' . format ( c_key , exc ) ) |
def u_get ( self , quant ) :
"""Return a number using the given quantity of unsigned bits .""" | if not quant :
return
bits = [ ]
while quant :
if self . _count == 0 :
byte = self . src . read ( 1 )
number = struct . unpack ( "<B" , byte ) [ 0 ]
self . _bits = bin ( number ) [ 2 : ] . zfill ( 8 )
self . _count = 8
if quant > self . _count :
self . _count , quant ... |
def get_backend_mod ( name = None ) :
"""Returns the imported module for the given backend name
Parameters
name : ` str ` , optional
the name of the backend , defaults to the current backend .
Returns
backend _ mod : ` module `
the module as returned by : func : ` importlib . import _ module `
Example... | if name is None :
name = get_backend ( )
backend_name = ( name [ 9 : ] if name . startswith ( "module://" ) else "matplotlib.backends.backend_{}" . format ( name . lower ( ) ) )
return importlib . import_module ( backend_name ) |
def classify_identifier ( did ) :
"""Return a text fragment classifying the ` ` did ` `
Return < UNKNOWN > if the DID could not be classified . This should not normally happen
and may indicate that the DID was orphaned in the database .""" | if _is_unused_did ( did ) :
return 'unused on this Member Node'
elif is_sid ( did ) :
return 'a Series ID (SID) of a revision chain'
elif is_local_replica ( did ) :
return 'a Persistent ID (PID) of a local replica'
elif is_unprocessed_local_replica ( did ) :
return ( 'a Persistent ID (PID) of an accepte... |
def raw_sensor_strings ( self ) :
"""Reads the raw strings from the kernel module sysfs interface
: returns : raw strings containing all bytes from the sensor memory
: rtype : str
: raises NoSensorFoundError : if the sensor could not be found
: raises SensorNotReadyError : if the sensor is not ready yet""" | try :
with open ( self . sensorpath , "r" ) as f :
data = f . readlines ( )
except IOError :
raise NoSensorFoundError ( self . type_name , self . id )
if data [ 0 ] . strip ( ) [ - 3 : ] != "YES" :
raise SensorNotReadyError ( self )
return data |
def _prep_callable_bed ( in_file , work_dir , stats , data ) :
"""Sort and merge callable BED regions to prevent SV double counting""" | out_file = os . path . join ( work_dir , "%s-merge.bed.gz" % utils . splitext_plus ( os . path . basename ( in_file ) ) [ 0 ] )
gsort = config_utils . get_program ( "gsort" , data )
if not utils . file_uptodate ( out_file , in_file ) :
with file_transaction ( data , out_file ) as tx_out_file :
fai_file = re... |
def _clause_formatter ( self , cond ) :
'''Formats conditions
args is a list of [ ' field ' , ' operator ' , ' value ' ]''' | if len ( cond ) == 2 :
cond = ' ' . join ( cond )
return cond
if 'in' in cond [ 1 ] . lower ( ) :
if not isinstance ( cond [ 2 ] , ( tuple , list ) ) :
raise TypeError ( '("{0}") must be of type <type tuple> or <type list>' . format ( cond [ 2 ] ) )
if 'select' not in cond [ 2 ] [ 0 ] . lower ( ... |
def merge_into ( self , other ) :
"""Merge two simple selectors together . This is expected to be the
selector being injected into ` other ` - - that is , ` other ` is the
selector for a block using ` ` @ extend ` ` , and ` self ` is a selector being
extended .
Element tokens must come first , and pseudo - ... | # TODO it shouldn ' t be possible to merge two elements or two pseudo
# elements , / but / it shouldn ' t just be a fatal error here - - it
# shouldn ' t even be considered a candidate for extending !
# TODO this is slightly inconsistent with ruby , which treats a trailing
# set of self tokens like ' : before . foo ' a... |
def install_config_kibana ( self ) :
"""install and config kibana
: return :""" | if self . prompt_check ( "Download and install kibana" ) :
self . kibana_install ( )
if self . prompt_check ( "Configure and autostart kibana" ) :
self . kibana_config ( ) |
def read_in_survey_parameters ( log , pathToSettingsFile ) :
"""* First reads in the mcs _ settings . yaml file to determine the name of the settings file to read in the survey parameters . *
* * Key Arguments : * *
- ` ` log ` ` - - logger
- ` ` pathToSettingsFile ` ` - - path to the settings file for the si... | # # # # # # > IMPORTS # # # # #
# # STANDARD LIB # #
# # THIRD PARTY # #
import yaml
# # LOCAL APPLICATION # #
# # # # # # VARIABLE ATTRIBUTES # # # # #
# # # # # # > ACTION ( S ) # # # # #
# READ THE NAME OF THE SETTINGS FILE FOR THIS SIMULATION
try :
stream = file ( pathToSettingsFile , 'r' )
thisDict = yaml ... |
def inspect_model ( self , model ) :
"""Inspect a single model""" | # See which interesting fields the model holds .
url_fields = sorted ( f for f in model . _meta . fields if isinstance ( f , ( PluginUrlField , models . URLField ) ) )
file_fields = sorted ( f for f in model . _meta . fields if isinstance ( f , ( PluginImageField , models . FileField ) ) )
html_fields = sorted ( f for ... |
def xi_eq ( x , kappa , chi_eff , q ) :
"""The roots of this equation determine the orbital radius
at the onset of NS tidal disruption in a nonprecessing
NS - BH binary [ ( 7 ) in Foucart PRD 86 , 124007 ( 2012 ) ]
Parameters
x : float
orbital separation in units of the NS radius
kappa : float
the BH ... | return x ** 3 * ( x ** 2 - 3 * kappa * x + 2 * chi_eff * kappa * math . sqrt ( kappa * x ) ) - 3 * q * ( x ** 2 - 2 * kappa * x + ( chi_eff * kappa ) ** 2 ) |
def _mapper ( self ) :
"""Maps payment attributes to their specific types .
: see : func : ` ~ APIResource . _ mapper `""" | return { 'card' : Payment . Card , 'customer' : Payment . Customer , 'hosted_payment' : Payment . HostedPayment , 'notification' : Payment . Notification , 'failure' : Payment . Failure , } |
def setup_launch_parser ( self , parser ) :
"""Setup the given parser for the launch command
: param parser : the argument parser to setup
: type parser : : class : ` argparse . ArgumentParser `
: returns : None
: rtype : None
: raises : None""" | parser . set_defaults ( func = self . launch )
parser . add_argument ( "addon" , help = "The jukebox addon to launch. The addon should be a standalone plugin." ) |
def _MultiStream ( cls , fds ) :
"""Method overriden by subclasses to optimize the MultiStream behavior .""" | for fd in fds :
fd . Seek ( 0 )
while True :
chunk = fd . Read ( cls . MULTI_STREAM_CHUNK_SIZE )
if not chunk :
break
yield fd , chunk , None |
def get_time_diff_days ( start_txt , end_txt ) :
'''Number of days between two days''' | if start_txt is None or end_txt is None :
return None
start = parser . parse ( start_txt )
end = parser . parse ( end_txt )
seconds_day = float ( 60 * 60 * 24 )
diff_days = ( end - start ) . total_seconds ( ) / seconds_day
diff_days = float ( '%.2f' % diff_days )
return diff_days |
def executorLost ( self , driver , executorId , agentId , status ) :
"""Invoked when an executor has exited / terminated abnormally .""" | failedId = executorId . get ( 'value' , None )
log . warning ( "Executor '%s' reported lost with status '%s'." , failedId , status )
self . _handleFailedExecutor ( agentId . value , failedId ) |
def get_system_uptime_input_rbridge_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_system_uptime = ET . Element ( "get_system_uptime" )
config = get_system_uptime
input = ET . SubElement ( get_system_uptime , "input" )
rbridge_id = ET . SubElement ( input , "rbridge-id" )
rbridge_id . text = kwargs . pop ( 'rbridge_id' )
callback = kwargs . pop ( 'callback' , se... |
def crab_factory ( ** kwargs ) :
'''Factory that generates a CRAB client .
A few parameters will be handled by the factory , other parameters will
be passed on to the client .
: param wsdl : ` Optional . ` Allows overriding the default CRAB wsdl url .
: param proxy : ` Optional . ` A dictionary of proxy inf... | if 'wsdl' in kwargs :
wsdl = kwargs [ 'wsdl' ]
del kwargs [ 'wsdl' ]
else :
wsdl = "http://crab.agiv.be/wscrab/wscrab.svc?wsdl"
log . info ( 'Creating CRAB client with wsdl: %s' , wsdl )
c = Client ( wsdl , ** kwargs )
return c |
def headloss_gen ( Area , Vel , PerimWetted , Length , KMinor , Nu , PipeRough ) :
"""Return the total head lossin the general case .
Total head loss is a combination of major and minor losses .
This equation applies to both laminar and turbulent flows .""" | # Inputs do not need to be checked here because they are checked by
# functions this function calls .
return ( headloss_exp_general ( Vel , KMinor ) . magnitude + headloss_fric_general ( Area , PerimWetted , Vel , Length , Nu , PipeRough ) . magnitude ) |
def _grouped ( input_type , output_type , base_class , output_type_method ) :
"""Define a user - defined function that is applied per group .
Parameters
input _ type : List [ ibis . expr . datatypes . DataType ]
A list of the types found in : mod : ` ~ ibis . expr . datatypes ` . The
length of this list mus... | def wrapper ( func ) :
funcsig = valid_function_signature ( input_type , func )
UDAFNode = type ( func . __name__ , ( base_class , ) , { 'signature' : sig . TypeSignature . from_dtypes ( input_type ) , 'output_type' : output_type_method ( output_type ) , } , )
# An execution rule for a simple aggregate node... |
def iteritems ( self , pipe = None ) :
"""Return an iterator over the dictionary ' s ` ` ( key , value ) ` ` pairs .""" | pipe = self . redis if pipe is None else pipe
for k , v in self . _data ( pipe ) . items ( ) :
yield k , self . cache . get ( k , v ) |
def write ( filename , headers , dcols , data , headerlines = [ ] , header_char = 'H' , sldir = '.' , sep = ' ' , trajectory = False , download = False ) :
'''Method for writeing Ascii files .
Note the attribute name at position i in dcols will be associated
with the column data at index i in data . Also the n... | if sldir . endswith ( os . sep ) :
filename = str ( sldir ) + str ( filename )
else :
filename = str ( sldir ) + os . sep + str ( filename )
tmp = [ ]
# temp variable
lines = [ ]
# list of the data lines
lengthList = [ ]
# list of the longest element ( data or column name )
# in each column
if os . path . exist... |
async def create ( source_id : str ) :
"""Create a connection object , represents a single endpoint and can be used for sending and receiving
credentials and proofs
: param source _ id : Institution ' s unique ID for the connection
: return : connection object
Example :
connection = await Connection . cre... | constructor_params = ( source_id , )
c_source_id = c_char_p ( source_id . encode ( 'utf-8' ) )
c_params = ( c_source_id , )
return await Connection . _create ( "vcx_connection_create" , constructor_params , c_params ) |
def resample ( self , sampling_rate = None , variables = None , force_dense = False , in_place = False , kind = 'linear' ) :
'''Resample all dense variables ( and optionally , sparse ones ) to the
specified sampling rate .
Args :
sampling _ rate ( int , float ) : Target sampling rate ( in Hz ) . If None ,
u... | # Store old sampling rate - based variables
sampling_rate = sampling_rate or self . sampling_rate
_variables = { }
for name , var in self . variables . items ( ) :
if variables is not None and name not in variables :
continue
if isinstance ( var , SparseRunVariable ) :
if force_dense and is_nume... |
def add_service ( self , zeroconf , srv_type , srv_name ) :
"""Method called when a new Zeroconf client is detected .
Return True if the zeroconf client is a Glances server
Note : the return code will never be used""" | if srv_type != zeroconf_type :
return False
logger . debug ( "Check new Zeroconf server: %s / %s" % ( srv_type , srv_name ) )
info = zeroconf . get_service_info ( srv_type , srv_name )
if info :
new_server_ip = socket . inet_ntoa ( info . address )
new_server_port = info . port
# Add server to the globa... |
def get_mac_address_table_input_request_type_get_next_request_last_mac_address_details_last_mac_type ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_mac_address_table = ET . Element ( "get_mac_address_table" )
config = get_mac_address_table
input = ET . SubElement ( get_mac_address_table , "input" )
request_type = ET . SubElement ( input , "request-type" )
get_next_request = ET . SubElement ( request_type , "get-next-request" ... |
def _get_zoom_mat ( sw : float , sh : float , c : float , r : float ) -> AffineMatrix :
"` sw ` , ` sh ` scale width , height - ` c ` , ` r ` focus col , row ." | return [ [ sw , 0 , c ] , [ 0 , sh , r ] , [ 0 , 0 , 1. ] ] |
def decodeTagAttributes ( self , text ) :
"""docstring for decodeTagAttributes""" | attribs = { }
if text . strip ( ) == u'' :
return attribs
scanner = _attributePat . scanner ( text )
match = scanner . search ( )
while match :
key , val1 , val2 , val3 , val4 = match . groups ( )
value = val1 or val2 or val3 or val4
if value :
value = _space . sub ( u' ' , value ) . strip ( )
... |
def postal_code ( random = random , * args , ** kwargs ) :
"""Produce something that vaguely resembles a postal code
> > > mock _ random . seed ( 0)
> > > postal _ code ( random = mock _ random )
' b0b 0c0'
> > > postal _ code ( random = mock _ random , capitalize = True )
' E0E 0F0'
> > > postal _ code... | return random . choice ( [ "{letter}{number}{letter} {other_number}{other_letter}{other_number}" , "{number}{other_number}{number}{number}{other_number}" , "{number}{letter}{number}{other_number}{other_letter}" ] ) . format ( number = number ( random = random ) , other_number = number ( random = random ) , letter = let... |
def overlay_gateway_site_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
site = ET . SubElement ( overlay_gateway , "site" )
name = ET . SubElemen... |
def verifyRefimage ( refimage ) :
"""Verify that the value of refimage specified by the user points to an
extension with a proper WCS defined . It starts by making sure an extension gets
specified by the user when using a MEF file . The final check comes by looking
for a CD matrix in the WCS object itself . I... | valid = True
# start by trying to see whether the code can even find the file
if is_blank ( refimage ) :
valid = True
return valid
refroot , extroot = fileutil . parseFilename ( refimage )
if not os . path . exists ( refroot ) :
valid = False
return valid
# if a MEF has been specified , make sure extens... |
def nic_a_c ( msg ) :
"""Obtain NICa / c , navigation integrity category supplements a and c
Args :
msg ( string ) : 28 bytes hexadecimal message string
Returns :
( int , int ) : NICa and NICc number ( 0 or 1)""" | tc = typecode ( msg )
if tc != 31 :
raise RuntimeError ( "%s: Not a status operation message, expecting TC = 31" % msg )
msgbin = common . hex2bin ( msg )
nic_a = int ( msgbin [ 75 ] )
nic_c = int ( msgbin [ 51 ] )
return nic_a , nic_c |
def add ( self , item , overflow_policy = OVERFLOW_POLICY_OVERWRITE ) :
"""Adds the specified item to the tail of the Ringbuffer . If there is no space in the Ringbuffer , the action is
determined by overflow policy as : const : ` OVERFLOW _ POLICY _ OVERWRITE ` or : const : ` OVERFLOW _ POLICY _ FAIL ` .
: par... | return self . _encode_invoke ( ringbuffer_add_codec , value = self . _to_data ( item ) , overflow_policy = overflow_policy ) |
def google ( rest ) :
"Look up a phrase on google" | API_URL = 'https://www.googleapis.com/customsearch/v1?'
try :
key = pmxbot . config [ 'Google API key' ]
except KeyError :
return "Configure 'Google API key' in config"
# Use a custom search that searches everything normally
# http : / / stackoverflow . com / a / 11206266/70170
custom_search = '0048627626690746... |
def get_coordinate_variables ( ds ) :
'''Returns a list of variable names that identify as coordinate variables .
A coordinate variable is a netCDF variable with exactly one dimension . The
name of this dimension must be equivalent to the variable name .
From CF § 1.2 Terminology
It is a one - dimensional v... | coord_vars = [ ]
for dimension in ds . dimensions :
if dimension in ds . variables :
if ds . variables [ dimension ] . dimensions == ( dimension , ) :
coord_vars . append ( dimension )
return coord_vars |
def get_releases ( data , ** kwargs ) :
"""Gets all releases from pypi meta data .
: param data : dict , meta data
: return : list , str releases""" | if "versions" in data :
return sorted ( data [ "versions" ] . keys ( ) , key = lambda v : parse ( v ) , reverse = True )
return [ ] |
def add_ring ( self , ring ) :
"""Adds a ring to _ rings if not already existing""" | if ring not in self . _rings and isinstance ( ring , RingDing0 ) :
self . _rings . append ( ring ) |
def get_persistent_boot_device ( self ) :
"""Get current persistent boot device set for the host
: returns : persistent boot device for the system
: raises : IloError , on an error from iLO .""" | boot_string = None
if not self . persistent_boot_config_order or not self . boot_sources :
msg = ( 'Boot sources or persistent boot config order not found' )
LOG . debug ( msg )
raise exception . IloError ( msg )
preferred_boot_device = self . persistent_boot_config_order [ 0 ]
for boot_source in self . boo... |
def get_uri ( self ) :
"""Returns a URI formatted representation of the host , including all
of it ' s attributes except for the name . Uses the
address , not the name of the host to build the URI .
: rtype : str
: return : A URI .""" | url = Url ( )
url . protocol = self . get_protocol ( )
url . hostname = self . get_address ( )
url . port = self . get_tcp_port ( )
url . vars = dict ( ( k , to_list ( v ) ) for ( k , v ) in list ( self . get_all ( ) . items ( ) ) if isinstance ( v , str ) or isinstance ( v , list ) )
if self . account :
url . user... |
def get_volumes_for_instance ( self , arg , device = None ) :
"""Return all EC2 Volume objects attached to ` ` arg ` ` instance name or ID .
May specify ` ` device ` ` to limit to the ( single ) volume attached as that
device .""" | instance = self . get ( arg )
filters = { 'attachment.instance-id' : instance . id }
if device is not None :
filters [ 'attachment.device' ] = device
return self . get_all_volumes ( filters = filters ) |
def do_ranges_intersect ( begin , end , old_begin , old_end ) :
"""Determine if the two given memory address ranges intersect .
@ type begin : int
@ param begin : Start address of the first range .
@ type end : int
@ param end : End address of the first range .
@ type old _ begin : int
@ param old _ beg... | return ( old_begin <= begin < old_end ) or ( old_begin < end <= old_end ) or ( begin <= old_begin < end ) or ( begin < old_end <= end ) |
def round_to ( dt , hour , minute , second , mode = "round" ) :
"""Round the given datetime to specified hour , minute and second .
: param mode : ' floor ' or ' ceiling '
. . versionadded : : 0.0.5
message
* * 中文文档 * *
将给定时间对齐到最近的一个指定了小时 , 分钟 , 秒的时间上 。""" | mode = mode . lower ( )
if mode not in _round_to_options :
raise ValueError ( "'mode' has to be one of %r!" % list ( _round_to_options . keys ( ) ) )
return _round_to_options [ mode ] ( dt , hour , minute , second ) |
def execute_flow ( self , custom_command = "" , is_config = False ) :
"""Execute flow which run custom command on device
: param custom _ command : the command to execute on device
: param is _ config : if True then run command in configuration mode
: return : command execution output""" | responses = [ ]
if isinstance ( custom_command , str ) :
commands = [ custom_command ]
elif isinstance ( custom_command , tuple ) :
commands = list ( custom_command )
else :
commands = custom_command
if is_config :
mode = self . _cli_handler . config_mode
if not mode :
raise Exception ( self... |
def get_rows ( self , match , fields = None , limit = 10 , sampling = None ) :
"""Returns raw rows that matches given query
: arg match : query to be run against Kibana log messages ( ex . { " @ message " : " Foo Bar DB queries " } )
: type fields list [ str ] or None
: arg limit : the number of results ( def... | query = { "match" : match , }
return self . _search ( query , fields , limit , sampling ) |
def handleEvent ( self , eventObj ) :
"""This method should be called every time through the main loop .
Returns :
False - if no event happens .
True - if the user clicks the animation to start it playing .""" | if not self . visible :
return
if not self . isEnabled :
return False
if eventObj . type != MOUSEBUTTONDOWN : # The animation only cares about a mouse down event
return False
eventPointInAnimationRect = self . rect . collidepoint ( eventObj . pos )
if not eventPointInAnimationRect : # clicked outside of ani... |
def search ( self , scope , search , ** kwargs ) :
"""Search GitLab resources matching the provided string . '
Args :
scope ( str ) : Scope of the search
search ( str ) : Search string
* * kwargs : Extra options to send to the server ( e . g . sudo )
Raises :
GitlabAuthenticationError : If authenticatio... | data = { 'scope' : scope , 'search' : search }
return self . http_list ( '/search' , query_data = data , ** kwargs ) |
def get_function_by_path ( dotted_function_module_path ) :
"""Returns the function for a given path ( e . g . ' my _ app . my _ module . my _ function ' ) .""" | # Separate the module path from the function name .
module_path , function_name = tuple ( dotted_function_module_path . rsplit ( '.' , 1 ) )
module = import_module ( module_path )
return getattr ( module , function_name ) |
def add_url_rule ( self , rule , endpoint = None , view_func = None , ** options ) :
"""Like : meth : ` ~ flask . Flask . add _ url _ rule ` but for a blueprint . The endpoint for
the : func : ` url _ for ` function is prefixed with the name of the blueprint .
Overridden to allow dots in endpoint names""" | self . record ( lambda s : s . add_url_rule ( rule , endpoint , view_func , register_with_babel = False , ** options ) ) |
def refresh_modules ( self , module_string = None , exact = True ) :
"""Update modules .
if module _ string is None all modules are refreshed
if module _ string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed .
If a module is an i3statu... | if not module_string :
if time . time ( ) > ( self . last_refresh_ts + 0.1 ) :
self . last_refresh_ts = time . time ( )
else : # rate limiting
return
update_i3status = False
for name , module in self . output_modules . items ( ) :
if ( module_string is None or ( exact and name == module_stri... |
def generate_symbolic_cmd_line_arg ( state , max_length = 1000 ) :
"""Generates a new symbolic cmd line argument string .
: return : The string reference .""" | str_ref = SimSootValue_StringRef ( state . memory . get_new_uuid ( ) )
str_sym = StringS ( "cmd_line_arg" , max_length )
state . solver . add ( str_sym != StringV ( "" ) )
state . memory . store ( str_ref , str_sym )
return str_ref |
def nodes_callback ( self , data ) :
"""Callback for nodes with tags""" | for node_id , tags , coords in data : # Discard the coords because they go into add _ coords
self . nodes [ node_id ] = tags |
def order_by_json_path ( self , json_path , language_code = None , order = 'asc' ) :
"""Orders a queryset by the value of the specified ` json _ path ` .
More about the ` # > > ` operator and the ` json _ path ` arg syntax :
https : / / www . postgresql . org / docs / current / static / functions - json . html ... | language_code = ( language_code or self . _language_code or self . get_language_key ( language_code ) )
json_path = '{%s,%s}' % ( language_code , json_path )
# Our jsonb field is named ` translations ` .
raw_sql_expression = RawSQL ( "translations#>>%s" , ( json_path , ) )
if order == 'desc' :
raw_sql_expression = ... |
def write ( self , data ) :
"""Send raw bytes to the instrument .
: param data : bytes to be sent to the instrument
: type data : bytes""" | begin , end , size = 0 , 0 , len ( data )
bytes_sent = 0
raw_write = super ( USBRawDevice , self ) . write
while not end > size :
begin = end
end = begin + self . RECV_CHUNK
bytes_sent += raw_write ( data [ begin : end ] )
return bytes_sent |
def write ( self , arg ) :
"""Write a string or bytes object to the buffer""" | if isinstance ( arg , str ) :
arg = arg . encode ( self . encoding )
return self . _buffer . write ( arg ) |
def remove_columns ( self , column_names , inplace = False ) :
"""Returns an SFrame with one or more columns removed .
If inplace = = False ( default ) this operation does not modify the
current SFrame , returning a new SFrame .
If inplace = = True , this operation modifies the current
SFrame , returning se... | column_names = list ( column_names )
existing_columns = dict ( ( k , i ) for i , k in enumerate ( self . column_names ( ) ) )
for name in column_names :
if name not in existing_columns :
raise KeyError ( 'Cannot find column %s' % name )
# Delete it going backwards so we don ' t invalidate indices
deletion_i... |
def sf ( self , lrt ) :
"""computes the survival function of a mixture of a chi - squared random variable of degree
0 and a scaled chi - squared random variable of degree d""" | _lrt = SP . copy ( lrt )
_lrt [ lrt < self . tol ] = 0
pv = self . mixture * STATS . chi2 . sf ( _lrt / self . scale , self . dof )
return pv |
def partition ( src , key = None ) :
"""No relation to : meth : ` str . partition ` , ` ` partition ` ` is like
: func : ` bucketize ` , but for added convenience returns a tuple of
` ` ( truthy _ values , falsy _ values ) ` ` .
> > > nonempty , empty = partition ( [ ' ' , ' ' , ' hi ' , ' ' , ' bye ' ] )
>... | bucketized = bucketize ( src , key )
return bucketized . get ( True , [ ] ) , bucketized . get ( False , [ ] ) |
def histogram2d ( data1 , data2 , bins = None , * args , ** kwargs ) :
"""Facade function to create 2D histogram using dask .""" | # TODO : currently very unoptimized ! for non - dasks
import dask
if "axis_names" not in kwargs :
if hasattr ( data1 , "name" ) and hasattr ( data2 , "name" ) :
kwargs [ "axis_names" ] = [ data1 . name , data2 . name ]
if not hasattr ( data1 , "dask" ) :
data1 = dask . array . from_array ( data1 , chunk... |
def parseString ( string , uri = None ) :
"""Read an XML document provided as a byte string , and return a
: mod : ` lxml . etree ` document . String cannot be a Unicode string .
Base _ uri should be provided for the calculation of relative URIs .""" | return etree . fromstring ( string , parser = _get_xmlparser ( ) , base_url = uri ) |
def knot_insertion ( degree , knotvector , ctrlpts , u , ** kwargs ) :
"""Computes the control points of the rational / non - rational spline after knot insertion .
Part of Algorithm A5.1 of The NURBS Book by Piegl & Tiller , 2nd Edition .
Keyword Arguments :
* ` ` num ` ` : number of knot insertions . * Defa... | # Get keyword arguments
num = kwargs . get ( 'num' , 1 )
# number of knot insertions
s = kwargs . get ( 's' , find_multiplicity ( u , knotvector ) )
# multiplicity
k = kwargs . get ( 'span' , find_span_linear ( degree , knotvector , len ( ctrlpts ) , u ) )
# knot span
# Initialize variables
np = len ( ctrlpts )
nq = np... |
def render_pdf_file_to_image_files_pdftoppm_ppm ( pdf_file_name , root_output_file_path , res_x = 150 , res_y = 150 , extra_args = None ) :
"""Use the pdftoppm program to render a PDF file to . png images . The
root _ output _ file _ path is prepended to all the output files , which have numbers
and extensions ... | if extra_args is None :
extra_args = [ ]
if not pdftoppm_executable :
init_and_test_pdftoppm_executable ( prefer_local = False , exit_on_fail = True )
if old_pdftoppm_version : # We only have - r , not - rx and - ry .
command = [ pdftoppm_executable ] + extra_args + [ "-r" , res_x , pdf_file_name , root_out... |
def jpath_parse ( jpath ) :
"""Parse given JPath into chunks .
Returns list of dictionaries describing all of the JPath chunks .
: param str jpath : JPath to be parsed into chunks
: return : JPath chunks as list of dicts
: rtype : : py : class : ` list `
: raises JPathException : in case of invalid JPath ... | result = [ ]
breadcrumbs = [ ]
# Split JPath into chunks based on ' . ' character .
chunks = jpath . split ( '.' )
for chnk in chunks :
match = RE_JPATH_CHUNK . match ( chnk )
if match :
res = { }
# Record whole match .
res [ 'm' ] = chnk
# Record breadcrumb path .
breadc... |
def delete ( self , option ) :
"""Deletes an option if exists""" | if self . config is not None :
if option in self . config :
del self . config [ option ] |
def comparable ( self ) :
"""str : comparable representation of the path specification .""" | string_parts = [ ]
if self . location is not None :
string_parts . append ( 'location: {0:s}' . format ( self . location ) )
if self . part_index is not None :
string_parts . append ( 'part index: {0:d}' . format ( self . part_index ) )
if self . start_offset is not None :
string_parts . append ( 'start off... |
def random_population ( dna_size , pop_size , tune_params ) :
"""create a random population""" | population = [ ]
for _ in range ( pop_size ) :
dna = [ ]
for i in range ( dna_size ) :
dna . append ( random_val ( i , tune_params ) )
population . append ( dna )
return population |
def _determine_impact_coordtransform ( self , deltaAngleTrackImpact , nTrackChunksImpact , timpact , impact_angle ) :
"""Function that sets up the transformation between ( x , v ) and ( O , theta )""" | # Integrate the progenitor backward to the time of impact
self . _gap_progenitor_setup ( )
# Sign of delta angle tells us whether the impact happens to the
# leading or trailing arm , self . _ sigMeanSign contains this info
if impact_angle > 0. :
self . _gap_leading = True
else :
self . _gap_leading = False
if ... |
def lookup_int ( values , name = None ) :
"""Lookup field which transforms the result into an integer .
: param values : values allowed
: param name : name for the field
: return : grammar for the lookup field""" | field = basic . lookup ( values , name )
field . addParseAction ( lambda l : int ( l [ 0 ] ) )
return field |
def configure_flair ( self , subreddit , flair_enabled = False , flair_position = 'right' , flair_self_assign = False , link_flair_enabled = False , link_flair_position = 'left' , link_flair_self_assign = False ) :
"""Configure the flair setting for the given subreddit .
: returns : The json response from the ser... | flair_enabled = 'on' if flair_enabled else 'off'
flair_self_assign = 'on' if flair_self_assign else 'off'
if not link_flair_enabled :
link_flair_position = ''
link_flair_self_assign = 'on' if link_flair_self_assign else 'off'
data = { 'r' : six . text_type ( subreddit ) , 'flair_enabled' : flair_enabled , 'flair_po... |
def solve_sweep_structure ( self , structures , sweep_param_list , filename = "structure_n_effs.dat" , plot = True , x_label = "Structure number" , fraction_mode_list = [ ] , ) :
"""Find the modes of many structures .
Args :
structures ( list ) : A list of ` Structures ` to find the modes
of .
sweep _ param... | n_effs = [ ]
mode_types = [ ]
fractions_te = [ ]
fractions_tm = [ ]
for s in tqdm . tqdm ( structures , ncols = 70 ) :
self . solve ( s )
n_effs . append ( np . real ( self . n_effs ) )
mode_types . append ( self . _get_mode_types ( ) )
fractions_te . append ( self . fraction_te )
fractions_tm . app... |
def histogram ( data , ** kwargs ) :
"""Function to create histogram , e . g . for voltages or currents .
Parameters
data : : pandas : ` pandas . DataFrame < dataframe > `
Data to be plotted , e . g . voltage or current ( ` v _ res ` or ` i _ res ` from
: class : ` edisgo . grid . network . Results ` ) . In... | timeindex = kwargs . get ( 'timeindex' , None )
directory = kwargs . get ( 'directory' , None )
filename = kwargs . get ( 'filename' , None )
title = kwargs . get ( 'title' , "" )
x_label = kwargs . get ( 'x_label' , "" )
y_label = kwargs . get ( 'y_label' , "" )
color = kwargs . get ( 'color' , None )
alpha = kwargs .... |
def set_sorting ( self , flag ) :
"""Enable result sorting after search is complete .""" | self . sorting [ 'status' ] = flag
self . header ( ) . setSectionsClickable ( flag == ON ) |
def get_pressure ( self ) :
"""Returns the pressure in Millibars""" | self . _init_pressure ( )
# Ensure pressure sensor is initialised
pressure = 0
data = self . _pressure . pressureRead ( )
if ( data [ 0 ] ) : # Pressure valid
pressure = data [ 1 ]
return pressure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.