signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def on_return ( self , node ) : # ( ' value ' , )
"""Return statement : look for None , return special sentinal .""" | self . retval = self . run ( node . value )
if self . retval is None :
self . retval = ReturnedNone
return |
def empty ( self , duration ) :
'''Empty label annotations .
Constructs a single observation with an empty value ( None ) .
Parameters
duration : number > 0
The duration of the annotation''' | ann = super ( DynamicLabelTransformer , self ) . empty ( duration )
ann . append ( time = 0 , duration = duration , value = None )
return ann |
def timeit_profile ( stmt , number , repeat , setup , profiler_factory , pickle_protocol , dump_filename , mono , ** _ignored ) :
"""Profile a Python statement like timeit .""" | del _ignored
globals_ = { }
exec_ ( setup , globals_ )
if number is None : # determine number so that 0.2 < = total time < 2.0 like timeit .
dummy_profiler = profiler_factory ( )
dummy_profiler . start ( )
for x in range ( 1 , 10 ) :
number = 10 ** x
t = time . time ( )
for y in rang... |
def envs ( self ) :
'''Return the available environments''' | ret = [ ]
for saltenv in self . opts [ 'pillar_roots' ] :
ret . append ( saltenv )
return ret |
def _get_cached_requirements ( requirements , saltenv ) :
'''Get the location of a cached requirements file ; caching if necessary .''' | req_file , senv = salt . utils . url . parse ( requirements )
if senv :
saltenv = senv
if req_file not in __salt__ [ 'cp.list_master' ] ( saltenv ) : # Requirements file does not exist in the given saltenv .
return False
cached_requirements = __salt__ [ 'cp.is_cached' ] ( requirements , saltenv )
if not cached_... |
def drain_OD ( q_plant , T , depth_end , SDR ) :
"""Return the nominal diameter of the entrance tank drain pipe . Depth at the
end of the flocculator is used for headloss and length calculation inputs in
the diam _ pipe calculation .
Parameters
q _ plant : float
Plant flow rate
T : float
Design temper... | nu = pc . viscosity_kinematic ( T )
K_minor = con . PIPE_ENTRANCE_K_MINOR + con . PIPE_EXIT_K_MINOR + con . EL90_K_MINOR
drain_ID = pc . diam_pipe ( q_plant , depth_end , depth_end , nu , mat . PVC_PIPE_ROUGH , K_minor )
drain_ND = pipe . SDR_available_ND ( drain_ID , SDR )
return pipe . OD ( drain_ND ) . magnitude |
def set_driver ( self , resource ) :
"""Set the driver for a neutron resource .
: param resource : Neutron resource in dict format .
Expected keys : :
' id ' : < value > ,
' hosting _ device ' : { ' id ' : < value > , } ,
' router _ type ' : { ' cfg _ agent _ driver ' : < value > , }
: returns : driver ... | try :
resource_id = resource [ 'id' ]
hosting_device = resource [ 'hosting_device' ]
hd_id = hosting_device [ 'id' ]
if hd_id in self . _hosting_device_routing_drivers_binding :
driver = self . _hosting_device_routing_drivers_binding [ hd_id ]
self . _drivers [ resource_id ] = driver
... |
def _prime_user_perm_caches ( self ) :
"""Prime both the user and group caches and put them on the ` ` self . user ` ` .
In addition add a cache filled flag on ` ` self . user ` ` .""" | perm_cache , group_perm_cache = self . _get_user_cached_perms ( )
self . user . _authority_perm_cache = perm_cache
self . user . _authority_group_perm_cache = group_perm_cache
self . user . _authority_perm_cache_filled = True |
def restore_attr ( self , attr_name ) :
"""Restore an attribute back onto the target object .
: param str attr _ name : the name of the attribute to restore""" | original_attr = self . _original_attr ( attr_name )
if self . _original_attr ( attr_name ) :
setattr ( self . obj . __class__ , attr_name , original_attr ) |
def _balanced_strand_gen ( base_aligns , limit ) :
'''given collection of random { aligns } , returns alternating forward / reverse
strands up to { total _ aligns } ; will return smaller of forward / reverse
collection if less than total _ aligns''' | predicate = lambda align : align . is_reverse
gen1 , gen2 = itertools . tee ( ( predicate ( align ) , align ) for align in base_aligns )
for_strand_gen = ( align for pred , align in gen1 if not pred )
rev_strand_gen = ( align for pred , align in gen2 if pred )
combined_gen = iter_zip ( for_strand_gen , rev_strand_gen )... |
def remove ( self ) :
'''a method to remove the entire table
: return string with status message''' | self . table . drop ( self . engine )
exit_msg = '%s table has been removed from %s database.' % ( self . table_name , self . database_name )
self . printer ( exit_msg )
return exit_msg |
def parse ( self ) :
"""The function for parsing the vcard to the vars dictionary .""" | keys = { 'fn' : self . _parse_name , 'kind' : self . _parse_kind , 'adr' : self . _parse_address , 'tel' : self . _parse_phone , 'email' : self . _parse_email , 'role' : self . _parse_role , 'title' : self . _parse_title }
for val in self . vcard :
try :
parser = keys . get ( val [ 0 ] )
parser ( va... |
def add_round_key ( state , rkey ) :
"""Transformation in the Cipher and Inverse Cipher in which a Round Key is
added to the State using an XOR operation . The length of a Round Key equals
the size of the State ( i . e . , for Nb = 4 , the Round Key length equals 128
bits / 16 bytes ) .""" | state = state . reshape ( 4 , 32 )
rkey = rkey . reshape ( 4 , 32 )
return fcat ( state [ 0 ] ^ rkey [ 0 ] , state [ 1 ] ^ rkey [ 1 ] , state [ 2 ] ^ rkey [ 2 ] , state [ 3 ] ^ rkey [ 3 ] , ) |
def binary_cross_entropy_with_logits ( input_ , target , name = PROVIDED , loss_weight = None , per_example_weights = None , per_output_weights = None ) :
"""Calculates the binary cross entropy of the input _ vs inputs .
Expects unscaled logits . Do not pass in results of sigmoid operation .
Args :
input _ : ... | if target is None :
raise ValueError ( 'target must be set' )
target = _convert_and_assert_tensors_compatible ( input_ , target )
with tf . name_scope ( 'stats' ) :
selected , sum_retrieved , sum_relevant = _compute_precision_recall ( input_ , target , 0 , per_example_weights )
precision = selected / sum_re... |
def get_http_header ( self ) -> Response :
'''Return the HTTP header .
It only attempts to read the first 4 KiB of the payload .
Returns :
Response , None : Returns an instance of
: class : ` . http . request . Response ` or None .''' | with wpull . util . reset_file_offset ( self . block_file ) :
data = self . block_file . read ( 4096 )
match = re . match ( br'(.*?\r?\n\r?\n)' , data )
if not match :
return
status_line , dummy , field_str = match . group ( 1 ) . partition ( b'\n' )
try :
version , code , reason = Response . parse_status_l... |
def use_mutation ( module_path , operator , occurrence ) :
"""A context manager that applies a mutation for the duration of a with - block .
This applies a mutation to a file on disk , and after the with - block it put the unmutated code
back in place .
Args :
module _ path : The path to the module to mutat... | original_code , mutated_code = apply_mutation ( module_path , operator , occurrence )
try :
yield original_code , mutated_code
finally :
with module_path . open ( mode = 'wt' , encoding = 'utf-8' ) as handle :
handle . write ( original_code )
handle . flush ( ) |
def select_catalogue_within_cell ( self , selector , distance , upper_depth = None , lower_depth = None ) :
'''Selects catalogue of earthquakes within distance from point
: param selector :
Populated instance of : class :
` openquake . hmtk . seismicity . selector . CatalogueSelector `
: param distance :
... | self . catalogue = selector . cartesian_square_centred_on_point ( self . geometry , distance )
if self . catalogue . get_number_events ( ) < 5 : # Throw a warning regarding the small number of earthquakes in
# the source !
warnings . warn ( 'Source %s (%s) has fewer than 5 events' % ( self . id , self . name ) ) |
def create_role ( self , name , role_type , project_id , ttl = "" , max_ttl = "" , period = "" , policies = None , bound_service_accounts = None , max_jwt_exp = '15m' , allow_gce_inference = True , bound_zones = None , bound_regions = None , bound_instance_groups = None , bound_labels = None , mount_point = DEFAULT_MOU... | type_specific_params = { 'iam' : { 'max_jwt_exp' : '15m' , 'allow_gce_inference' : True , } , 'gce' : { 'bound_zones' : None , 'bound_regions' : None , 'bound_instance_groups' : None , 'bound_labels' : None , } , }
list_of_strings_params = { 'policies' : policies , 'bound_service_accounts' : bound_service_accounts , 'b... |
def plotShape ( includePost = [ 'all' ] , includePre = [ 'all' ] , showSyns = False , showElectrodes = False , synStyle = '.' , synSiz = 3 , dist = 0.6 , cvar = None , cvals = None , iv = False , ivprops = None , includeAxon = True , bkgColor = None , fontSize = 12 , figSize = ( 10 , 8 ) , saveData = None , dpi = 300 ,... | from . . import sim
from neuron import h
print ( 'Plotting 3D cell shape ...' )
cellsPreGids = [ c . gid for c in sim . getCellsList ( includePre ) ] if includePre else [ ]
cellsPost = sim . getCellsList ( includePost )
if not hasattr ( sim . net , 'compartCells' ) :
sim . net . compartCells = [ c for c in cellsPos... |
def _delete_port_channel_resources ( self , host_id , switch_ip , intf_type , nexus_port , port_id ) :
'''This determines if port channel id needs to be freed .''' | # if this connection is not a port - channel , nothing to do .
if intf_type != 'port-channel' :
return
# Check if this driver created it and its no longer needed .
try :
vpc = nxos_db . get_switch_vpc_alloc ( switch_ip , nexus_port )
except excep . NexusVPCAllocNotFound : # This can occur for non - baremetal co... |
def update ( self , deltat = 1.0 ) :
'''straight lines , with short life''' | DNFZ . update ( self , deltat )
self . lifetime -= deltat
if self . lifetime <= 0 :
self . randpos ( )
self . lifetime = random . uniform ( 300 , 600 ) |
def enqueue_command ( self , command , data ) :
"""Enqueue command into command queues""" | if command == CommandType . TrialEnd or ( command == CommandType . ReportMetricData and data [ 'type' ] == 'PERIODICAL' ) :
self . assessor_command_queue . put ( ( command , data ) )
else :
self . default_command_queue . put ( ( command , data ) )
qsize = self . default_command_queue . qsize ( )
if qsize >= QUE... |
def __range ( a , bins ) :
'''Compute the histogram range of the values in the array a according to
scipy . stats . histogram .''' | a = numpy . asarray ( a )
a_max = a . max ( )
a_min = a . min ( )
s = 0.5 * ( a_max - a_min ) / float ( bins - 1 )
return ( a_min - s , a_max + s ) |
def save ( f , arr , vocab ) :
"""Save word embedding file .
Check : func : ` word _ embedding _ loader . saver . glove . save ` for the API .""" | f . write ( ( '%d %d' % ( arr . shape [ 0 ] , arr . shape [ 1 ] ) ) . encode ( 'utf-8' ) )
for word , idx in vocab :
_write_line ( f , arr [ idx ] , word ) |
def write_failure_file ( failure_msg ) : # type : ( str ) - > None
"""Create a file ' failure ' if training fails after all algorithm output ( for example , logging ) completes ,
the failure description should be written to this file . In a DescribeTrainingJob response , Amazon SageMaker
returns the first 1024 ... | file_path = os . path . join ( _env . output_dir , 'failure' )
write_file ( file_path , failure_msg ) |
def depth ( self ) :
"""The number of hierarchy levels in this category graph . Returns 0 if
it contains no categories .""" | categories = self . _categories
if not categories :
return 0
first_depth = categories [ 0 ] . depth
for category in categories [ 1 : ] :
if category . depth != first_depth :
raise ValueError ( 'category depth not uniform' )
return first_depth |
def dock_help ( ) :
"""Help message for Dock Widget .
. . versionadded : : 3.2.1
: returns : A message object containing helpful information .
: rtype : messaging . message . Message""" | message = m . Message ( )
message . add ( m . Brand ( ) )
message . add ( heading ( ) )
message . add ( content ( ) )
return message |
def keep_params_s ( s , params ) :
"""Keep the given parameters from a string
Same as : meth : ` keep _ params ` but does not use the : attr : ` params `
dictionary
Parameters
s : str
The string of the parameters like section
params : list of str
The parameter names to keep
Returns
str
The modif... | patt = '(?s)' + '|' . join ( '(?<=\n)' + s + '\s*:.+?\n(?=\S+|$)' for s in params )
return '' . join ( re . findall ( patt , '\n' + s . strip ( ) + '\n' ) ) . rstrip ( ) |
def list_adb_devices_by_usb_id ( ) :
"""List the usb id of all android devices connected to the computer that
are detected by adb .
Returns :
A list of strings that are android device usb ids . Empty if there ' s
none .""" | out = adb . AdbProxy ( ) . devices ( [ '-l' ] )
clean_lines = new_str ( out , 'utf-8' ) . strip ( ) . split ( '\n' )
results = [ ]
for line in clean_lines :
tokens = line . strip ( ) . split ( )
if len ( tokens ) > 2 and tokens [ 1 ] == 'device' :
results . append ( tokens [ 2 ] )
return results |
def get_ntlm_response ( self , flags , challenge , target_info = None , channel_binding = None ) :
"""Computes the 24 byte NTLM challenge response given the 8 byte server challenge , along with the session key .
If NTLMv2 is used , the TargetInfo structure must be supplied , the updated TargetInfo structure will ... | # TODO : IMPLEMENT THE FOLLOWING FEATURES
# If NTLM v2 authentication is used and the CHALLENGE _ MESSAGE does not contain both MsvAvNbComputerName and
# MsvAvNbDomainName AVPairs and either Integrity is TRUE or Confidentiality is TRUE , then return STATUS _ LOGON _ FAILURE .
# If NTLM v2 authentication is used and the... |
def InputSplines ( seq_length , n_bases = 10 , name = None , ** kwargs ) :
"""Input placeholder for array returned by ` encodeSplines `
Wrapper for : ` keras . layers . Input ( ( seq _ length , n _ bases ) , name = name , * * kwargs ) `""" | return Input ( ( seq_length , n_bases ) , name = name , ** kwargs ) |
def get_all_fields ( cls , class_obj = None , fields = None ) :
"""TODO : This needs to be properly used""" | def return_fields ( obj ) :
internal_fields = fields
if internal_fields is None :
internal_fields = { }
for attribute in dir ( obj ) :
try :
attr_val = getattr ( obj , attribute )
attr_cls = attr_val . __class__
# If it is a model field , call on init
... |
def charts_slug_pollster_trendlines_tsv_get ( self , slug , ** kwargs ) :
"""Estimates of what the polls suggest about trends
Derived data presented on a Pollster Chart . The trendlines on a Pollster chart don ' t add up to 100 : we calculate each label ' s trendline separately . Use the ` charts / { slug } ` res... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . charts_slug_pollster_trendlines_tsv_get_with_http_info ( slug , ** kwargs )
else :
( data ) = self . charts_slug_pollster_trendlines_tsv_get_with_http_info ( slug , ** kwargs )
return data |
def bottom ( self ) :
"""Bottom coordinate .""" | if self . _has_real ( ) :
return self . _data . real_bottom
return self . _data . bottom |
def on_set ( self , key , value ) :
"""Callback called on successful set . Uses function from _ _ init _ _ .""" | if self . _on_set is not None :
self . _on_set ( key , value ) |
def automatic_density ( cls , structure , kppa , chksymbreak = None , use_symmetries = True , use_time_reversal = True , shifts = ( 0.5 , 0.5 , 0.5 ) ) :
"""Returns an automatic Kpoint object based on a structure and a kpoint
density . Uses Gamma centered meshes for hexagonal cells and Monkhorst - Pack grids othe... | lattice = structure . lattice
lengths = lattice . abc
shifts = np . reshape ( shifts , ( - 1 , 3 ) )
ngrid = kppa / structure . num_sites / len ( shifts )
mult = ( ngrid * lengths [ 0 ] * lengths [ 1 ] * lengths [ 2 ] ) ** ( 1 / 3. )
num_div = [ int ( round ( 1.0 / lengths [ i ] * mult ) ) for i in range ( 3 ) ]
# ensu... |
def url ( self ) :
"""Return the admin url of the object .""" | return urlresolvers . reverse ( "admin:%s_%s_change" % ( self . content_type . app_label , self . content_type . model ) , args = ( self . get_object ( ) . uid , ) ) |
def lmeasure ( reference_intervals_hier , reference_labels_hier , estimated_intervals_hier , estimated_labels_hier , frame_size = 0.1 , beta = 1.0 ) :
'''Computes the tree measures for hierarchical segment annotations .
Parameters
reference _ intervals _ hier : list of ndarray
` ` reference _ intervals _ hier... | # Compute the number of frames in the window
if frame_size <= 0 :
raise ValueError ( 'frame_size ({:.2f}) must be a positive ' 'number.' . format ( frame_size ) )
# Validate the hierarchical segmentations
validate_hier_intervals ( reference_intervals_hier )
validate_hier_intervals ( estimated_intervals_hier )
# Bui... |
def all_to_public ( self ) :
"""Sets all members , types and executables in this module as public as
long as it doesn ' t already have the ' private ' modifier .""" | if "private" not in self . modifiers :
def public_collection ( attribute ) :
for key in self . collection ( attribute ) :
if key not in self . publics :
self . publics [ key . lower ( ) ] = 1
public_collection ( "members" )
public_collection ( "types" )
public_collect... |
def merge ( left , right , how = "inner" , on = None , left_on = None , right_on = None , left_index = False , right_index = False , sort = False , suffixes = ( "_x" , "_y" ) , copy = True , indicator = False , validate = None , ) :
"""Database style join , where common columns in " on " are merged .
Args :
lef... | if not isinstance ( left , DataFrame ) :
raise ValueError ( "can not merge DataFrame with instance of type {}" . format ( type ( right ) ) )
return left . merge ( right , how = how , on = on , left_on = left_on , right_on = right_on , left_index = left_index , right_index = right_index , sort = sort , suffixes = su... |
def LoadInstallations ( counter ) :
"""Load installed packages and export the version map .
This function may be called multiple times , but the counters will
be increased each time . Since Prometheus counters are never
decreased , the aggregated results will not make sense .""" | process = subprocess . Popen ( [ "pip" , "list" , "--format=json" ] , stdout = subprocess . PIPE )
output , _ = process . communicate ( )
installations = json . loads ( output )
for i in installations :
counter . labels ( i [ "name" ] , i [ "version" ] ) . inc ( ) |
def dataset_from_dataframe ( df , delays = ( 1 , 2 , 3 ) , inputs = ( 1 , 2 , - 1 ) , outputs = ( - 1 , ) , normalize = False , verbosity = 1 ) :
"""Compose a pybrain . dataset from a pandas DataFrame
Arguments :
delays ( list of int ) : sample delays to use for the input tapped delay line
Positive and negati... | if isinstance ( delays , int ) :
if delays :
delays = range ( 1 , delays + 1 )
else :
delays = [ 0 ]
delays = np . abs ( np . array ( [ int ( i ) for i in delays ] ) )
inputs = [ df . columns [ int ( inp ) ] if isinstance ( inp , ( float , int ) ) else str ( inp ) for inp in inputs ]
outputs = [... |
def arabicrange ( ) :
u"""return a list of arabic characteres .
Return a list of characteres between \u060c to \u0652
@ return : list of arabic characteres .
@ rtype : unicode""" | mylist = [ ]
for i in range ( 0x0600 , 0x00653 ) :
try :
mylist . append ( unichr ( i ) )
except NameError : # python 3 compatible
mylist . append ( chr ( i ) )
except ValueError :
pass
return mylist |
def load ( self , data , context = None ) :
"""Deserialize data from primitive types . Raises
: exc : ` ~ lollipop . errors . ValidationError ` if data is invalid .
: param data : Data to deserialize .
: param context : Context data .
: returns : Loaded data
: raises : : exc : ` ~ lollipop . errors . Vali... | errors_builder = ValidationErrorBuilder ( )
for validator in self . validators :
try :
validator ( data , context )
except ValidationError as ve :
errors_builder . add_errors ( ve . messages )
errors_builder . raise_errors ( )
return data |
def stop ( self , id ) :
"""stop the tracker .""" | path = partial ( _path , self . adapter )
path = path ( id )
return self . _delete ( path ) |
def handle ( self , dict ) :
'''Processes a vaild zookeeper request
@ param dict : a valid dictionary object''' | # format key
key = "zk:{action}:{domain}:{appid}" . format ( action = dict [ 'action' ] , appid = dict [ 'appid' ] , domain = dict [ 'domain' ] )
d = { "domain" : dict [ 'domain' ] , "uuid" : dict [ 'uuid' ] }
if dict [ 'action' ] == 'domain-update' :
if dict [ 'hits' ] != 0 and dict [ 'window' ] != 0 :
d [... |
def _set_protected_port ( self , v , load = False ) :
"""Setter method for protected _ port , mapped from YANG variable / interface / hundredgigabitethernet / protected _ port ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ protected _ port is considered a... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = protected_port . protected_port , is_container = 'container' , presence = False , yang_name = "protected-port" , rest_name = "protected-port" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmetho... |
def clear_recovery_range ( working_dir ) :
"""Clear out our recovery hint""" | recovery_range_path = os . path . join ( working_dir , '.recovery' )
if os . path . exists ( recovery_range_path ) :
os . unlink ( recovery_range_path ) |
def predict ( self , data , output_margin = False , ntree_limit = 0 , pred_leaf = False ) :
"""Predict with data .
NOTE : This function is not thread safe .
For each booster object , predict can only be called from one thread .
If you want to run prediction using multiple thread , call bst . copy ( ) to make ... | option_mask = 0x00
if output_margin :
option_mask |= 0x01
if pred_leaf :
option_mask |= 0x02
self . _validate_features ( data )
length = ctypes . c_ulong ( )
preds = ctypes . POINTER ( ctypes . c_float ) ( )
_check_call ( _LIB . XGBoosterPredict ( self . handle , data . handle , option_mask , ntree_limit , ctyp... |
def set_new_version ( new_version : str ) -> bool :
"""Replaces the version number in the correct place and writes the changed file to disk .
: param new _ version : The new version number as a string .
: return : ` True ` if it succeeded .""" | filename , variable = config . get ( 'semantic_release' , 'version_variable' ) . split ( ':' )
variable = variable . strip ( )
with open ( filename , mode = 'r' ) as fr :
content = fr . read ( )
content = replace_version_string ( content , variable , new_version )
with open ( filename , mode = 'w' ) as fw :
fw ... |
def from_inline ( cls : Type [ ESCoreEndpointType ] , inline : str ) -> ESCoreEndpointType :
"""Return ESCoreEndpoint instance from endpoint string
: param inline : Endpoint string
: return :""" | m = ESCoreEndpoint . re_inline . match ( inline )
if m is None :
raise MalformedDocumentError ( ESCoreEndpoint . API )
server = m . group ( 1 )
port = int ( m . group ( 2 ) )
return cls ( server , port ) |
def std ( self , axis ) :
"""Returns d - 1 dimensional histogram of ( estimated ) std value along axis
NB this is very different from just std of the histogram values ( which describe bin counts )""" | def weighted_std ( values , weights , axis ) : # Stolen from http : / / stackoverflow . com / questions / 2413522
average = np . average ( values , weights = weights , axis = axis )
average = average [ self . _simsalabim_slice ( axis ) ]
variance = np . average ( ( values - average ) ** 2 , weights = weight... |
def update_uris ( self , new_uri ) :
"""Update all URIS .
: param new _ uri : URI to switch to and update the matching
: returns : n / a
Note : This overwrites any existing URI""" | self . uri = new_uri
# if there is a sub - service , update it too
if self . obj :
self . obj . base_url = '{0}/{1}' . format ( self . uri , self . service_name ) |
def _load_rsa_private_key ( pem ) :
"""PEM encoded PKCS # 8 private key - > rsa . PrivateKey .""" | # ADB uses private RSA keys in pkcs # 8 format . ' rsa ' library doesn ' t support
# them natively . Do some ASN unwrapping to extract naked RSA key
# ( in der - encoded form ) . See https : / / www . ietf . org / rfc / rfc2313 . txt .
# Also http : / / superuser . com / a / 606266.
try :
der = rsa . pem . load_pem... |
def build_docker ( ctx , image ) :
"""build docker images""" | if image not in DOCKER_IMGS :
print ( 'Error: unknown docker image "{0}"!' . format ( image ) , file = sys . stderr )
sys . exit ( 1 )
dinfo = DOCKER_IMGS [ image ]
ctx . run ( 'docker rmi -f {0}' . format ( dinfo [ 'name' ] ) , warn = True )
dinfo_work_dir = os . path . join ( dinfo [ 'path' ] , '_work' )
ctx ... |
def check_error_cmd ( result ) :
"""Checks if any function returns an error from firmware in USB - CANmodul .
: param ReturnCode result : Error code of the function .
: return : True if a function returned error from firmware , otherwise False .
: rtype : bool""" | return ( result . value >= ReturnCode . ERRCMD ) and ( result . value < ReturnCode . WARNING ) |
def interpolate_logscale ( start , end , steps ) :
"""Interpolate series between start and end in given number of steps - logscale interpolation""" | if start <= 0.0 :
warnings . warn ( "Start of logscale interpolation must be positive!" )
start = 1e-5
return np . logspace ( np . log10 ( float ( start ) ) , np . log10 ( float ( end ) ) , steps ) |
def movementCompute ( self , displacement , noiseFactor = 0 , moduleNoiseFactor = 0 ) :
"""@ param displacement ( dict )
The change in location . Example : { " top " : 10 , " left " , 10}
@ return ( dict )
Data for logging / tracing .""" | if noiseFactor != 0 :
xdisp = np . random . normal ( 0 , noiseFactor )
ydisp = np . random . normal ( 0 , noiseFactor )
else :
xdisp = 0
ydisp = 0
locationParams = { "displacement" : [ displacement [ "top" ] + ydisp , displacement [ "left" ] + xdisp ] , "noiseFactor" : moduleNoiseFactor }
for module in ... |
def _load_prev ( self ) :
"""Load the next days data ( or file ) without decrementing the date .
Repeated calls will not decrement date / file and will produce the same
data
Uses info stored in object to either decrement the date ,
or the file . Looks for self . _ load _ by _ date flag .""" | if self . _load_by_date :
prev_date = self . date - pds . DateOffset ( days = 1 )
return self . _load_data ( date = prev_date )
else :
return self . _load_data ( fid = self . _fid - 1 ) |
def get_close_matches ( word , possibilities , n = None , cutoff = 0.6 ) :
"""Overrides ` difflib . get _ close _ match ` to controle argument ` n ` .""" | if n is None :
n = settings . num_close_matches
return difflib_get_close_matches ( word , possibilities , n , cutoff ) |
def load_keypair ( keypair_file ) :
'''load a keypair from a keypair file . We add attributes key ( the raw key )
and public _ key ( the url prepared public key ) to the client .
Parameters
keypair _ file : the pem file to load .''' | from Crypto . PublicKey import RSA
# Load key
with open ( keypair_file , 'rb' ) as filey :
key = RSA . import_key ( filey . read ( ) )
return quote_plus ( key . publickey ( ) . exportKey ( ) . decode ( 'utf-8' ) ) |
def _shuffle_field ( self , * args ) :
"""Permute field""" | p = self . _permutation
fields = [ ]
for arg in args :
fields . append ( arg [ p ] )
if len ( fields ) == 1 :
return fields [ 0 ]
else :
return fields |
def pause ( self , payload ) :
"""Start the daemon and all processes or only specific processes .""" | # Pause specific processes , if ` keys ` is given in the payload
if payload . get ( 'keys' ) :
succeeded = [ ]
failed = [ ]
for key in payload . get ( 'keys' ) :
success = self . process_handler . pause_process ( key )
if success :
succeeded . append ( str ( key ) )
else ... |
def receive ( self , msg ) :
'''The message received from the queue specify a method of the
class the actor represents . This invokes it . If the
communication is an ASK , sends the result back
to the channel included in the message as an
ASKRESPONSE .
If it is a FUTURE , generates a FUTURERESPONSE
to s... | if msg [ TYPE ] == TELL and msg [ METHOD ] == 'stop' :
self . running = False
self . future_manager . stop ( )
else :
result = None
try :
invoke = getattr ( self . _obj , msg [ METHOD ] )
params = msg [ PARAMS ]
result = invoke ( * params [ 0 ] , ** params [ 1 ] )
except Exce... |
def get_next_interval_histogram ( self , range_start_time_sec = 0.0 , range_end_time_sec = sys . maxsize , absolute = False ) :
'''Read the next interval histogram from the log , if interval falls
within an absolute or relative time range .
Timestamps are assumed to appear in order in the log file , and as such... | return self . _decode_next_interval_histogram ( None , range_start_time_sec , range_end_time_sec , absolute ) |
def url_defaults ( self , func : Callable , name : AppOrBlueprintKey = None ) -> Callable :
"""Add a url default preprocessor .
This is designed to be used as a decorator . An example usage ,
. . code - block : : python
@ app . url _ defaults
def default ( endpoint , values ) :""" | self . url_default_functions [ name ] . append ( func )
return func |
def remove ( self , index ) :
"""Remove chunk at index .
Doesn ' t actually delete data , copies last chunk ' s data over data to be
removed , and decreases the count""" | assert index < self . count
last_index = self . count - 1
data = self . get ( index )
if index == last_index : # easy case - nothing to do except zero last chunk
last_data = data
moved = None
else :
last_data = self . get ( last_index )
# copy the last chunk ' s data over the data to be deleted
data... |
def start_pty_request ( self , channel , term , modes ) :
"""Start a PTY - intended to run it a ( green ) thread .""" | request = self . dummy_request ( )
request . _sock = channel
request . modes = modes
request . term = term
request . username = self . username
# This should block until the user quits the pty
self . pty_handler ( request , self . client_address , self . tcp_server , self . vfs , self . session )
# Shutdown the entire ... |
def accept_record ( self , record ) :
"""Accept a record for inclusion in the community .
: param record : Record object .""" | with db . session . begin_nested ( ) :
req = InclusionRequest . get ( self . id , record . id )
if req is None :
raise InclusionRequestMissingError ( community = self , record = record )
req . delete ( )
self . add_record ( record )
self . last_record_accepted = datetime . utcnow ( ) |
def graph_key_from_tag ( tag , entity_index ) :
"""Returns a key from a tag entity
Args :
tag ( tag ) : this is the tag selected to get the key from
entity _ index ( int ) : this is the index of the tagged entity
Returns :
str : String representing the key for the given tagged entity .""" | start_token = tag . get ( 'start_token' )
entity = tag . get ( 'entities' , [ ] ) [ entity_index ]
return str ( start_token ) + '-' + entity . get ( 'key' ) + '-' + str ( entity . get ( 'confidence' ) ) |
def MakeRequest ( self , data ) :
"""Make a HTTP Post request to the server ' control ' endpoint .""" | stats_collector_instance . Get ( ) . IncrementCounter ( "grr_client_sent_bytes" , len ( data ) )
# Verify the response is as it should be from the control endpoint .
response = self . http_manager . OpenServerEndpoint ( path = "control?api=%s" % config . CONFIG [ "Network.api" ] , verify_cb = self . VerifyServerControl... |
def print ( cls , * args , ** kwargs ) :
"""Print synchronized .""" | # pylint : disable = protected - access
with _shared . _PRINT_LOCK :
print ( * args , ** kwargs )
_sys . stdout . flush ( ) |
def read_request_from_str ( data , ** params ) :
"""从字符串中读取请求头 , 并根据格式化字符串模板 , 进行字符串格式化
: param data :
: param params :
: return :""" | method , uri = None , None
headers = { }
host = ''
try :
split_list = data . split ( '\n\n' )
headers_text = split_list [ 0 ]
body = '\n\n' . join ( split_list [ 1 : ] )
except :
headers_text = data
body = ''
body = force_bytes ( body )
for k , v in params . items ( ) :
body = body . replace ( b... |
def map2set ( data , relation ) :
"""EXPECTING A is _ data ( relation ) THAT MAPS VALUES TO lists
THE LISTS ARE EXPECTED TO POINT TO MEMBERS OF A SET
A set ( ) IS RETURNED""" | if data == None :
return Null
if isinstance ( relation , Data ) :
Log . error ( "Does not accept a Data" )
if is_data ( relation ) :
try : # relation [ d ] is expected to be a list
# return set ( cod for d in data for cod in relation [ d ] )
output = set ( )
for d in data :
f... |
def run_function ( app_function , event , context ) :
"""Given a function and event context ,
detect signature and execute , returning any result .""" | # getargspec does not support python 3 method with type hints
# Related issue : https : / / github . com / Miserlou / Zappa / issues / 1452
if hasattr ( inspect , "getfullargspec" ) : # Python 3
args , varargs , keywords , defaults , _ , _ , _ = inspect . getfullargspec ( app_function )
else : # Python 2
args ,... |
def missing_representative_structure ( self ) :
"""list : List of genes with no mapping to a representative structure .""" | return [ x . id for x in self . genes if not self . genes_with_a_representative_structure . has_id ( x . id ) ] |
def get_translation_args ( self , args ) :
"""Returns linguist args from model args .""" | translation_args = [ ]
for arg in args :
condition = self . _get_linguist_condition ( arg , transform = True )
if condition :
translation_args . append ( condition )
return translation_args |
def add_done_callback ( self , fn ) :
"""Attaches a callable that will be called when the future finishes .
Args :
fn : A callable that will be called with this future as its only
argument when the future completes or is cancelled . The callable
will always be called by a thread in the same process in which... | with self . _condition :
if self . _state not in [ CANCELLED , CANCELLED_AND_NOTIFIED , FINISHED ] :
self . _done_callbacks . append ( fn )
return
fn ( self ) |
def resolve_id ( marked_id ) :
"""Given a marked ID , returns the original ID and its : tl : ` Peer ` type .""" | if marked_id >= 0 :
return marked_id , types . PeerUser
# There have been report of chat IDs being 10000xyz , which means their
# marked version is - 10000xyz , which in turn looks like a channel but
# it becomes 00xyz ( = xyz ) . Hence , we must assert that there are only
# two zeroes .
m = re . match ( r'-100([^0... |
def _to_fields ( self , data ) :
'''Return generator over the ( numerical ) PLY representation of the
list data ( length followed by actual data ) .''' | ( len_t , val_t ) = self . list_dtype ( )
data = _np . asarray ( data , dtype = val_t ) . ravel ( )
yield _np . dtype ( len_t ) . type ( data . size )
for x in data :
yield x |
def fetch_results_from_source ( self , * fields , dataframe = False ) :
"""Get values for specific fields in the elasticsearch index , from source
: param fields : a list of fields that have to be retrieved from the index
: param dataframe : if true , will return the data in the form of a pandas . DataFrame
:... | if not fields :
raise AttributeError ( "Please provide the fields to get from elasticsearch!" )
self . reset_aggregations ( )
self . search = self . search . extra ( _source = fields )
self . search = self . search . extra ( size = self . size )
response = self . search . execute ( )
hits = response . to_dict ( ) [... |
def _convertUnitAsWords ( self , unitText ) :
"""Converts text units into their number value .
@ type unitText : string
@ param unitText : number text to convert
@ rtype : integer
@ return : numerical value of unitText""" | word_list , a , b = re . split ( r"[,\s-]+" , unitText ) , 0 , 0
for word in word_list :
x = self . ptc . small . get ( word )
if x is not None :
a += x
elif word == "hundred" :
a *= 100
else :
x = self . ptc . magnitude . get ( word )
if x is not None :
b += ... |
def process_teffs ( self , teffs , coords , s = np . array ( [ 0. , 0. , 1. ] ) , t = None ) :
"""Change the local effective temperatures for any values within the
" cone " defined by the spot . Any teff within the spot will have its
current value multiplied by the " relteff " factor
: parameter array teffs :... | if t is None : # then assume at t0
t = self . _t0
pointing_vector = self . pointing_vector ( s , t )
logger . debug ( "spot.process_teffs at t={} with pointing_vector={} and radius={}" . format ( t , pointing_vector , self . _radius ) )
cos_alpha_coords = np . dot ( coords , pointing_vector ) / np . linalg . norm (... |
def format_table ( table , column_names = None , column_specs = None , max_col_width = 32 , report_dimensions = False ) :
'''Table pretty printer .
Expects tables to be given as arrays of arrays .
Example :
print format _ table ( [ [ 1 , " 2 " ] , [ 3 , " 456 " ] ] , column _ names = [ ' A ' , ' B ' ] )''' | if len ( table ) > 0 :
col_widths = [ 0 ] * len ( list ( table ) [ 0 ] )
elif column_specs is not None :
col_widths = [ 0 ] * ( len ( column_specs ) + 1 )
elif column_names is not None :
col_widths = [ 0 ] * len ( column_names )
my_column_names = [ ]
if column_specs is not None :
column_names = [ 'Row' ... |
async def on_raw_317 ( self , message ) :
"""WHOIS idle time .""" | target , nickname , idle_time = message . params [ : 3 ]
info = { 'idle' : int ( idle_time ) , }
if nickname in self . _pending [ 'whois' ] :
self . _whois_info [ nickname ] . update ( info ) |
def extractGlyph ( self , glyph , pointPen = None , onlyGeometry = False ) :
"""" rehydrate " to a glyph . this requires
a glyph as an argument . if a point pen other
than the type of pen returned by glyph . getPointPen ( )
is required for drawing , send this the needed point pen .""" | if pointPen is None :
pointPen = glyph . getPointPen ( )
glyph . clearContours ( )
glyph . clearComponents ( )
glyph . clearAnchors ( )
glyph . clearGuidelines ( )
glyph . lib . clear ( )
cleanerPen = FilterRedundantPointPen ( pointPen )
self . drawPoints ( cleanerPen )
glyph . anchors = [ dict ( anchor ) for ancho... |
def main ( host = 'localhost' , port = 8086 ) :
"""Instantiate the connection to the InfluxDB client .""" | user = 'root'
password = 'root'
dbname = 'demo'
protocol = 'json'
client = DataFrameClient ( host , port , user , password , dbname )
print ( "Create pandas DataFrame" )
df = pd . DataFrame ( data = list ( range ( 30 ) ) , index = pd . date_range ( start = '2014-11-16' , periods = 30 , freq = 'H' ) , columns = [ '0' ] ... |
def _end_session ( self , kill = None ) :
"""End the client session .""" | if self . _stc :
if kill is None :
kill = os . environ . get ( 'STC_SESSION_TERMINATE_ON_DISCONNECT' )
kill = _is_true ( kill )
self . _stc . end_session ( kill )
self . _stc = None |
def assign_ranks_by_cluster ( grid , n , ranks = None ) :
"""Takes a 2D array representing phenotypes or resource sets across the world ,
and integer rpresenting the maximum number of clusters allowed , and
optionally a dictionary indicating the rank of the cluster of each
phenotype / resource set . If this d... | if ranks is None :
ranks = generate_ranks ( grid , n )
return assign_ranks_to_grid ( grid , ranks ) , len ( ranks ) |
def gradient_black ( self , text = None , fore = None , back = None , style = None , start = None , step = 1 , reverse = False , linemode = True , movefactor = 2 , rgb_mode = False ) :
"""Return a black and white gradient .
Arguments :
text : String to colorize .
This will always be greater than 0.
fore : F... | gradargs = { 'step' : step , 'fore' : fore , 'back' : back , 'style' : style , 'reverse' : reverse , 'rgb_mode' : rgb_mode , }
if linemode :
gradargs [ 'movefactor' ] = 2 if movefactor is None else movefactor
method = self . _gradient_black_lines
else :
method = self . _gradient_black_line
if text :
ret... |
def color ( string , name , style = 'normal' , when = 'auto' ) :
"""Change the color of the given string .""" | if name not in colors :
from . text import oxford_comma
raise ValueError ( "unknown color '{}'.\nknown colors are: {}" . format ( name , oxford_comma ( [ "'{}'" . format ( x ) for x in sorted ( colors ) ] ) ) )
if style not in styles :
from . text import oxford_comma
raise ValueError ( "unknown style '{... |
def context ( self , size , placeholder = None , scope = None ) :
"""Returns this word in context , { size } words to the left , the current word , and { size } words to the right""" | return self . leftcontext ( size , placeholder , scope ) + [ self ] + self . rightcontext ( size , placeholder , scope ) |
def list ( self , to = values . unset , from_ = values . unset , date_sent_before = values . unset , date_sent = values . unset , date_sent_after = values . unset , limit = None , page_size = None ) :
"""Lists MessageInstance records from the API as a list .
Unlike stream ( ) , this operation is eager and will lo... | return list ( self . stream ( to = to , from_ = from_ , date_sent_before = date_sent_before , date_sent = date_sent , date_sent_after = date_sent_after , limit = limit , page_size = page_size , ) ) |
def _construct_instance ( cls , values ) :
"""method used to construct instances from query results
this is where polymorphic deserialization occurs""" | # we ' re going to take the values , which is from the DB as a dict
# and translate that into our local fields
# the db _ map is a db _ field - > model field map
items = values . items ( )
field_dict = dict ( [ ( cls . _db_map . get ( k , k ) , v ) for k , v in items ] )
if cls . _is_polymorphic :
poly_key = field_... |
def close ( self ) :
'''Close all connections
Return a : class : ` ~ asyncio . Future ` called once all connections
have closed''' | if not self . closed :
waiters = [ ]
queue = self . _queue
while queue . qsize ( ) :
connection = queue . get_nowait ( )
if connection :
closed = connection . close ( )
if closed :
waiters . append ( closed )
in_use = self . _in_use_connections
... |
def delete_instance ( self , instance_id ) :
'''method for removing an instance from AWS EC2
: param instance _ id : string of instance id on AWS
: return : string reporting state of instance''' | title = '%s.delete_instance' % self . __class__ . __name__
# validate inputs
input_fields = { 'instance_id' : instance_id }
for key , value in input_fields . items ( ) :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
self . fields . validate ( value , '.%s' % key , object_title )
# report query
se... |
def _get_fit_params ( self , x , fit_key ) :
"""Transforms the input parameter to fit parameters for the 7dq2 model .
That is , maps from
x = [ q , chiAx , chiAy , chiAz , chiBx , chiBy , chiBz ]
fit _ params = [ np . log ( q ) , chiAx , chiAy , chiHat , chiBx , chiBy , chi _ a ]
chiHat is defined in Eq . (... | q , chiAz , chiBz = x [ 0 ] , x [ 3 ] , x [ 6 ]
eta = q / ( 1. + q ) ** 2
chi_wtAvg = ( q * chiAz + chiBz ) / ( 1. + q )
chiHat = ( chi_wtAvg - 38. * eta / 113. * ( chiAz + chiBz ) ) / ( 1. - 76. * eta / 113. )
chi_a = ( chiAz - chiBz ) / 2.
fit_params = x
fit_params [ 0 ] = np . log ( q )
fit_params [ 3 ] = chiHat
fit... |
def add_group_members ( self , members ) :
"""Add a new group member to the groups list
: param members : member name
: type members : str
: return : None""" | if not isinstance ( members , list ) :
members = [ members ]
if not getattr ( self , 'group_members' , None ) :
self . group_members = members
else :
self . group_members . extend ( members ) |
def import_items ( import_directives , style , quiet_load = False ) :
"""Import the items in import _ directives and return a list of the imported items
Each item in import _ directives should be one of the following forms
* a tuple like ( ' module . submodule ' , ( ' classname1 ' , ' classname2 ' ) ) , which i... | imported_objects = { }
for directive in import_directives :
try : # First try a straight import
if isinstance ( directive , six . string_types ) :
imported_object = __import__ ( directive )
imported_objects [ directive . split ( '.' ) [ 0 ] ] = imported_object
if not quie... |
def extract_options_dict ( template , options ) :
"""Extract options from a dictionary against the template""" | for option , val in template . items ( ) :
if options and option in options :
yield option , options [ option ]
else :
yield option , Default ( template [ option ] [ 'default' ] ( os . environ ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.