signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def write ( self , data , offset = 0 , write_through = False , unbuffered = False , wait = True , send = True ) :
"""Writes data to an opened file .
Supports out of band send function , call this function with send = False
to return a tuple of ( SMBWriteRequest , receive _ func ) instead of
sending the the re... | data_len = len ( data )
if data_len > self . connection . max_write_size :
raise SMBException ( "The requested write length %d is greater than " "the maximum negotiated write size %d" % ( data_len , self . connection . max_write_size ) )
write = SMB2WriteRequest ( )
write [ 'length' ] = len ( data )
write [ 'offset... |
def decode_body ( cls , header , f ) :
"""Generates a ` MqttUnsuback ` packet given a
` MqttFixedHeader ` . This method asserts that header . packet _ type
is ` unsuback ` .
Parameters
header : MqttFixedHeader
f : file
Object with a read method .
Raises
DecodeError
When there are extra bytes at th... | assert header . packet_type == MqttControlPacketType . unsuback
decoder = mqtt_io . FileDecoder ( mqtt_io . LimitReader ( f , header . remaining_len ) )
packet_id , = decoder . unpack ( mqtt_io . FIELD_PACKET_ID )
if header . remaining_len != decoder . num_bytes_consumed :
raise DecodeError ( 'Extra bytes at end of... |
def need_update ( a , b ) :
"""Check if file a is newer than file b and decide whether or not to update
file b . Can generalize to two lists .""" | a = listify ( a )
b = listify ( b )
return any ( ( not op . exists ( x ) ) for x in b ) or all ( ( os . stat ( x ) . st_size == 0 for x in b ) ) or any ( is_newer_file ( x , y ) for x in a for y in b ) |
def get_urls ( self ) :
"""Adds a url to move nodes to this admin""" | urls = super ( TreeAdmin , self ) . get_urls ( )
if django . VERSION < ( 1 , 10 ) :
from django . views . i18n import javascript_catalog
jsi18n_url = url ( r'^jsi18n/$' , javascript_catalog , { 'packages' : ( 'treebeard' , ) } )
else :
from django . views . i18n import JavaScriptCatalog
jsi18n_url = url... |
def _load_build ( self ) :
"""See ` pickle . py ` in Python ' s source code .""" | # if the ctor . function ( penultimate on the stack ) is the ` Ref ` class . . .
if isinstance ( self . stack [ - 2 ] , Ref ) : # Ref . _ _ setstate _ _ will know it ' s a remote ref if the state is a tuple
self . stack [ - 1 ] = ( self . stack [ - 1 ] , self . node )
self . load_build ( )
# continue with t... |
def _bind ( self , _descriptor ) :
"""Bind a ResponseObject to a given action descriptor . This
updates the default HTTP response code and selects the
appropriate content type and serializer for the response .""" | # If the method has a default code , use it
self . _defcode = getattr ( _descriptor . method , '_wsgi_code' , 200 )
# Set up content type and serializer
self . content_type , self . serializer = _descriptor . serializer ( self . req ) |
def search_debit ( ) :
"""Get one to ten debit ( s ) for a single User .
parameters :
- name : searchcd
in : body
description : The Debit ( s ) you ' d like to get .
required : false
schema :
$ ref : ' # / definitions / SearchCD '
responses :
'200 ' :
description : the User ' s debit ( s )
sch... | sid = request . jws_payload [ 'data' ] . get ( 'id' )
address = request . jws_payload [ 'data' ] . get ( 'address' )
currency = request . jws_payload [ 'data' ] . get ( 'currency' )
network = request . jws_payload [ 'data' ] . get ( 'network' )
# reference = request . jws _ payload [ ' data ' ] . get ( ' reference ' )
... |
def cds_length_of_associated_transcript ( effect ) :
"""Length of coding sequence of transcript associated with effect ,
if there is one ( otherwise return 0 ) .""" | return apply_to_transcript_if_exists ( effect = effect , fn = lambda t : len ( t . coding_sequence ) if ( t . complete and t . coding_sequence ) else 0 , default = 0 ) |
def add_loaded_callback ( self , callback ) :
"""Add a callback to be run when the ALDB load is complete .""" | if callback not in self . _cb_aldb_loaded :
self . _cb_aldb_loaded . append ( callback ) |
def autofit ( ts , maxp = 5 , maxd = 2 , maxq = 5 , sc = None ) :
"""Utility function to help in fitting an automatically selected ARIMA model based on approximate
Akaike Information Criterion ( AIC ) values . The model search is based on the heuristic
developed by Hyndman and Khandakar ( 2008 ) and described i... | assert sc != None , "Missing SparkContext"
jmodel = sc . _jvm . com . cloudera . sparkts . models . ARIMA . autoFit ( _py2java ( sc , Vectors . dense ( ts ) ) , maxp , maxd , maxq )
return ARIMAModel ( jmodel = jmodel , sc = sc ) |
def _read_para_nat_traversal_mode ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP NAT _ TRAVERSAL _ MODE parameter .
Structure of HIP NAT _ TRAVERSAL _ MODE parameter [ RFC 5770 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| Reserv... | if clen % 2 != 0 :
raise ProtocolError ( f'HIPv{version}: [Parano {code}] invalid format' )
_resv = self . _read_fileng ( 2 )
_mdid = list ( )
for _ in range ( ( clen - 2 ) // 2 ) :
_mdid . append ( _MODE_ID . get ( self . _read_unpack ( 2 ) , 'Unassigned' ) )
nat_traversal_mode = dict ( type = desc , critical ... |
def setup ( self , ** kwargs ) :
'''This is called during production de - trending , prior to
calling the : py : obj : ` Detrender . run ( ) ` method .
: param tuple cdpp _ range : If : py : obj : ` parent _ model ` is set , neighbors are selected only if their de - trended CDPPs fall within this range . Defaul... | # Get neighbors
self . parent_model = kwargs . get ( 'parent_model' , None )
neighbors = kwargs . get ( 'neighbors' , 10 )
neighbors_data = kwargs . get ( 'neighbors_data' , None )
if hasattr ( neighbors , '__len__' ) :
self . neighbors = neighbors
else :
num_neighbors = neighbors
self . neighbors = self . ... |
def delete_all_volumes ( self ) :
"""Remove all the volumes .
Only the manager nodes can delete a volume""" | # Raise an exception if we are not a manager
if not self . _manager :
raise RuntimeError ( 'Volumes can only be deleted ' 'on swarm manager nodes' )
volume_list = self . get_volume_list ( )
for volumes in volume_list : # Remove all the services
self . _api_client . remove_volume ( volumes , force = True ) |
def getargspec ( method ) :
"""Drill through layers of decorators attempting to locate the actual argspec
for a method .""" | argspec = _getargspec ( method )
args = argspec [ 0 ]
if args and args [ 0 ] == 'self' :
return argspec
if hasattr ( method , '__func__' ) :
method = method . __func__
func_closure = six . get_function_closure ( method )
# NOTE ( sileht ) : if the closure is None we cannot look deeper ,
# so return actual argsp... |
def post ( self , endpoint , body = None , timeout = None , allow_redirects = None , validate = True , headers = None , ) :
"""* Sends a POST request to the endpoint . *
The endpoint is joined with the URL given on library init ( if any ) .
If endpoint starts with ` ` http : / / ` ` or ` ` https : / / ` ` , it ... | endpoint = self . _input_string ( endpoint )
request = deepcopy ( self . request )
request [ "method" ] = "POST"
request [ "body" ] = self . input ( body )
if allow_redirects is not None :
request [ "allowRedirects" ] = self . _input_boolean ( allow_redirects )
if timeout is not None :
request [ "timeout" ] = s... |
def get_model_info ( self ) :
''': return : dictionary of information about this model''' | info = { }
info [ 'model_name' ] = self . name
info [ 'stages' ] = '->' . join ( [ repr ( s ) for s in self . _stages ] )
info [ 'sequence' ] = { 'index' : self . _current_index }
return info |
def metrics ( ref_time , ref_freqs , est_time , est_freqs , ** kwargs ) :
"""Compute multipitch metrics . All metrics are computed at the ' macro ' level
such that the frame true positive / false positive / false negative rates are
summed across time and the metrics are computed on the combined values .
Examp... | validate ( ref_time , ref_freqs , est_time , est_freqs )
# resample est _ freqs if est _ times is different from ref _ times
if est_time . size != ref_time . size or not np . allclose ( est_time , ref_time ) :
warnings . warn ( "Estimate times not equal to reference times. " "Resampling to common time base." )
... |
def mase ( simulated_array , observed_array , m = 1 , replace_nan = None , replace_inf = None , remove_neg = False , remove_zero = False ) :
"""Compute the mean absolute scaled error between the simulated and observed data .
. . image : : / pictures / MASE . png
* * Range : * *
* * Notes : * *
Parameters
... | # Checking and cleaning the data
simulated_array , observed_array = treat_values ( simulated_array , observed_array , replace_nan = replace_nan , replace_inf = replace_inf , remove_neg = remove_neg , remove_zero = remove_zero )
start = m
end = simulated_array . size - m
a = np . mean ( np . abs ( simulated_array - obse... |
def search_by_category ( self , category_id , limit = 0 , order_by = None , sort_order = None , filter = None ) :
"""Search for series that belongs to a category id . Returns information about matching series in a DataFrame .
Parameters
category _ id : int
category id , e . g . , 32145
limit : int , optiona... | url = "%s/category/series?category_id=%d&" % ( self . root_url , category_id )
info = self . __get_search_results ( url , limit , order_by , sort_order , filter )
if info is None :
raise ValueError ( 'No series exists for category id: ' + str ( category_id ) )
return info |
def execute_cleanup_tasks ( ctx , cleanup_tasks , dry_run = False ) :
"""Execute several cleanup tasks as part of the cleanup .
REQUIRES : ` ` clean ( ctx , dry _ run = False ) ` ` signature in cleanup tasks .
: param ctx : Context object for the tasks .
: param cleanup _ tasks : Collection of cleanup tasks (... | # pylint : disable = redefined - outer - name
executor = Executor ( cleanup_tasks , ctx . config )
for cleanup_task in cleanup_tasks . tasks :
print ( "CLEANUP TASK: %s" % cleanup_task )
executor . execute ( ( cleanup_task , dict ( dry_run = dry_run ) ) ) |
def set_stim_by_index ( self , index ) :
"""Sets the stimulus to be generated to the one referenced by index
: param index : index number of stimulus to set from this class ' s internal list of stimuli
: type index : int""" | # remove any current components
self . stimulus . clearComponents ( )
# add one to index because of tone curve
self . stimulus . insertComponent ( self . stim_components [ index ] ) |
def Indentation ( logical_line , previous_logical , indent_level , previous_indent_level ) :
"""Use two spaces per indentation level .""" | comment = '' if logical_line else ' (comment)'
if indent_level % 2 :
code = 'YCM111' if logical_line else 'YCM114'
message = ' indentation is not a multiple of two spaces' + comment
yield 0 , code + message
if ( previous_logical . endswith ( ':' ) and ( indent_level - previous_indent_level != 2 ) ) :
co... |
def write_bed_with_trackline ( bed , out , trackline , add_chr = False ) :
"""Read a bed file and write a copy with a trackline . Here ' s a simple trackline
example : ' track type = bed name = " cool " description = " A cool track . " '
Parameters
bed : str
Input bed file name .
out : str
Output bed fi... | df = pd . read_table ( bed , index_col = None , header = None )
bt = pbt . BedTool ( '\n' . join ( df . apply ( lambda x : '\t' . join ( x . astype ( str ) ) , axis = 1 ) ) + '\n' , from_string = True )
if add_chr :
bt = add_chr_to_contig ( bt )
bt = bt . saveas ( out , trackline = trackline ) |
def results_cache_path ( self ) -> str :
"""Location where step report is cached between sessions to
prevent loss of display data between runs .""" | if not self . project :
return ''
return os . path . join ( self . project . results_path , '.cache' , 'steps' , '{}.json' . format ( self . id ) ) |
def match ( self , pattern , context = None ) :
"""This method returns a ( possibly empty ) list of strings that
match the regular expression ` ` pattern ` ` provided . You can
also provide a ` ` context ` ` as described above .
This method calls ` ` choices ` ` to get a list of all possible
choices and the... | matches = [ ]
regex = pattern
if regex == '*' :
regex = '.*'
regex = re . compile ( regex )
for choice in self . choices ( context ) :
if regex . search ( choice ) :
matches . append ( choice )
return matches |
def rescaleX ( self ) :
'''Rescales the horizontal axes to make the lengthscales equal .''' | self . ratio = self . figure . get_size_inches ( ) [ 0 ] / float ( self . figure . get_size_inches ( ) [ 1 ] )
self . axes . set_xlim ( - self . ratio , self . ratio )
self . axes . set_ylim ( - 1 , 1 ) |
def stopObserver ( self ) :
"""Stops this region ' s observer loop .
If this is running in a subprocess , the subprocess will end automatically .""" | self . _observer . isStopped = True
self . _observer . isRunning = False |
def get_vsan_enabled ( host , username , password , protocol = None , port = None , host_names = None ) :
'''Get the VSAN enabled status for a given host or a list of host _ names . Returns ` ` True ` `
if VSAN is enabled , ` ` False ` ` if it is not enabled , and ` ` None ` ` if a VSAN Host Config
is unset , p... | service_instance = salt . utils . vmware . get_service_instance ( host = host , username = username , password = password , protocol = protocol , port = port )
host_names = _check_hosts ( service_instance , host , host_names )
ret = { }
for host_name in host_names :
host_ref = _get_host_ref ( service_instance , hos... |
def _get_result_paths ( self , data ) :
"""Build the dict of result filepaths""" | # get the filepath of the indexed database ( after comma )
# / path / to / refseqs . fasta , / path / to / refseqs . idx
db_name = ( self . Parameters [ '--ref' ] . Value ) . split ( ',' ) [ 1 ]
result = { }
extensions = [ 'bursttrie' , 'kmer' , 'pos' , 'stats' ]
for extension in extensions :
for file_path in glob ... |
async def _handle_local_charms ( self , bundle ) :
"""Search for references to local charms ( i . e . filesystem paths )
in the bundle . Upload the local charms to the model , and replace
the filesystem paths with appropriate ' local : ' paths in the bundle .
Return the modified bundle .
: param dict bundle... | apps , args = [ ] , [ ]
default_series = bundle . get ( 'series' )
apps_dict = bundle . get ( 'applications' , bundle . get ( 'services' , { } ) )
for app_name in self . applications :
app_dict = apps_dict [ app_name ]
charm_dir = os . path . abspath ( os . path . expanduser ( app_dict [ 'charm' ] ) )
if no... |
def toDict ( self ) :
"""To Dict
Returns the Hashed Node as a dictionary in the same format as is used in
constructing it
Returns :
dict""" | # Init the dictionary we will return
dRet = { }
# Add the hash key
dRet [ '__hash__' ] = self . _key . toDict ( )
# Get the parents dict and add it to the return
dRet . update ( super ( HashNode , self ) . toDict ( ) )
# Get the nodes dict and also add it to the return
dRet . update ( self . _node . toDict ( ) )
# Retu... |
def create_jar_builder ( self , jar ) :
"""Creates a ` ` JarTask . JarBuilder ` ` ready for use .
This method should be called during in ` execute ` context and only after ensuring
` JarTask . JarBuilder . prepare ` has already been called in ` prepare ` context .
: param jar : An opened ` ` pants . backend .... | builder = self . JarBuilder ( self . context , jar )
yield builder
builder . commit_manifest ( jar ) |
def has_documented_fields ( self , include_inherited_fields = False ) :
"""Returns whether at least one field is documented .""" | fields = self . all_fields if include_inherited_fields else self . fields
for field in fields :
if field . doc :
return True
return False |
def value_from_person ( self , array , role , default = 0 ) :
"""Get the value of ` ` array ` ` for the person with the unique role ` ` role ` ` .
` ` array ` ` must have the dimension of the number of persons in the simulation
If such a person does not exist , return ` ` default ` ` instead
The result is a v... | self . entity . check_role_validity ( role )
if role . max != 1 :
raise Exception ( 'You can only use value_from_person with a role that is unique in {}. Role {} is not unique.' . format ( self . key , role . key ) )
self . members . check_array_compatible_with_entity ( array )
members_map = self . ordered_members_... |
def get_det_id ( self , det_oid ) :
"""Convert detector string representation ( OID ) to serialnumber""" | try :
return self . detectors [ self . detectors . OID == det_oid ] . SERIALNUMBER . iloc [ 0 ]
except IndexError :
log . critical ( "No det ID found for OID '{}'" . format ( det_oid ) )
return None |
def extrair_logs ( self ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . extrair _ logs ` .
: return : Uma resposta SAT especializada em ` ` ExtrairLogs ` ` .
: rtype : satcfe . resposta . extrairlogs . RespostaExtrairLogs""" | retorno = super ( ClienteSATLocal , self ) . extrair_logs ( )
return RespostaExtrairLogs . analisar ( retorno ) |
def credential_update ( self , cred_id , ** options ) :
"""credential _ update cred _ id * * options
Updates the specified values of the credential ID specified .""" | payload = None
# First we pull the credentials and populate the payload if we
# find a match .
for cred in self . credentials ( ) [ 'credentials' ] :
if cred [ 'id' ] == str ( cred_id ) :
payload = { 'id' : cred_id , 'type' : cred [ 'type' ] , 'name' : cred [ 'name' ] , 'description' : cred [ 'description' ... |
def log_every_n_seconds ( level , msg , n_seconds , * args ) :
"""Logs ' msg % args ' at level ' level ' iff ' n _ seconds ' elapsed since last call .
Logs the first call , logs subsequent calls if ' n ' seconds have elapsed since
the last logging call from the same call site ( file + line ) . Not thread - safe... | should_log = _seconds_have_elapsed ( get_absl_logger ( ) . findCaller ( ) , n_seconds )
log_if ( level , msg , should_log , * args ) |
def parse ( stream ) :
"""Creates a ` ` ValidationDefinition ` ` from a provided stream containing XML .
The XML typically will look like this :
` ` < items > ` `
` ` < server _ host > myHost < / server _ host > ` `
` ` < server _ uri > https : / / 127.0.0.1:8089 < / server _ uri > ` `
` ` < session _ key... | definition = ValidationDefinition ( )
# parse XML from the stream , then get the root node
root = ET . parse ( stream ) . getroot ( )
for node in root : # lone item node
if node . tag == "item" : # name from item node
definition . metadata [ "name" ] = node . get ( "name" )
definition . parameters =... |
def data ( self , index , role = Qt . DisplayRole ) :
"""Cell content""" | if not index . isValid ( ) :
return to_qvariant ( )
value = self . get_value ( index )
if is_binary_string ( value ) :
try :
value = to_text_string ( value , 'utf8' )
except :
pass
if role == Qt . DisplayRole :
if value is np . ma . masked :
return ''
else :
try :
... |
def build ( path , query = None , fragment = '' ) :
"""Generates a URL based on the inputted path and given query options and
fragment . The query should be a dictionary of terms that will be
generated into the URL , while the fragment is the anchor point within the
target path that will be navigated to . If ... | url = nstr ( path )
# replace the optional arguments in the url
keys = projex . text . findkeys ( path )
if keys :
if query is None :
query = { }
opts = { }
for key in keys :
opts [ key ] = query . pop ( key , '%({})s' . format ( key ) )
url %= opts
# add the query
if query :
if type... |
def from_xyz ( x , y , z , alpha = 1.0 , wref = _DEFAULT_WREF ) :
"""Create a new instance based on the specifed CIE - XYZ values .
Parameters :
The Red component value [ 0 . . . 1]
The Green component value [ 0 . . . 1]
The Blue component value [ 0 . . . 1]
: alpha :
The color transparency [ 0 . . . 1 ... | return Color ( xyz_to_rgb ( x , y , z ) , 'rgb' , alpha , wref ) |
def p_identifier ( self , p ) :
'identifier : ID' | p [ 0 ] = Identifier ( p [ 1 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def create_loadbalancer ( call = None , kwargs = None ) :
'''Creates a loadbalancer within the datacenter from the provider config .
CLI Example :
. . code - block : : bash
salt - cloud - f create _ loadbalancer profitbricks name = mylb''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The create_address function must be called with -f or --function.' )
if kwargs is None :
kwargs = { }
conn = get_conn ( )
datacenter_id = get_datacenter_id ( )
loadbalancer = LoadBalancer ( name = kwargs . get ( 'name' ) , ip = kwargs . get ( 'ip' ) , dhcp = ... |
def get_anonymous_request ( leonardo_page ) :
"""returns inicialized request""" | request_factory = RequestFactory ( )
request = request_factory . get ( leonardo_page . get_absolute_url ( ) , data = { } )
request . feincms_page = request . leonardo_page = leonardo_page
request . frontend_editing = False
request . user = AnonymousUser ( )
if not hasattr ( request , '_feincms_extra_context' ) :
re... |
def AssertType ( value , expected_type ) :
"""Ensures that given value has certain type .
Args :
value : A value to assert the type for .
expected _ type : An expected type for the given value .
Raises :
TypeError : If given value does not have the expected type .""" | if not isinstance ( value , expected_type ) :
message = "Expected type `%r`, but got value `%r` of type `%s`"
message %= ( expected_type , value , type ( value ) )
raise TypeError ( message ) |
def _get_chain_by_pid ( pid ) :
"""Find chain by pid .
Return None if not found .""" | try :
return d1_gmn . app . models . ChainMember . objects . get ( pid__did = pid ) . chain
except d1_gmn . app . models . ChainMember . DoesNotExist :
pass |
def _choose_node ( self , nodes = None ) :
"""Chooses a random node from the list of nodes in the client ,
taking into account each node ' s recent error rate .
: rtype RiakNode""" | if not nodes :
nodes = self . nodes
# Prefer nodes which have gone a reasonable time without
# errors
def _error_rate ( node ) :
return node . error_rate . value ( )
good = [ n for n in nodes if _error_rate ( n ) < 0.1 ]
if len ( good ) is 0 : # Fall back to a minimally broken node
return min ( nodes , key ... |
def dot ( self , vector , theta = None ) :
"""Return the dot product of two vectors .
If theta is given then the dot product is computed as
v1 * v1 = | v1 | | v2 | cos ( theta ) . Argument theta
is measured in degrees .""" | if theta is not None :
return ( self . magnitude ( ) * vector . magnitude ( ) * math . degrees ( math . cos ( theta ) ) )
return ( reduce ( lambda x , y : x + y , [ x * vector . vector [ i ] for i , x in self . to_list ( ) ( ) ] ) ) |
def set_runtime_value_float ( self , ihcid : int , value : float ) -> bool :
"""Set float runtime value with re - authenticate if needed""" | if self . client . set_runtime_value_float ( ihcid , value ) :
return True
self . re_authenticate ( )
return self . client . set_runtime_value_float ( ihcid , value ) |
def write_pkg_to_file ( self , name , objects , path = '.' , filename = None ) :
"""Write a list of related objs to file""" | # Kibana uses an array of docs , do the same
# as opposed to a dict of docs
pkg_objs = [ ]
for _ , obj in iteritems ( objects ) :
pkg_objs . append ( obj )
sorted_pkg = sorted ( pkg_objs , key = lambda k : k [ '_id' ] )
output = self . json_dumps ( sorted_pkg ) + '\n'
if filename is None :
filename = self . saf... |
def enable ( commanddict , modulename ) :
"""< Purpose >
Enables a module and imports its commands into the seash commanddict .
< Arguments >
modulename : The module to import .
< Side Effects >
All commands inside the specified module will be inserted into the seash
commanddict if possible .
The file... | # Is this an installed module ?
if not modulename in module_data :
raise seash_exceptions . UserError ( "Error, module '" + modulename + "' is not installed" )
if _is_module_enabled ( modulename ) :
raise seash_exceptions . UserError ( "Module is already enabled." )
merge_commanddict ( commanddict , module_data... |
def calculate_legacy_pad_amount ( H_in , pad_h , k_h , s_h ) :
'''This function calculate padding amount along H - axis . It can be applied to other axes . It should be only used with
pooling conversion .
: param H _ in : input dimension along H - axis
: param pad _ h : padding amount at H - axis
: param k ... | # Calculate a common variable
H_temp = H_in + 2 * pad_h - k_h
# Pooling output shape under CoerML IncludeLastPixel padding mode
H_include_last_pad_out = math . ceil ( H_temp / s_h ) + 1
# Pooling output shape under valid padding mode
H_valid_pad_out = math . floor ( H_temp / s_h ) + 1
# Amount of values padded at top b... |
def get_unicodedata ( version , output = HOME , no_zip = False ) :
"""Ensure we have Unicode data to generate Unicode tables .""" | target = os . path . join ( output , 'unicodedata' , version )
zip_target = os . path . join ( output , 'unicodedata' , '%s.zip' % version )
if not os . path . exists ( target ) and os . path . exists ( zip_target ) :
unzip_unicode ( output , version )
# Download missing files if any . Zip if required .
download_un... |
def reducejson ( j ) :
"""Not sure if there ' s a better way to walk the . . . interesting result""" | authors = [ ]
for key in j [ "data" ] [ "repository" ] [ "commitComments" ] [ "edges" ] :
authors . append ( key [ "node" ] [ "author" ] )
for key in j [ "data" ] [ "repository" ] [ "issues" ] [ "nodes" ] :
authors . append ( key [ "author" ] )
for c in key [ "comments" ] [ "nodes" ] :
authors . app... |
def writePlist ( dataObject , filepath ) :
'''Write ' rootObject ' as a plist to filepath .''' | plistData , error = ( NSPropertyListSerialization . dataFromPropertyList_format_errorDescription_ ( dataObject , NSPropertyListXMLFormat_v1_0 , None ) )
if plistData is None :
if error :
error = error . encode ( 'ascii' , 'ignore' )
else :
error = "Unknown error"
raise NSPropertyListSerializ... |
def _import_protobuf_from_file ( grpc_pyfile , method_name , service_name = None ) :
"""helper function which try to import method from the given _ pb2 _ grpc . py file
service _ name should be provided only in case of name conflict
return ( False , None ) in case of failure
return ( True , ( stub _ class , r... | prefix = grpc_pyfile [ : - 12 ]
pb2 = __import__ ( "%s_pb2" % prefix )
pb2_grpc = __import__ ( "%s_pb2_grpc" % prefix )
# we take all objects from pb2 _ grpc module which endswith " Stub " , and we remove this postfix to get service _ name
all_service_names = [ stub_name [ : - 4 ] for stub_name in dir ( pb2_grpc ) if s... |
def delete_project ( project_id ) :
"""Delete Project .""" | project = get_data_or_404 ( 'project' , project_id )
if project [ 'owner_id' ] != get_current_user_id ( ) :
return jsonify ( message = 'forbidden' ) , 403
delete_instance ( 'project' , project_id )
return jsonify ( { } ) |
def getIfConfig ( self ) :
"""Return dictionary of Interface Configuration ( ifconfig ) .
@ return : Dictionary of if configurations keyed by if name .""" | conf = { }
try :
out = subprocess . Popen ( [ ipCmd , "addr" , "show" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ]
except :
raise Exception ( 'Execution of command %s failed.' % ipCmd )
for line in out . splitlines ( ) :
mobj = re . match ( '^\d+: (\S+):\s+<(\S*)>\s+(\S.*\S)\s*$' , line )
if... |
def assert_credentials_match ( self , verifier , authc_token , account ) :
""": type verifier : authc _ abcs . CredentialsVerifier
: type authc _ token : authc _ abcs . AuthenticationToken
: type account : account _ abcs . Account
: returns : account _ abcs . Account
: raises IncorrectCredentialsException :... | cred_type = authc_token . token_info [ 'cred_type' ]
try :
verifier . verify_credentials ( authc_token , account [ 'authc_info' ] )
except IncorrectCredentialsException :
updated_account = self . update_failed_attempt ( authc_token , account )
failed_attempts = updated_account [ 'authc_info' ] [ cred_type ]... |
def compiler ( self , target ) :
"""Returns the thrift compiler to use for the given target .
: param target : The target to extract the thrift compiler from .
: type target : : class : ` pants . backend . codegen . thrift . java . java _ thrift _ library . JavaThriftLibrary `
: returns : The thrift compiler ... | self . _check_target ( target )
return target . compiler or self . _default_compiler |
def _get_next_events ( self , material ) :
"""Get next events from Genie ROOT file
Looks over the generator""" | f = ROOT . TFile ( self . filenames [ material ] )
try :
t = f . Get ( 'gst' )
n = t . GetEntries ( )
except :
self . log . critical ( 'Could not open the ROOT file with Genie events' )
raise
for i in range ( n ) :
t . GetEntry ( i )
next_events = [ ]
position = convert_3vector_to_dict ( [ s... |
def graphs ( self ) :
"""Sorry for the black magic . The result is an object whose attributes
are all the graphs found in graphs . py initialized with this instance as
only argument .""" | result = Dummy ( )
for graph in graphs . __all__ :
cls = getattr ( graphs , graph )
setattr ( result , cls . short_name , cls ( self ) )
return result |
def from_api_repr ( cls , api_repr ) :
"""Return a ` ` SchemaField ` ` object deserialized from a dictionary .
Args :
api _ repr ( Mapping [ str , str ] ) : The serialized representation
of the SchemaField , such as what is output by
: meth : ` to _ api _ repr ` .
Returns :
google . cloud . biquery . sc... | # Handle optional properties with default values
mode = api_repr . get ( "mode" , "NULLABLE" )
description = api_repr . get ( "description" )
fields = api_repr . get ( "fields" , ( ) )
return cls ( field_type = api_repr [ "type" ] . upper ( ) , fields = [ cls . from_api_repr ( f ) for f in fields ] , mode = mode . uppe... |
def _srcRect_x ( self , attr_name ) :
"""Value of ` p : blipFill / a : srcRect / @ { attr _ name } ` or 0.0 if not present .""" | srcRect = self . blipFill . srcRect
if srcRect is None :
return 0.0
return getattr ( srcRect , attr_name ) |
def concat ( bed_files , catted = None ) :
"""recursively concat a set of BED files , returning a
sorted bedtools object of the result""" | bed_files = [ x for x in bed_files if x ]
if len ( bed_files ) == 0 :
if catted : # move to a . bed extension for downstream tools if not already
sorted_bed = catted . sort ( )
if not sorted_bed . fn . endswith ( ".bed" ) :
return sorted_bed . moveto ( sorted_bed . fn + ".bed" )
... |
def register_to_random_name ( grad_f ) :
"""Register a gradient function to a random string .
In order to use a custom gradient in TensorFlow , it must be registered to a
string . This is both a hassle , and - - because only one function can every be
registered to a string - - annoying to iterate on in an int... | grad_f_name = grad_f . __name__ + "_" + str ( uuid . uuid4 ( ) )
tf . RegisterGradient ( grad_f_name ) ( grad_f )
return grad_f_name |
def get_temp_url_key ( self , cached = True ) :
"""Returns the current TempURL key , or None if it has not been set .
By default the value returned is cached . To force an API call to get
the current value on the server , pass ` cached = False ` .""" | meta = self . _cached_temp_url_key
if not cached or not meta :
key = "temp_url_key"
meta = self . get_account_metadata ( ) . get ( key )
self . _cached_temp_url_key = meta
return meta |
def setdiff ( left , * rights , ** kwargs ) :
"""Exclude data from a collection , like ` except ` clause in SQL . All collections involved should
have same schema .
: param left : collection to drop data from
: param rights : collection or list of collections
: param distinct : whether to preserve duplicate... | import time
from . . utils import output
distinct = kwargs . get ( 'distinct' , False )
if isinstance ( rights [ 0 ] , list ) :
rights = rights [ 0 ]
cols = [ n for n in left . schema . names ]
types = [ n for n in left . schema . types ]
counter_col_name = 'exc_counter_%d' % int ( time . time ( ) )
left = left [ l... |
def _make_pull_imethod_resp ( objs , eos , context_id ) :
"""Create the correct imethod response for the open and pull methods""" | eos_tup = ( u'EndOfSequence' , None , eos )
enum_ctxt_tup = ( u'EnumerationContext' , None , context_id )
return [ ( "IRETURNVALUE" , { } , objs ) , enum_ctxt_tup , eos_tup ] |
def check ( text ) :
"""Flag offensive words based on the GLAAD reference guide .""" | err = "glaad.offensive_terms"
msg = "Offensive term. Remove it or consider the context."
list = [ "fag" , "faggot" , "dyke" , "sodomite" , "homosexual agenda" , "gay agenda" , "transvestite" , "homosexual lifestyle" , "gay lifestyle" # homo - may create false positives without additional context
# FIXME use topic detet... |
def serialize_args ( self ) :
"""Returns ( args , kwargs ) to be used when deserializing this parameter .""" | args , kwargs = super ( MultiParameter , self ) . serialize_args ( )
args . insert ( 0 , [ [ t . id , t . serialize_args ( ) ] for t in self . types ] )
return args , kwargs |
def get_router_id ( self , tenant_id , tenant_name ) :
"""Retrieve the router ID .""" | router_id = None
if tenant_id in self . tenant_dict :
router_id = self . tenant_dict . get ( tenant_id ) . get ( 'router_id' )
if not router_id :
router_list = self . os_helper . get_rtr_by_name ( 'FW_RTR_' + tenant_name )
if len ( router_list ) > 0 :
router_id = router_list [ 0 ] . get ( 'id' )
ret... |
def parse_solver_setting ( s ) :
"""Parse a string containing a solver setting""" | try :
key , value = s . split ( '=' , 1 )
except ValueError :
key , value = s , 'yes'
if key in ( 'rational' , 'integer' , 'quadratic' ) :
value = value . lower ( ) in ( '1' , 'yes' , 'true' , 'on' )
elif key in ( 'threads' , ) :
value = int ( value )
elif key in ( 'feasibility_tolerance' , 'optimality_... |
def atomic_output_file ( dest_path , make_parents = False , backup_suffix = None , suffix = ".partial.%s" ) :
"""A context manager for convenience in writing a file or directory in an atomic way . Set up
a temporary name , then rename it after the operation is done , optionally making a backup of
the previous f... | if dest_path == os . devnull : # Handle the ( probably rare ) case of writing to / dev / null .
yield dest_path
else :
tmp_path = ( "%s" + suffix ) % ( dest_path , new_uid ( ) )
if make_parents :
make_parent_dirs ( tmp_path )
yield tmp_path
# Note this is not in a finally block , so that res... |
def validate ( self , value ) :
"""Performs validation of the value .
: param value : value to validate
: raise ValidationError if the value is invalid""" | # check choices
if self . choices :
if isinstance ( self . choices [ 0 ] , ( list , tuple ) ) :
option_keys = [ k for k , v in self . choices ]
if value not in option_keys :
msg = ( 'Value {0} is not listed among valid choices {1}' . format ( value , option_keys ) )
self . ra... |
def gather_hinting ( config , rules , valid_paths ) :
"""Construct hint arguments for datanommer from a list of rules .""" | hinting = collections . defaultdict ( list )
for rule in rules :
root , name = rule . code_path . split ( ':' , 1 )
info = valid_paths [ root ] [ name ]
if info [ 'hints-callable' ] : # Call the callable hint to get its values
result = info [ 'hints-callable' ] ( config = config , ** rule . argument... |
def absolute_address ( self ) :
"""Get the absolute byte address of this node .
Indexes of all arrays in the node ' s lineage must be known
Raises
ValueError
If this property is referenced on a node whose array lineage is not
fully defined""" | if self . parent and not isinstance ( self . parent , RootNode ) :
return self . parent . absolute_address + self . address_offset
else :
return self . address_offset |
def length_degrees ( self ) :
'''Computes the length of the arc in degrees .
The length computation corresponds to what you would expect if you would draw the arc using matplotlib taking direction into account .
> > > Arc ( ( 0,0 ) , 1 , 0 , 0 , True ) . length _ degrees ( )
0.0
> > > Arc ( ( 0,0 ) , 2 , 0 ... | d_angle = self . sign * ( self . to_angle - self . from_angle )
if ( d_angle > 360 ) :
return 360.0
elif ( d_angle < 0 ) :
return d_angle % 360.0
else :
return abs ( d_angle ) |
def create_settings ( sender , ** kwargs ) :
"""create user notification settings on user creation""" | created = kwargs [ 'created' ]
user = kwargs [ 'instance' ]
if created :
UserWebNotificationSettings . objects . create ( user = user )
UserEmailNotificationSettings . objects . create ( user = user ) |
def expect_types ( __funcname = _qualified_name , ** named ) :
"""Preprocessing decorator that verifies inputs have expected types .
Examples
> > > @ expect _ types ( x = int , y = str )
. . . def foo ( x , y ) :
. . . return x , y
> > > foo ( 2 , ' 3 ' )
(2 , ' 3 ' )
> > > foo ( 2.0 , ' 3 ' ) # docte... | for name , type_ in iteritems ( named ) :
if not isinstance ( type_ , ( type , tuple ) ) :
raise TypeError ( "expect_types() expected a type or tuple of types for " "argument '{name}', but got {type_} instead." . format ( name = name , type_ = type_ , ) )
def _expect_type ( type_ ) : # Slightly different me... |
def _initialize_operation_name_to_id ( self ) :
"""Initializer for _ operation _ name _ to _ id .
Returns :
a { string : int } , mapping operation names to their index in _ operations .""" | operation_name_to_id = { }
for i , operation in enumerate ( self . _operations ) :
operation_name_to_id [ operation . name ] = i
return operation_name_to_id |
def do_start_cluster ( self , cluster ) :
"""Start the cluster
Usage :
> start _ cluster < cluster >""" | try :
cluster = api . get_cluster ( cluster )
cluster . start ( )
print ( "Starting Cluster" )
except ApiException :
print ( "Cluster not found" )
return None |
def factorize ( number ) :
"""Get the prime factors of an integer except for 1.
Parameters
number : int
Returns
primes : iterable
Examples
> > > factorize ( - 17)
[ - 1 , 17]
> > > factorize ( 8)
[2 , 2 , 2]
> > > factorize ( 3 * * 25)
[3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3... | if not isinstance ( number , int ) :
raise ValueError ( 'integer expected, but type(number)={}' . format ( type ( number ) ) )
if number < 0 :
return [ - 1 ] + factorize ( number * ( - 1 ) )
elif number == 0 :
raise ValueError ( 'All primes are prime factors of 0.' )
else :
for i in range ( 2 , int ( ma... |
def view_user ( self , user ) :
"""View the given user on the user page
: param user : the user to view
: type user : : class : ` jukeboxcore . djadapter . models . User `
: returns : None
: rtype : None
: raises : None""" | log . debug ( 'Viewing user %s' , user . username )
self . cur_user = None
self . pages_tabw . setCurrentIndex ( 9 )
self . user_username_le . setText ( user . username )
self . user_first_le . setText ( user . first_name )
self . user_last_le . setText ( user . last_name )
self . user_email_le . setText ( user . email... |
def CreateAdGroup ( client , campaign_id ) :
"""Creates a dynamic remarketing campaign .
Args :
client : an AdWordsClient instance .
campaign _ id : an int campaign ID .
Returns :
The ad group that was successfully created .""" | ad_group_service = client . GetService ( 'AdGroupService' , 'v201809' )
ad_group = { 'name' : 'Dynamic remarketing ad group' , 'campaignId' : campaign_id , 'status' : 'ENABLED' }
operations = [ { 'operator' : 'ADD' , 'operand' : ad_group } ]
return ad_group_service . mutate ( operations ) [ 'value' ] [ 0 ] |
def add_device ( self , resource_name , device ) :
"""Bind device to resource name""" | if device . resource_name is not None :
msg = 'The device %r is already assigned to %s'
raise ValueError ( msg % ( device , device . resource_name ) )
device . resource_name = resource_name
self . _internal [ device . resource_name ] = device |
def finished_or_stopped ( self ) :
"""Condition check on finished or stopped status
The method returns a value which is equivalent with not ' active ' status of the current state machine .
: return : outcome of condition check stopped or finished
: rtype : bool""" | return ( self . _status . execution_mode is StateMachineExecutionStatus . STOPPED ) or ( self . _status . execution_mode is StateMachineExecutionStatus . FINISHED ) |
def query_api ( app , client_id , imgur_id , is_album ) :
"""Query the Imgur API .
: raise APIError : When Imgur responds with errors or unexpected data .
: param sphinx . application . Sphinx app : Sphinx application object .
: param str client _ id : Imgur API client ID to use . https : / / api . imgur . co... | url = API_URL . format ( type = 'album' if is_album else 'image' , id = imgur_id )
headers = { 'Authorization' : 'Client-ID {}' . format ( client_id ) }
timeout = 5
# Query .
app . info ( 'querying {}' . format ( url ) )
try :
response = requests . get ( url , headers = headers , timeout = timeout )
except ( reques... |
def _compute_magnitude ( self , rup , C ) :
"""Compute the first term of the equation described on p . 199:
` ` b1 + b2 * M + b3 * M * * 2 ` `""" | return C [ 'b1' ] + ( C [ 'b2' ] * rup . mag ) + ( C [ 'b3' ] * ( rup . mag ** 2 ) ) |
def state ( self ) :
"""Reading returns a list of state flags . Possible flags are
` running ` , ` ramping ` , ` holding ` , ` overloaded ` and ` stalled ` .""" | self . _state , value = self . get_attr_set ( self . _state , 'state' )
return value |
def register_members ( self ) :
"""Collect the names of the class member and convert them to object
members .
Unlike Terms , the Group class members are converted into object
members , so the configuration data""" | self . _members = { name : attr for name , attr in iteritems ( type ( self ) . __dict__ ) if isinstance ( attr , Group ) }
for name , m in iteritems ( self . _members ) :
m . init_descriptor ( name , self ) |
def disconnect ( self , close = True ) :
"""Closes the connection as well as logs off any of the
Disconnects the TCP connection and shuts down the socket listener
running in a thread .
: param close : Will close all sessions in the connection as well as the
tree connections of each session .""" | if close :
for session in list ( self . session_table . values ( ) ) :
session . disconnect ( True )
log . info ( "Disconnecting transport connection" )
self . transport . disconnect ( ) |
def read_attributes ( self , attributes = None ) :
'''Collect read attributes across reads in this PileupCollection into a
pandas . DataFrame .
Valid attributes are the following properties of a pysam . AlignedSegment
instance . See :
http : / / pysam . readthedocs . org / en / latest / api . html # pysam .... | def include ( attribute ) :
return attributes is None or attribute in attributes
reads = self . reads ( )
possible_column_names = list ( PileupCollection . _READ_ATTRIBUTE_NAMES )
result = OrderedDict ( ( name , [ getattr ( read , name ) for read in reads ] ) for name in PileupCollection . _READ_ATTRIBUTE_NAMES if ... |
def model_import ( self ) :
"""Import and instantiate the non - JIT models and the JIT models .
Models defined in ` ` jits ` ` and ` ` non _ jits ` ` in ` ` models / _ _ init _ _ . py ` `
will be imported and instantiated accordingly .
Returns
None""" | # non - JIT models
for file , pair in non_jits . items ( ) :
for cls , name in pair . items ( ) :
themodel = importlib . import_module ( 'andes.models.' + file )
theclass = getattr ( themodel , cls )
self . __dict__ [ name ] = theclass ( self , name )
group = self . __dict__ [ name ]... |
def dateparser ( self , dformat = '%d/%m/%Y' ) :
"""Returns a date parser for pandas""" | def dateparse ( dates ) :
return [ pd . datetime . strptime ( d , dformat ) for d in dates ]
return dateparse |
def dropcols ( df , start = None , end = None ) :
"""Drop columns that contain NaN within [ start , end ] inclusive .
A wrapper around DataFrame . dropna ( ) that builds an easier * subset *
syntax for tseries - indexed DataFrames .
Parameters
df : DataFrame
start : str or datetime , default None
start ... | if isinstance ( df , Series ) :
raise ValueError ( "func only applies to `pd.DataFrame`" )
if start is None :
start = df . index [ 0 ]
if end is None :
end = df . index [ - 1 ]
subset = df . index [ ( df . index >= start ) & ( df . index <= end ) ]
return df . dropna ( axis = 1 , subset = subset ) |
def adapter ( self , adapter ) :
"""Sets the adapter instance under the " _ adapter " property in use by this class .
Also sets the adapter property for all implemented classes under this category .
: param adapter : New adapter instance to set for this class and all implemented classes under this category .
... | self . _adapter = adapter
for implemented_class in self . implemented_classes :
class_name = implemented_class . __name__ . lower ( )
getattr ( self , self . get_private_attr_name ( class_name ) ) . adapter = adapter |
def detect_encoding ( data , encoding = None , fallback = 'latin1' , is_html = False ) :
'''Detect the character encoding of the data .
Returns :
str : The name of the codec
Raises :
ValueError : The codec could not be detected . This error can only
occur if fallback is not a " lossless " codec .''' | if encoding :
encoding = normalize_codec_name ( encoding )
bs4_detector = EncodingDetector ( data , override_encodings = ( encoding , ) if encoding else ( ) , is_html = is_html )
candidates = itertools . chain ( bs4_detector . encodings , ( fallback , ) )
for candidate in candidates :
if not candidate :
... |
def params ( self ) :
"""A combined : class : ` MultiDict ` with values from : attr : ` forms ` and
: attr : ` GET ` . File - uploads are not included .""" | params = MultiDict ( self . GET )
for key , value in self . forms . iterallitems ( ) :
params [ key ] = value
return params |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.