signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def show_firmware_version_output_show_firmware_version_switchid ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_firmware_version = ET . Element ( "show_firmware_version" )
config = show_firmware_version
output = ET . SubElement ( show_firmware_version , "output" )
show_firmware_version = ET . SubElement ( output , "show-firmware-version" )
switchid = ET . SubElement ( show_firmware_version... |
def reorient_wf ( name = 'ReorientWorkflow' ) :
"""A workflow to reorient images to ' RPI ' orientation""" | workflow = pe . Workflow ( name = name )
inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_file' ] ) , name = 'inputnode' )
outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'out_file' ] ) , name = 'outputnode' )
deoblique = pe . Node ( afni . Refit ( deoblique = True ) , name = 'deoblique' )... |
async def stepper_config ( self , steps_per_revolution , stepper_pins ) :
"""Configure stepper motor prior to operation .
This is a FirmataPlus feature .
: param steps _ per _ revolution : number of steps per motor revolution
: param stepper _ pins : a list of control pin numbers - either 4 or 2
: returns :... | data = [ PrivateConstants . STEPPER_CONFIGURE , steps_per_revolution & 0x7f , ( steps_per_revolution >> 7 ) & 0x7f ]
for pin in range ( len ( stepper_pins ) ) :
data . append ( stepper_pins [ pin ] )
await self . _send_sysex ( PrivateConstants . STEPPER_DATA , data ) |
def set_value ( self , value ) :
"""Set value of the checkbox .
Parameters
value : bool
value for the checkbox""" | if value :
self . setCheckState ( Qt . Checked )
else :
self . setCheckState ( Qt . Unchecked ) |
def parse_cookies_str ( cookies ) :
"""parse cookies str to dict
: param cookies : cookies str
: type cookies : str
: return : cookie dict
: rtype : dict""" | cookie_dict = { }
for record in cookies . split ( ";" ) :
key , value = record . strip ( ) . split ( "=" , 1 )
cookie_dict [ key ] = value
return cookie_dict |
def one ( self ) :
"""Shows one row of the dataframe and the field
names wiht count
: return : a pandas dataframe
: rtype : pd . DataFrame
: example : ` ` ds . one ( ) ` `""" | try :
return self . show ( 1 )
except Exception as e :
self . err ( e , self . one , "Can not display dataframe" ) |
def parse_single_ad ( ad , global_names , common_words , args = { } ) :
"""An example extraction of a Backpage ad , with the following parameters :
ad - > A dict representing an ad that is scraped as such :
ad = items . BackpageScrapeItem (
backpage _ id = response . url . split ( ' . ' ) [ 0 ] . split ( ' / ... | multiple_phones = False if 'multiple_phones' not in args else args [ 'multiple_phones' ]
item = { }
# Backpage category
# # 1 - - > FemaleEscorts
# # 2 - - > BodyRubs
# # 3 - - > Dating section ( after 1/9/17 Backpage shutdown of FemaleEscorts and BodyRubs )
# # 4 - - > TherapeuticMassage section ( 1/23/17 partial begi... |
def clear ( self ) :
"""Removes all pending Jobs from the queue and return them in a list . This
method does * * no * * t call # Job . cancel ( ) on any of the jobs . If you want
that , use # cancel _ all ( ) or call it manually .""" | with synchronized ( self . __queue ) :
jobs = self . __queue . snapshot ( )
self . __queue . clear ( )
return jobs |
def del_bridge_port ( name , port ) :
'''Delete a port from the named openvswitch bridge''' | log ( 'Deleting port {} from bridge {}' . format ( port , name ) )
subprocess . check_call ( [ "ovs-vsctl" , "--" , "--if-exists" , "del-port" , name , port ] )
subprocess . check_call ( [ "ip" , "link" , "set" , port , "down" ] )
subprocess . check_call ( [ "ip" , "link" , "set" , port , "promisc" , "off" ] ) |
def _add_assertion_provenance ( self , assoc_id , evidence_line_bnode ) :
"""Add assertion level provenance , currently always IMPC
: param assoc _ id :
: param evidence _ line _ bnode :
: return :""" | provenance_model = Provenance ( self . graph )
model = Model ( self . graph )
assertion_bnode = self . make_id ( "assertion{0}{1}" . format ( assoc_id , self . localtt [ 'IMPC' ] ) , '_' )
model . addIndividualToGraph ( assertion_bnode , None , self . globaltt [ 'assertion' ] )
provenance_model . add_assertion ( assert... |
def geom2localortho ( geom ) :
"""Convert existing geom to local orthographic projection
Useful for local cartesian distance / area calculations""" | cx , cy = geom . Centroid ( ) . GetPoint_2D ( )
lon , lat , z = cT_helper ( cx , cy , 0 , geom . GetSpatialReference ( ) , wgs_srs )
local_srs = localortho ( lon , lat )
local_geom = geom_dup ( geom )
geom_transform ( local_geom , local_srs )
return local_geom |
def update ( gandi , ip , reverse , background ) :
"""Update an ip .""" | if not reverse :
return
return gandi . ip . update ( ip , { 'reverse' : reverse } , background ) |
def sql ( self , stmt , parameters = None , bulk_parameters = None ) :
"""Execute SQL stmt against the crate server .""" | if stmt is None :
return None
data = _create_sql_payload ( stmt , parameters , bulk_parameters )
logger . debug ( 'Sending request to %s with payload: %s' , self . path , data )
content = self . _json_request ( 'POST' , self . path , data = data )
logger . debug ( "JSON response for stmt(%s): %s" , stmt , content )... |
def merge_wheres ( self , wheres , bindings ) :
"""Merge a list of where clauses and bindings
: param wheres : A list of where clauses
: type wheres : list
: param bindings : A list of bindings
: type bindings : list
: rtype : None""" | self . wheres = self . wheres + wheres
self . _bindings [ 'where' ] = self . _bindings [ 'where' ] + bindings |
def closest_timezone_at ( self , * , lat , lng , delta_degree = 1 , exact_computation = False , return_distances = False , force_evaluation = False ) :
"""This function searches for the closest polygon in the surrounding shortcuts .
Make sure that the point does not lie within a polygon ( for that case the algori... | def exact_routine ( polygon_nr ) :
coords = self . coords_of ( polygon_nr )
nr_points = len ( coords [ 0 ] )
empty_array = empty ( [ 2 , nr_points ] , dtype = DTYPE_FORMAT_F_NUMPY )
return distance_to_polygon_exact ( lng , lat , nr_points , coords , empty_array )
def normal_routine ( polygon_nr ) :
... |
def get_alias_table ( ) :
"""Get the current alias table .""" | try :
alias_table = get_config_parser ( )
alias_table . read ( azext_alias . alias . GLOBAL_ALIAS_PATH )
return alias_table
except Exception : # pylint : disable = broad - except
return get_config_parser ( ) |
def unbuffered_write ( self , buf ) :
"""Performs an unbuffered write , the default unless socket . send does
not send everything , in which case an unbuffered write is done and the
write method is set to be a buffered write until the buffer is empty
once again .
buf - - bytes to send""" | if self . closed :
raise ConnectionClosed ( )
result = 0
try :
result = self . sock . send ( buf )
except EnvironmentError as e : # if the socket is simply backed up ignore the error
if e . errno != errno . EAGAIN :
self . _close ( e )
return
# when the socket buffers are full / backed up th... |
def serialize_to_dict ( dictionary ) :
'''Make a json - serializable dictionary from input dictionary by converting
non - serializable data types such as numpy arrays .''' | retval = { }
for k , v in dictionary . items ( ) :
if isinstance ( v , dict ) :
retval [ k ] = serialize_to_dict ( v )
else : # This is when custom serialization happens
if isinstance ( v , np . ndarray ) :
if v . dtype == 'float64' : # We don ' t support float64 on js side
... |
def predict ( self , peptides , alleles = None , allele = None , throw = True , centrality_measure = DEFAULT_CENTRALITY_MEASURE ) :
"""Predict nM binding affinities .
If multiple predictors are available for an allele , the predictions are
the geometric means of the individual model predictions .
One of ' all... | df = self . predict_to_dataframe ( peptides = peptides , alleles = alleles , allele = allele , throw = throw , include_percentile_ranks = False , include_confidence_intervals = False , centrality_measure = centrality_measure , )
return df . prediction . values |
def acknowledge_alarm ( self , alarm , comment = None ) :
"""Acknowledges a specific alarm associated with a parameter .
: param alarm : Alarm instance
: type alarm : : class : ` . Alarm `
: param str comment : Optional comment to associate with the state
change .""" | url = '/processors/{}/{}/parameters{}/alarms/{}' . format ( self . _instance , self . _processor , alarm . name , alarm . sequence_number )
req = rest_pb2 . EditAlarmRequest ( )
req . state = 'acknowledged'
if comment is not None :
req . comment = comment
self . _client . put_proto ( url , data = req . SerializeToS... |
def bed_writer ( parser , keep , extract , args ) :
"""Writes BED / BIM / FAM files .""" | # The output bed and bim file
bim_fn = args . output + ".bim"
with open ( bim_fn , "w" ) as bim , PyPlink ( args . output , "w" ) as bed : # Getting the samples
samples = np . array ( parser . get_samples ( ) , dtype = str )
k = _get_sample_select ( samples = samples , keep = keep )
# Writing the FAM file
... |
def processNickList ( nicks , platforms = None , rutaDescarga = "./" , avoidProcessing = True , avoidDownload = True , nThreads = 12 , verbosity = 1 , logFolder = "./logs" ) :
"""Process a list of nicks to check whether they exist .
This method receives as a parameter a series of nicks and verifies whether
thos... | if platforms == None :
platforms = platform_selection . getAllPlatformNames ( "usufy" )
# Defining the output results variable
res = [ ]
# Processing the whole list of terms . . .
for nick in nicks : # If the process is executed by the current app , we use the Processes . It is faster than pools .
if nThreads <... |
def send ( self , message ) :
"""Send message to device .""" | serialized = message . SerializeToString ( )
log_binary ( _LOGGER , '>> Send' , Data = serialized )
if self . _chacha :
serialized = self . _chacha . encrypt ( serialized )
log_binary ( _LOGGER , '>> Send' , Encrypted = serialized )
data = write_variant ( len ( serialized ) ) + serialized
self . _transport . wr... |
def valid_web_plugin ( self , plugin ) :
"""Validate a web plugin , ensuring it is a web plugin and has the
necessary fields present .
` plugin ` is a subclass of scruffy ' s Plugin class .""" | if ( issubclass ( plugin , WebPlugin ) and hasattr ( plugin , 'plugin_type' ) and plugin . plugin_type == 'web' and hasattr ( plugin , 'name' ) and plugin . name != None ) :
return True
return False |
def list ( self , session = None ) :
"""List the names of all files stored in this instance of
: class : ` GridFS ` .
: Parameters :
- ` session ` ( optional ) : a
: class : ` ~ pymongo . client _ session . ClientSession `
. . versionchanged : : 3.6
Added ` ` session ` ` parameter .
. . versionchanged... | # With an index , distinct includes documents with no filename
# as None .
return [ name for name in self . __files . distinct ( "filename" , session = session ) if name is not None ] |
def get_kx ( N , dx ) :
"""GET _ KX
: summary : Returns the frequencies to be used with FFT analysis
: parameter N : number of samples in data
: parameter dx : sampling step
: return : Returns
* k : frequency
* L : length
* imx : index of maximum frequency ( for separating positive and negative freque... | # to work with dimensional axes
L = N * dx
# Odd or even
odd = N & 1 and True or False
# Get frequency & wavenumber
k = ft . fftfreq ( N , d = dx )
# k = f * N
imx = ( N - 1 ) / 2 if odd else N / 2
# Maximum frequency
# Convert into frequencies
# k / = L
return k , L , imx |
def get_instance ( self , payload ) :
"""Build an instance of DependentHostedNumberOrderInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . preview . hosted _ numbers . authorization _ document . dependent _ hosted _ number _ order . DependentHostedNumberOrderInstance
: r... | return DependentHostedNumberOrderInstance ( self . _version , payload , signing_document_sid = self . _solution [ 'signing_document_sid' ] , ) |
def _dims_in_order ( self , dimension_order ) :
''': param list dimension _ order : A list of axes
: rtype : bool
: return : Returns True if the dimensions are in order U * , T , Z , Y , X ,
False otherwise''' | regx = regex . compile ( r'^[^TZYX]*T?Z?Y?X?$' )
dimension_string = '' . join ( dimension_order )
return regx . match ( dimension_string ) is not None |
def build_logger_tree ( ) :
"""Build a DFS tree representing the logger layout .
Adapted with much appreciation from : https : / / github . com / brandon - rhodes / logging _ tree""" | cache = { }
tree = make_logger_node ( "" , root )
for name , logger in sorted ( root . manager . loggerDict . items ( ) ) :
if "." in name :
parent_name = "." . join ( name . split ( "." ) [ : - 1 ] )
parent = cache [ parent_name ]
else :
parent = tree
cache [ name ] = make_logger_no... |
def _enqueue_function ( self ) :
"""Internal method used by AddEventHandler .
Provides functionality of enqueue / dequeue of the events and triggering callbacks .""" | from UcsBase import _GenericMO , UcsUtils , WriteObject
myThread = self . _enqueueThread
self . _enqueueThreadSignal . acquire ( )
try :
xmlQuery = '<eventSubscribe cookie="' + self . _cookie + '"/>'
uri = self . Uri ( ) + '/nuova'
req = urllib2 . Request ( url = uri , data = xmlQuery )
self . _watchWeb... |
def manage_actor ( self , monitor , actor , stop = False ) :
'''If an actor failed to notify itself to the arbiter for more than
the timeout , stop the actor .
: param actor : the : class : ` Actor ` to manage .
: param stop : if ` ` True ` ` , stop the actor .
: return : if the actor is alive 0 if it is no... | if not monitor . is_running ( ) :
stop = True
if not actor . is_alive ( ) :
if not actor . should_be_alive ( ) and not stop :
return 1
actor . join ( )
self . _remove_monitored_actor ( monitor , actor )
return 0
timeout = None
started_stopping = bool ( actor . stopping_start )
# if started _... |
def configure_uploadfor ( self , ns , definition ) :
"""Register an upload - for relation endpoint .
The definition ' s func should be an upload function , which must :
- accept kwargs for path data and query string parameters
- accept a list of tuples of the form ( formname , tempfilepath , filename )
- op... | upload_for = self . create_upload_func ( ns , definition , ns . relation_path , Operation . UploadFor )
upload_for . __doc__ = "Upload a {} for a {}" . format ( ns . subject_name , ns . object_name ) |
def get_template ( filename_or_string , is_string = False ) :
'''Gets a jinja2 ` ` Template ` ` object for the input filename or string , with caching
based on the filename of the template , or the SHA1 of the input string .''' | # Cache against string sha or just the filename
cache_key = sha1_hash ( filename_or_string ) if is_string else filename_or_string
if cache_key in TEMPLATES :
return TEMPLATES [ cache_key ]
if is_string : # Set the input string as our template
template_string = filename_or_string
else : # Load template data into... |
def _num_players ( self ) :
"""Compute number of players , both human and computer .""" | self . _player_num = 0
self . _computer_num = 0
for player in self . _header . scenario . game_settings . player_info :
if player . type == 'human' :
self . _player_num += 1
elif player . type == 'computer' :
self . _computer_num += 1 |
def add_field ( self , name , script , lang = None , params = None , ignore_failure = False ) :
"""Add a field to script _ fields""" | data = { }
if lang :
data [ "lang" ] = lang
if script :
data [ 'script' ] = script
else :
raise ScriptFieldsError ( "Script is required for script_fields definition" )
if params :
if isinstance ( params , dict ) :
if len ( params ) :
data [ 'params' ] = params
else :
rais... |
def wrap ( self , LayoutClass , * args , ** kwargs ) :
"""Wraps every layout object pointed in ` self . slice ` under a ` LayoutClass ` instance with
` args ` and ` kwargs ` passed .""" | def wrap_object ( layout_object , j ) :
layout_object . fields [ j ] = self . wrapped_object ( LayoutClass , layout_object . fields [ j ] , * args , ** kwargs )
self . pre_map ( wrap_object ) |
def exists ( self ) :
"""Retrieves whether the document exists in the remote database or not .
: returns : True if the document exists in the remote database ,
otherwise False""" | if '_id' not in self or self [ '_id' ] is None :
return False
resp = self . r_session . head ( self . document_url )
if resp . status_code not in [ 200 , 404 ] :
resp . raise_for_status ( )
return resp . status_code == 200 |
def incompatibilities_for ( self , package ) : # type : ( DependencyPackage ) - > List [ Incompatibility ]
"""Returns incompatibilities that encapsulate a given package ' s dependencies ,
or that it can ' t be safely selected .
If multiple subsequent versions of this package have the same
dependencies , this ... | if package . is_root ( ) :
dependencies = package . all_requires
else :
dependencies = package . requires
if not package . python_constraint . allows_all ( self . _package . python_constraint ) :
intersection = package . python_constraint . intersect ( package . dependency . transitive_python_constr... |
def add_property ( self , property_name , use_context = True ) :
"""Add simple property to schema
: param property _ name : str , property name
: param use _ context : bool , whether custom context should be used
: return : shiftschema . property . SimpleProperty""" | if self . has_property ( property_name ) :
err = 'Property "{}" already exists'
raise PropertyExists ( err . format ( property_name ) )
prop = SimpleProperty ( use_context = bool ( use_context ) )
self . properties [ property_name ] = prop
return prop |
def update ( self , data ) :
"""Updates the object information based on live data , if there were any changes made . Any changes will be
automatically applied to the object , but will not be automatically persisted . You must manually call
` db . session . add ( instance ) ` on the object .
Args :
data ( : ... | updated = False
if 'missing_tags' in data :
updated |= self . set_property ( 'missing_tags' , data [ 'missing_tags' ] )
if 'notes' in data :
updated |= self . set_property ( 'notes' , data [ 'notes' ] )
if 'state' in data :
updated |= self . set_property ( 'state' , data [ 'state' ] )
if 'last_alert' in dat... |
async def add ( self , device , recursive = None ) :
"""Mount or unlock the device depending on its type .
: param device : device object , block device path or mount path
: param bool recursive : recursively mount and unlock child devices
: returns : whether all attempted operations succeeded""" | device , created = await self . _find_device_losetup ( device )
if created and recursive is False :
return device
if device . is_filesystem :
success = await self . mount ( device )
elif device . is_crypto :
success = await self . unlock ( device )
if success and recursive :
await self . udisks ... |
def get_list_url ( self , kind_slug = None ) :
"""Get the list URL for this Work .
You can also pass a kind _ slug in ( e . g . ' movies ' ) and it will use that
instead of the Work ' s kind _ slug . ( Why ? Useful in views . Or tests of
views , at least . )""" | if kind_slug is None :
kind_slug = self . KIND_SLUGS [ self . kind ]
return reverse ( 'spectator:events:work_list' , kwargs = { 'kind_slug' : kind_slug } ) |
def _findRedundantProteins ( protToPeps , pepToProts , proteins = None ) :
"""Returns a set of proteins with redundant peptide evidence .
After removing the redundant proteins from the " protToPeps " and " pepToProts "
mapping , all remaining proteins have at least one unique peptide . The
remaining proteins ... | if proteins is None :
proteins = viewkeys ( protToPeps )
pepFrequency = _getValueCounts ( pepToProts )
protPepCounts = _getValueCounts ( protToPeps )
getCount = operator . itemgetter ( 1 )
getProt = operator . itemgetter ( 0 )
# TODO : quick and dirty solution
# NOTE : add a test for merged proteins
proteinTuples =... |
def main ( args = None ) :
"""Start application .""" | dlx = Downloader ( )
epilog = dlx . epilog ( )
options , arguments = parse ( args , epilog )
# create list of video files that don ' t have accompanying ' srt ' subtitles
targets = [ p for p in arguments if os . path . isfile ( p ) and not os . path . exists ( os . path . splitext ( p ) [ 0 ] + '.srt' ) ]
if not target... |
def create ( cls , location = None , storage_class = None , ** kwargs ) :
r"""Create a bucket .
: param location : Location of a bucket ( instance or name ) .
Default : Default location .
: param storage _ class : Storage class of a bucket .
Default : Default storage class .
: param \ * * kwargs : Keyword... | with db . session . begin_nested ( ) :
if location is None :
location = Location . get_default ( )
elif isinstance ( location , six . string_types ) :
location = Location . get_by_name ( location )
obj = cls ( default_location = location . id , default_storage_class = storage_class or curren... |
def GetList ( self ) :
"""Get Info on Current List
This is run in _ _ init _ _ so you don ' t
have to run it again .
Access from self . schema""" | # Build Request
soap_request = soap ( 'GetList' )
soap_request . add_parameter ( 'listName' , self . listName )
self . last_request = str ( soap_request )
# Send Request
response = self . _session . post ( url = self . _url ( 'Lists' ) , headers = self . _headers ( 'GetList' ) , data = str ( soap_request ) , verify = s... |
def conforms ( cntxt : Context , n : Node , S : ShExJ . Shape ) -> bool :
"""` 5.6.1 Schema Validation Requirement < http : / / shex . io / shex - semantics / # validation - requirement > ` _
A graph G is said to conform with a schema S with a ShapeMap m when :
Every , SemAct in the startActs of S has a success... | # return semActsSatisfied ( cntxt . schema . startActs , cntxt ) and \
# all ( reference _ of ( cntxt . schema , sa . shapeLabel ) is not None and
return True |
def incidental ( self ) :
"""Returns incidental properties .""" | result = [ p for p in self . lazy_properties if p . feature . incidental ]
result . extend ( self . incidental_ )
return result |
def merge ( cls , tables , fillna = False ) :
"""Merge a list of tables""" | cols = set ( itertools . chain ( * [ table . dtype . descr for table in tables ] ) )
tables_to_merge = [ ]
for table in tables :
missing_cols = cols - set ( table . dtype . descr )
if missing_cols :
if fillna :
n = len ( table )
n_cols = len ( missing_cols )
col_names... |
def _get_filesystem_path ( self , url_path , basedir = settings . MEDIA_ROOT ) :
"""Makes a filesystem path from the specified URL path""" | if url_path . startswith ( settings . MEDIA_URL ) :
url_path = url_path [ len ( settings . MEDIA_URL ) : ]
# strip media root url
return os . path . normpath ( os . path . join ( basedir , url2pathname ( url_path ) ) ) |
def _starting_consonants_only ( self , letters : list ) -> list :
"""Return a list of starting consonant positions .""" | for idx , letter in enumerate ( letters ) :
if not self . _contains_vowels ( letter ) and self . _contains_consonants ( letter ) :
return [ idx ]
if self . _contains_vowels ( letter ) :
return [ ]
if self . _contains_vowels ( letter ) and self . _contains_consonants ( letter ) :
retu... |
def reset ( self ) :
"""Resets the value of config item to its default value .""" | old_value = self . _value
old_raw_str_value = self . raw_str_value
self . _value = not_set
self . raw_str_value = not_set
new_value = self . _value
if old_value is not_set : # Nothing to report
return
if self . section :
self . section . dispatch_event ( self . section . hooks . item_value_changed , item = self... |
def load_toolbars ( self ) :
"""Loads the last visible toolbars from the . ini file .""" | toolbars_names = CONF . get ( 'main' , 'last_visible_toolbars' , default = [ ] )
if toolbars_names :
dic = { }
for toolbar in self . toolbars :
dic [ toolbar . objectName ( ) ] = toolbar
toolbar . toggleViewAction ( ) . setChecked ( False )
toolbar . setVisible ( False )
for name in ... |
def add_rule_entry ( self , rule_info ) :
"""Add host data object to the rule _ info list .""" | new_rule = IpMacPort ( rule_info . get ( 'ip' ) , rule_info . get ( 'mac' ) , rule_info . get ( 'port' ) )
LOG . debug ( 'Added rule info %s to the list' , rule_info )
self . rule_info . append ( new_rule ) |
def visit_ellipsis ( self , node , parent ) :
"""visit an Ellipsis node by returning a fresh instance of it""" | return nodes . Ellipsis ( getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent ) |
def write ( self , version ) : # type : ( str ) - > None
"""Write the project version to . py file .
This will regex search in the file for a
` ` _ _ version _ _ = VERSION _ STRING ` ` and substitute the version string
for the new version .""" | with open ( self . version_file ) as fp :
content = fp . read ( )
ver_statement = "__version__ = '{}'" . format ( version )
new_content = RE_PY_VERSION . sub ( ver_statement , content )
fs . write_file ( self . version_file , new_content ) |
def update_environment ( ApplicationName = None , EnvironmentId = None , EnvironmentName = None , GroupName = None , Description = None , Tier = None , VersionLabel = None , TemplateName = None , SolutionStackName = None , PlatformArn = None , OptionSettings = None , OptionsToRemove = None ) :
"""Updates the enviro... | pass |
def connection_from_host ( self , host , port = 80 , scheme = 'http' ) :
"""Get a : class : ` ConnectionPool ` based on the host , port , and scheme .
Note that an appropriate ` ` port ` ` value is required here to normalize
connection pools in our container most effectively .""" | pool_key = ( scheme , host , port )
# If the scheme , host , or port doesn ' t match existing open connections ,
# open a new ConnectionPool .
pool = self . pools . get ( pool_key )
if pool :
return pool
# Make a fresh ConnectionPool of the desired type
pool_cls = pool_classes_by_scheme [ scheme ]
pool = pool_cls (... |
def ml_entropy ( lst ) :
"""General Machine Learning Formulas
Intermezzo - computing Logarithms
log2 ( x ) = y < = > 2 ^ y = x
Definition of Entropy
E = - SUM ( p [ i ] log2 ( p [ i ] )
i = 1
where
k = possible values enumerated 1,2 , . . . , k
p [ i ] = c [ i ] / n is the fraction of elements havin... | tot = sum ( lst )
res = 0
for v in lst :
if v > 0 :
p = v / tot
l = math . log ( p , 2 )
res += round ( p * l , 6 )
res = round ( res * - 1 , 6 )
print ( 'lst = ' , lst , 'entropy = ' , res )
return res |
def _set_attr ( self , name , doc = None , preload = False ) :
"Initially sets up an attribute ." | if doc is None :
doc = 'The {name} attribute.' . format ( name = name )
if not hasattr ( self . _attr_func_ , name ) :
attr_prop = property ( functools . partial ( self . _setable_get_ , name ) , functools . partial ( self . _setable_set_ , name ) , doc = doc )
elif preload :
func = getattr ( self . _attr_f... |
def using_env ( self , env , clean = True , silent = True , filename = None ) :
"""This context manager allows the contextual use of a different env
Example of settings . toml : :
[ development ]
message = ' This is in dev '
[ other ]
message = ' this is in other env '
Program : :
> > > from dynaconf ... | try :
self . setenv ( env , clean = clean , silent = silent , filename = filename )
self . logger . debug ( "In env: %s" , env )
yield
finally :
if env . lower ( ) != self . ENV_FOR_DYNACONF . lower ( ) :
del self . loaded_envs [ - 1 ]
self . logger . debug ( "Out env: %s" , env )
self .... |
def thread_function ( self ) :
"""Thread function .""" | self . __subscribed = True
url = SUBSCRIBE_ENDPOINT + "?token=" + self . _session_token
data = self . _session . query ( url , method = 'GET' , raw = True , stream = True )
if not data or not data . ok :
_LOGGER . debug ( "Did not receive a valid response. Aborting.." )
return None
self . __sseclient = sseclien... |
def get_reply ( self , message ) :
"""根据 message 的内容获取 Reply 对象 。
: param message : 要处理的 message
: return : 获取的 Reply 对象""" | session_storage = self . session_storage
id = None
session = None
if session_storage and hasattr ( message , "source" ) :
id = to_binary ( message . source )
session = session_storage [ id ]
handlers = self . get_handlers ( message . type )
try :
for handler , args_count in handlers :
args = [ messa... |
def load_rnn_checkpoint ( cells , prefix , epoch ) :
"""Load model checkpoint from file .
Pack weights after loading .
Parameters
cells : mxnet . rnn . RNNCell or list of RNNCells
The RNN cells used by this symbol .
prefix : str
Prefix of model name .
epoch : int
Epoch number of model we would like ... | sym , arg , aux = load_checkpoint ( prefix , epoch )
if isinstance ( cells , BaseRNNCell ) :
cells = [ cells ]
for cell in cells :
arg = cell . pack_weights ( arg )
return sym , arg , aux |
def write ( filename , samples , write_params = None , static_args = None , injtype = None , ** metadata ) :
"""Writes the injection samples to the given hdf file .
Parameters
filename : str
The name of the file to write to .
samples : io . FieldArray
FieldArray of parameters .
write _ params : list , o... | # DELETE the following " if " once xml is dropped
ext = os . path . basename ( filename )
if ext . endswith ( ( '.xml' , '.xml.gz' , '.xmlgz' ) ) :
_XMLInjectionSet . write ( filename , samples , write_params , static_args )
else : # try determine the injtype if it isn ' t given
if injtype is None :
if ... |
def handle_scrollwheel ( self , event ) :
"""Make endev from appkit scroll wheel event .""" | delta_x , delta_y , delta_z = self . _get_deltas ( event )
if delta_x :
self . events . append ( self . emulate_wheel ( delta_x , 'x' , self . timeval ) )
if delta_y :
self . events . append ( self . emulate_wheel ( delta_y , 'y' , self . timeval ) )
if delta_z :
self . events . append ( self . emulate_whee... |
def from_records ( cls , data , index = None , exclude = None , columns = None , coerce_float = False , nrows = None ) :
"""Convert structured or record ndarray to DataFrame .
Parameters
data : ndarray ( structured dtype ) , list of tuples , dict , or DataFrame
index : string , list of fields , array - like
... | # Make a copy of the input columns so we can modify it
if columns is not None :
columns = ensure_index ( columns )
if is_iterator ( data ) :
if nrows == 0 :
return cls ( )
try :
first_row = next ( data )
except StopIteration :
return cls ( index = index , columns = columns )
... |
def fetch_task_failures ( self ) :
"""Read in the error file from bsub""" | error_file = os . path . join ( self . tmp_dir , "job.err" )
if os . path . isfile ( error_file ) :
with open ( error_file , "r" ) as f_err :
errors = f_err . readlines ( )
else :
errors = ''
return errors |
def request ( input , representation , resolvers = None , get3d = False , tautomers = False , ** kwargs ) :
"""Make a request to CIR and return the XML response .
: param string input : Chemical identifier to resolve
: param string representation : Desired output representation
: param list ( string ) resolve... | url = construct_api_url ( input , representation , resolvers , get3d , tautomers , ** kwargs )
log . debug ( 'Making request: %s' , url )
response = urlopen ( url )
return etree . parse ( response ) . getroot ( ) |
def _normalize_address_type ( self , addr ) : # pylint : disable = no - self - use
"""Convert address of different types to a list of mapping between region IDs and offsets ( strided intervals ) .
: param claripy . ast . Base addr : Address to convert
: return : A list of mapping between region IDs and offsets ... | addr_e = _raw_ast ( addr )
if isinstance ( addr_e , ( claripy . bv . BVV , claripy . vsa . StridedInterval , claripy . vsa . ValueSet ) ) :
raise SimMemoryError ( '_normalize_address_type() does not take claripy models.' )
if isinstance ( addr_e , claripy . ast . Base ) :
if not isinstance ( addr_e . _model_vsa... |
def indent ( self ) :
"""Indents the document text under cursor .
: return : Method success .
: rtype : bool""" | cursor = self . textCursor ( )
if not cursor . hasSelection ( ) :
cursor . insertText ( self . __indent_marker )
else :
block = self . document ( ) . findBlock ( cursor . selectionStart ( ) )
while True :
block_cursor = self . textCursor ( )
block_cursor . setPosition ( block . position ( ) ... |
def pressure_tendency ( code : str , unit : str = 'mb' ) -> str :
"""Translates a 5 - digit pressure outlook code
Ex : 50123 - > 12.3 mb : Increasing , then decreasing""" | width , precision = int ( code [ 2 : 4 ] ) , code [ 4 ]
return ( '3-hour pressure difference: +/- ' f'{width}.{precision} {unit} - {PRESSURE_TENDENCIES[code[1]]}' ) |
def minimum_swaps ( binary_str1 : str , binary_str2 : str ) -> int :
"""Determine the minimum number of swaps required to transform one binary string into another .
If the transformation isn ' t possible , return a message indicating this .
Args :
binary _ str1 : The first binary string .
binary _ str2 : Th... | diff_count = 0
for i in range ( len ( binary_str1 ) ) :
if binary_str1 [ i ] != binary_str2 [ i ] :
diff_count += 1
if diff_count % 2 == 0 :
return diff_count // 2
else :
return 'Not Possible' |
def parse ( self , spec = None , spec_params = None ) :
"""Parses the contents generically , or using a spec with optional params
: param spec :
A class derived from Asn1Value that defines what class _ and tag the
value should have , and the semantics of the encoded value . The
return value will be of this ... | if self . _parsed is None or self . _parsed [ 1 : 3 ] != ( spec , spec_params ) :
parsed_value , _ = _parse_build ( self . __bytes__ ( ) , spec = spec , spec_params = spec_params )
self . _parsed = ( parsed_value , spec , spec_params )
return self . _parsed [ 0 ] |
def active_url ( context , urls , css = None ) :
"""Highlight menu item based on url tag .
Returns a css class if ` ` request . path ` ` is in given ` ` url ` ` .
: param url :
Django url to be reversed .
: param css :
Css class to be returned for highlighting . Return active if none set .""" | request = context [ 'request' ]
if request . get_full_path in ( reverse ( url ) for url in urls . split ( ) ) :
return css if css else 'active'
return '' |
def call_callbacks ( self , iid , type , args ) :
"""Call the available callbacks for a certain marker
: param iid : marker identifier
: type iid : str
: param type : type of callback ( key in tag dictionary )
: type type : str
: param args : arguments for the callback
: type args : tuple
: return : a... | amount = 0
for tag in self . marker_tags ( iid ) :
callback = self . _tags [ tag ] . get ( type , None )
if callback is not None :
amount += 1
callback ( * args )
return amount |
def readline ( self , size = - 1 ) :
'''This reads and returns one entire line . The newline at the end of
line is returned as part of the string , unless the file ends without a
newline . An empty string is returned if EOF is encountered immediately .
This looks for a newline as a CR / LF pair ( \\ r \\ n ) ... | if size == 0 :
return self . string_type ( )
# delimiter default is EOF
index = self . expect ( [ self . crlf , self . delimiter ] )
if index == 0 :
return self . before + self . crlf
else :
return self . before |
def get_data ( self ) :
"""Find the data stored in the config _ map
: return : dict , the json of the data data that was passed into the ConfigMap on creation""" | data = graceful_chain_get ( self . json , "data" )
if data is None :
return { }
data_dict = { }
for key in data :
if self . is_yaml ( key ) :
data_dict [ key ] = yaml . load ( data [ key ] )
else :
data_dict [ key ] = json . loads ( data [ key ] )
return data_dict |
def parse_timestamp ( timestamp ) :
"""Parse ISO8601 timestamps given by github API .""" | dt = dateutil . parser . parse ( timestamp )
return dt . astimezone ( dateutil . tz . tzutc ( ) ) |
def curry ( f , args_supplied = ( ) ) :
"""Takes a function , and then returns a function that takes each argument for the original
function through _ _ call _ _ . You probably shouldn ' t use this with builtins ! Even if it seems
to work with a builtin , it might not work properly in previous versions of Pytho... | try :
nargs_required = len ( signature ( f ) . parameters )
except ValueError as e :
raise ValueError ( str ( e ) + " (maybe you're trying to curry a built-in?)" )
def inner ( arg ) :
new_args_supplied = args_supplied + ( arg , )
if len ( new_args_supplied ) == nargs_required :
return f ( * new_... |
def getLogger ( name = None ) :
'''return a logger instrumented with additional 1 - letter logging methods ;''' | logger = logging . getLogger ( name = name )
if not hasattr ( logger , 'd' ) :
def d ( self , msg , * args , ** kwargs ) :
return self . log ( DEBUG , msg , * args , ** kwargs )
logger . d = types . MethodType ( d , logger )
if not hasattr ( logger , 'v' ) :
def v ( self , msg , * args , ** kwargs )... |
def lbnd ( self ) :
"""the lower bound vector while respecting log transform
Returns
lbnd : pandas . Series""" | if not self . istransformed :
return self . pst . parameter_data . parlbnd . copy ( )
else :
lb = self . pst . parameter_data . parlbnd . copy ( )
lb [ self . log_indexer ] = np . log10 ( lb [ self . log_indexer ] )
return lb |
def scratch_file ( unlink = True , ** kwargs ) :
"""Create a temporary file and return its name .
Additional arguments are passed to : class : ` tempfile . NamedTemporaryFile `
At the start of the with block a secure , temporary file is created
and its name returned . At the end of the with block it is
dele... | kwargs [ 'delete' ] = False
tf = tempfile . NamedTemporaryFile ( ** kwargs )
tf . close ( )
try :
yield tf . name
finally :
if unlink :
os . unlink ( tf . name ) |
def open ( self ) :
"""Open TCP socket with ` ` socket ` ` - library and set it as escpos device""" | self . device = socket . socket ( socket . AF_INET , socket . SOCK_STREAM )
self . device . settimeout ( self . timeout )
self . device . connect ( ( self . host , self . port ) )
if self . device is None :
print ( "Could not open socket for {0}" . format ( self . host ) ) |
def format_account ( service_name , data ) :
"""Given profile data and the name of a
social media service , format it for
the zone file .
@ serviceName : name of the service
@ data : legacy profile verification
Returns the formatted account on success ,
as a dict .""" | if "username" not in data :
raise KeyError ( "Account is missing a username" )
account = { "@type" : "Account" , "service" : service_name , "identifier" : data [ "username" ] , "proofType" : "http" }
if ( data . has_key ( service_name ) and data [ service_name ] . has_key ( "proof" ) and data [ service_name ] [ "pr... |
def _add_to_ptr_size ( self , ptr ) : # type : ( path _ table _ record . PathTableRecord ) - > int
'''An internal method to add a PTR to a VD , adding space to the VD if
necessary .
Parameters :
ptr - The PTR to add to the vd .
Returns :
The number of additional bytes that are needed to fit the new PTR
... | num_bytes_to_add = 0
for pvd in self . pvds : # The add _ to _ ptr _ size ( ) method returns True if the PVD needs
# additional space in the PTR to store this directory . We always
# add 4 additional extents for that ( 2 for LE , 2 for BE ) .
if pvd . add_to_ptr_size ( path_table_record . PathTableRecord . record_l... |
def _get_hangul_syllable_name ( hangul_syllable ) :
"""Function for taking a Unicode scalar value representing a Hangul syllable and converting it to its syllable name as
defined by the Unicode naming rule NR1 . See the Unicode Standard , ch . 04 , section 4.8 , Names , for more information .
: param hangul _ s... | if not _is_hangul_syllable ( hangul_syllable ) :
raise ValueError ( "Value passed in does not represent a Hangul syllable!" )
jamo = decompose_hangul_syllable ( hangul_syllable , fully_decompose = True )
result = ''
for j in jamo :
if j is not None :
result += _get_jamo_short_name ( j )
return result |
def count_stages ( self , matrix_name ) :
"""Number of registered stages for given matrix name .
Parameters :
matrix _ name ( str ) : name of the matrix
Returns :
int : number of reported stages for given matrix name .""" | return len ( self . data [ matrix_name ] ) if matrix_name in self . data else 0 |
def context ( self , line ) :
"""Return the context for a given 1 - offset line number .""" | # XXX due to a limitation in Visitor ,
# non - python code after the last python code
# in a file is not added to self . lines , so we
# have to guard against IndexErrors .
idx = line - 1
if idx >= len ( self . lines ) :
return self . prefix
return self . lines [ idx ] |
def split_limits_heads ( self ) :
"""Return first parts of dot - separated strings , and rest of strings .
Returns :
( list of str , list of str ) : the heads and rest of the strings .""" | heads = [ ]
new_limit_to = [ ]
for limit in self . limit_to :
if '.' in limit :
name , limit = limit . split ( '.' , 1 )
heads . append ( name )
new_limit_to . append ( limit )
else :
heads . append ( limit )
return heads , new_limit_to |
def severity ( self ) :
"""Severity level of the event . One of ` ` INFO ` ` , ` ` WATCH ` ` ,
` ` WARNING ` ` , ` ` DISTRESS ` ` , ` ` CRITICAL ` ` or ` ` SEVERE ` ` .""" | if self . _proto . HasField ( 'severity' ) :
return yamcs_pb2 . Event . EventSeverity . Name ( self . _proto . severity )
return None |
def reindex ( self , target , method = None , level = None , limit = None , tolerance = None ) :
"""Create index with target ' s values ( move / add / delete values as necessary )
Returns
new _ index : pd . MultiIndex
Resulting index
indexer : np . ndarray or None
Indices of output values in original inde... | # GH6552 : preserve names when reindexing to non - named target
# ( i . e . neither Index nor Series ) .
preserve_names = not hasattr ( target , 'names' )
if level is not None :
if method is not None :
raise TypeError ( 'Fill method not supported if level passed' )
# GH7774 : preserve dtype / tz if targ... |
def argmin ( self , values ) :
"""return the index into values corresponding to the minimum value of the group
Parameters
values : array _ like , [ keys ]
values to pick the argmin of per group
Returns
unique : ndarray , [ groups ]
unique keys
argmin : ndarray , [ groups ]
index into value array , r... | keys , minima = self . min ( values )
minima = minima [ self . inverse ]
# select the first occurence of the minimum in each group
index = as_index ( ( self . inverse , values == minima ) )
return keys , index . sorter [ index . start [ - self . groups : ] ] |
def cross_chan_coherence ( st1 , st2 , allow_shift = False , shift_len = 0.2 , i = 0 , xcorr_func = 'time_domain' ) :
"""Calculate cross - channel coherency .
Determine the cross - channel coherency between two streams of multichannel
seismic data .
: type st1 : obspy . core . stream . Stream
: param st1 : ... | cccoh = 0.0
kchan = 0
array_xcorr = get_array_xcorr ( xcorr_func )
for tr in st1 :
tr2 = st2 . select ( station = tr . stats . station , channel = tr . stats . channel )
if len ( tr2 ) > 0 and tr . stats . sampling_rate != tr2 [ 0 ] . stats . sampling_rate :
warnings . warn ( 'Sampling rates do not matc... |
def get_recurring_bill_by_client ( self , * , customer_id , date_begin = None , date_final = None ) :
"""Consulta de las facturas que están pagadas o pendientes por pagar . Se puede consultar por cliente ,
por suscripción o por rango de fechas .
Args :
customer _ id :
date _ begin :
date _ final :
Ret... | params = { "customerId" : customer_id , }
if date_begin and date_final :
params [ 'dateBegin' ] = date_begin . strftime ( '%Y-%m-%d' )
params [ 'dateFinal' ] = date_final . strftime ( '%Y-%m-%d' )
return self . client . _get ( self . url + 'recurringBill' , params = params , headers = self . get_headers ( ) ) |
def update_member_names ( oldasndict , pydr_input ) :
"""Update names in a member dictionary .
Given an association dictionary with rootnames and a list of full
file names , it will update the names in the member dictionary to
contain ' _ * ' extension . For example a rootname of ' u9600201m ' will
be repla... | omembers = oldasndict [ 'members' ] . copy ( )
nmembers = { }
translated_names = [ f . split ( '.fits' ) [ 0 ] for f in pydr_input ]
newkeys = [ fileutil . buildNewRootname ( file ) for file in pydr_input ]
keys_map = list ( zip ( newkeys , pydr_input ) )
for okey , oval in list ( omembers . items ( ) ) :
if okey i... |
def send_messages ( self , sms_messages ) :
"""Sends one or more SmsMessage objects and returns the number of sms
messages sent .""" | if not sms_messages :
return
num_sent = 0
for message in sms_messages :
if self . _send ( message ) :
num_sent += 1
return num_sent |
def scan_for_field ( self , field_key ) :
'''Scan for a field in the container and its enclosed fields
: param field _ key : name of field to look for
: return : field with name that matches field _ key , None if not found''' | if field_key == self . get_name ( ) :
return self
if field_key in self . _fields_dict :
return self . _fields_dict [ field_key ]
for field in self . _fields :
if isinstance ( field , Container ) :
resolved = field . scan_for_field ( field_key )
if resolved :
return resolved
retur... |
def __shpHeader ( self ) :
"""Reads the header information from a . shp or . shx file .""" | if not self . shp :
raise ShapefileException ( "Shapefile Reader requires a shapefile or file-like object. (no shp file found" )
shp = self . shp
# File length ( 16 - bit word * 2 = bytes )
shp . seek ( 24 )
self . shpLength = unpack ( ">i" , shp . read ( 4 ) ) [ 0 ] * 2
# Shape type
shp . seek ( 32 )
self . shapeT... |
def select_one_song ( songs ) :
"""Display the songs returned by search api .
: params songs : API [ ' result ' ] [ ' songs ' ]
: return : a Song object .""" | if len ( songs ) == 1 :
select_i = 0
else :
table = PrettyTable ( [ 'Sequence' , 'Song Name' , 'Artist Name' ] )
for i , song in enumerate ( songs , 1 ) :
table . add_row ( [ i , song [ 'name' ] , song [ 'ar' ] [ 0 ] [ 'name' ] ] )
click . echo ( table )
select_i = click . prompt ( 'Select o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.