signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def solve_venn3_circles ( venn_areas ) :
'''Given the list of " venn areas " ( as output from compute _ venn3 _ areas , i . e . [ A , B , C , AB , BC , AC , ABC ] ) ,
finds the positions and radii of the three circles .
The return value is a tuple ( coords , radii ) , where coords is a 3x2 array of coordinates ... | ( A_a , A_b , A_c , A_ab , A_bc , A_ac , A_abc ) = list ( map ( float , venn_areas ) )
r_a , r_b , r_c = np . sqrt ( A_a / np . pi ) , np . sqrt ( A_b / np . pi ) , np . sqrt ( A_c / np . pi )
intersection_areas = [ A_ab , A_bc , A_ac ]
radii = np . array ( [ r_a , r_b , r_c ] )
# Hypothetical distances between circle ... |
def FloatStringToFloat ( float_string , problems = None ) :
"""Convert a float as a string to a float or raise an exception""" | # Will raise TypeError unless a string
match = re . match ( r"^[+-]?\d+(\.\d+)?$" , float_string )
# Will raise TypeError if the string can ' t be parsed
parsed_value = float ( float_string )
if "x" in float_string : # This is needed because Python 2.4 does not complain about float ( " 0x20 " ) .
# But it does complain... |
def _add_edge ( self , layer , input_id , output_id ) :
"""Add a new layer to the graph . The nodes should be created in advance .""" | if layer in self . layer_to_id :
layer_id = self . layer_to_id [ layer ]
if input_id not in self . layer_id_to_input_node_ids [ layer_id ] :
self . layer_id_to_input_node_ids [ layer_id ] . append ( input_id )
if output_id not in self . layer_id_to_output_node_ids [ layer_id ] :
self . layer... |
def slices_to_layers ( G_coupling , slice_attr = 'slice' , vertex_id_attr = 'id' , edge_type_attr = 'type' , weight_attr = 'weight' ) :
"""Convert a coupling graph of slices to layers of graphs .
This function converts a graph of slices to layers so that they can be used
with this package . This function assume... | if not slice_attr in G_coupling . vertex_attributes ( ) :
raise ValueError ( "Could not find the vertex attribute {0} in the coupling graph." . format ( slice_attr ) )
if not weight_attr in G_coupling . edge_attributes ( ) :
raise ValueError ( "Could not find the edge attribute {0} in the coupling graph." . for... |
def depsignal ( class_ , signal_name , * , defer = False ) :
"""Connect the decorated method or coroutine method to the addressed signal on
a class on which the service depends .
: param class _ : A service class which is listed in the
: attr : ` ~ . Meta . ORDER _ AFTER ` relationship .
: type class _ : : ... | def decorator ( f ) :
add_handler_spec ( f , _depsignal_spec ( class_ , signal_name , f , defer ) )
return f
return decorator |
def setPixelColorRGB ( self , n , red , green , blue ) :
"""Set LED at position n to the provided red , green , and blue color .
Each color component should be a value from 0 to 255 ( where 0 is the
lowest intensity and 255 is the highest intensity ) .""" | self . setPixelColor ( n , Color ( red , green , blue ) ) |
def load_code ( self , path , package , callwith ) :
'''Used internally when loading code . You should probably use
load _ objects ( ) .''' | sys . path = [ path ] + sys . path
g_o = importlib . import_module ( package ) . get_objects
del sys . path [ 0 ]
for obj in g_o ( callwith ) :
self . code [ obj . title . lower ( ) ] = obj |
def clean_title ( title ) :
"""Clean title - > remove dates , remove duplicated spaces and strip title .
Args :
title ( str ) : Title .
Returns :
str : Clean title without dates , duplicated , trailing and leading spaces .""" | date_pattern = re . compile ( r'\W*' r'\d{1,2}' r'[/\-.]' r'\d{1,2}' r'[/\-.]' r'(?=\d*)(?:.{4}|.{2})' r'\W*' )
title = date_pattern . sub ( ' ' , title )
title = re . sub ( r'\s{2,}' , ' ' , title )
title = title . strip ( )
return title |
def _cryptography_cipher ( key , iv ) :
"""Build a cryptography AES Cipher object .
: param bytes key : Encryption key
: param bytes iv : Initialization vector
: returns : AES Cipher instance
: rtype : cryptography . hazmat . primitives . ciphers . Cipher""" | return Cipher ( algorithm = algorithms . AES ( key ) , mode = modes . CFB ( iv ) , backend = default_backend ( ) ) |
def colorbrewer ( values , alpha = 255 ) :
"""Return a dict of colors for the unique values .
Colors are adapted from Harrower , Mark , and Cynthia A . Brewer .
" ColorBrewer . org : an online tool for selecting colour schemes for maps . "
The Cartographic Journal 40.1 ( 2003 ) : 27-37.
: param values : val... | basecolors = [ [ 31 , 120 , 180 ] , [ 178 , 223 , 138 ] , [ 51 , 160 , 44 ] , [ 251 , 154 , 153 ] , [ 227 , 26 , 28 ] , [ 253 , 191 , 111 ] , [ 255 , 127 , 0 ] , [ 202 , 178 , 214 ] , [ 106 , 61 , 154 ] , [ 255 , 255 , 153 ] , [ 177 , 89 , 40 ] ]
unique_values = list ( set ( values ) )
return { k : basecolors [ i % len... |
def request_name ( self , name ) :
"""Request a name , might return the name or a similar one if already
used or reserved""" | while name in self . _blacklist :
name += "_"
self . _blacklist . add ( name )
return name |
def writeJsonZipfile ( filelike , data , compress = True , mode = 'w' , name = 'data' ) :
"""Serializes the objects contained in data to a JSON formated string and
writes it to a zipfile .
: param filelike : path to a file ( str ) or a file - like object
: param data : object that should be converted to a JSO... | zipcomp = zipfile . ZIP_DEFLATED if compress else zipfile . ZIP_STORED
with zipfile . ZipFile ( filelike , mode , allowZip64 = True ) as containerFile :
containerFile . writestr ( name , json . dumps ( data , cls = MaspyJsonEncoder ) , zipcomp ) |
def concat_ws ( sep , * cols ) :
"""Concatenates multiple input string columns together into a single string column ,
using the given separator .
> > > df = spark . createDataFrame ( [ ( ' abcd ' , ' 123 ' ) ] , [ ' s ' , ' d ' ] )
> > > df . select ( concat _ ws ( ' - ' , df . s , df . d ) . alias ( ' s ' ) ... | sc = SparkContext . _active_spark_context
return Column ( sc . _jvm . functions . concat_ws ( sep , _to_seq ( sc , cols , _to_java_column ) ) ) |
def find_for_x_in_y_keys ( node ) :
"""Finds looping against dictionary keys""" | return ( isinstance ( node , ast . For ) and h . call_name_is ( node . iter , 'keys' ) ) |
def visit_Dict ( self , node : ast . Dict ) -> Dict [ Any , Any ] :
"""Visit keys and values and assemble a dictionary with the results .""" | recomputed_dict = dict ( )
# type : Dict [ Any , Any ]
for key , val in zip ( node . keys , node . values ) :
recomputed_dict [ self . visit ( node = key ) ] = self . visit ( node = val )
self . recomputed_values [ node ] = recomputed_dict
return recomputed_dict |
def environment_does_base_variable_exist ( self , name ) :
"""Checks if the given environment variable exists in the session ' s base
environment ( : py : func : ` IGuestSession . environment _ base ` ) .
in name of type str
Name of the environment variable to look for . This cannot be
empty nor can it cont... | if not isinstance ( name , basestring ) :
raise TypeError ( "name can only be an instance of type basestring" )
exists = self . _call ( "environmentDoesBaseVariableExist" , in_p = [ name ] )
return exists |
def agent ( self ) :
"""This method returns the agent name .
: return :""" | try :
if self . _data_from_search :
agent = self . _data_from_search . find ( 'ul' , { 'class' : 'links' } ) . text
return agent . split ( ':' ) [ 1 ] . strip ( )
else :
return self . _ad_page_content . find ( 'a' , { 'id' : 'smi-link-branded' } ) . text . strip ( )
except Exception as e... |
def connection ( self ) :
"""A context manager that returns a connection
to the server using some * session * .""" | conn = self . session ( ** self . options )
try :
for item in self . middlewares :
item ( conn )
yield conn
finally :
conn . teardown ( ) |
def smoothed_moving_average ( data , period ) :
"""Smoothed Moving Average .
Formula :
smma = avg ( data ( n ) ) - avg ( data ( n ) / n ) + data ( t ) / n""" | catch_errors . check_for_period_error ( data , period )
series = pd . Series ( data )
return series . ewm ( alpha = 1.0 / period ) . mean ( ) . values . flatten ( ) |
def find ( self , cell_designation , cell_filter = lambda x , c : 'c' in x and x [ 'c' ] == c ) :
"""finds spike containers in multi spike containers collection offspring""" | if 'parent' in self . meta :
return ( self . meta [ 'parent' ] , self . meta [ 'parent' ] . find ( cell_designation , cell_filter = cell_filter ) ) |
def hex_colors ( self ) :
"""Colors as a tuple of hex strings . ( e . g . ' # A912F4 ' )""" | hc = [ ]
for color in self . colors :
h = '#' + '' . join ( '{0:>02}' . format ( hex ( c ) [ 2 : ] . upper ( ) ) for c in color )
hc . append ( h )
return hc |
def squelch ( self , threshold ) :
"""Set all records that do not exceed the given threhsold to 0.
Parameters
threshold : scalar
Level below which to set records to zero""" | func = lambda x : zeros ( x . shape ) if max ( x ) < threshold else x
return self . map ( func ) |
def SetLowerTimestamp ( cls , timestamp ) :
"""Sets the lower bound timestamp .""" | if not hasattr ( cls , '_lower' ) :
cls . _lower = timestamp
return
if timestamp < cls . _lower :
cls . _lower = timestamp |
def generate_data_for_env_problem ( problem_name ) :
"""Generate data for ` EnvProblem ` s .""" | assert FLAGS . env_problem_max_env_steps > 0 , ( "--env_problem_max_env_steps " "should be greater than zero" )
assert FLAGS . env_problem_batch_size > 0 , ( "--env_problem_batch_size should be" " greather than zero" )
problem = registry . env_problem ( problem_name )
task_id = None if FLAGS . task_id < 0 else FLAGS . ... |
def _ls_print_summary ( all_trainings : List [ Tuple [ str , dict , TrainingTrace ] ] ) -> None :
"""Print trainings summary .
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
: param all _ trainings : a list of tra... | counts_by_name = defaultdict ( int )
counts_by_classes = defaultdict ( int )
for _ , config , _ in all_trainings :
counts_by_name [ get_model_name ( config ) ] += 1
counts_by_classes [ get_classes ( config ) ] += 1
print_boxed ( 'summary' )
print ( )
counts_table = [ [ name , count ] for name , count in counts_... |
def convert_objects ( self , convert_dates = True , convert_numeric = False , convert_timedeltas = True , copy = True ) :
"""Attempt to infer better dtype for object columns .
. . deprecated : : 0.21.0
Parameters
convert _ dates : boolean , default True
If True , convert to date where possible . If ' coerce... | msg = ( "convert_objects is deprecated. To re-infer data dtypes for " "object columns, use {klass}.infer_objects()\nFor all " "other conversions use the data-type specific converters " "pd.to_datetime, pd.to_timedelta and pd.to_numeric." ) . format ( klass = self . __class__ . __name__ )
warnings . warn ( msg , Future... |
def role_list ( endpoint_id ) :
"""Executor for ` globus access endpoint - role - list `""" | client = get_client ( )
roles = client . endpoint_role_list ( endpoint_id )
resolved_ids = LazyIdentityMap ( x [ "principal" ] for x in roles if x [ "principal_type" ] == "identity" )
def principal_str ( role ) :
principal = role [ "principal" ]
if role [ "principal_type" ] == "identity" :
username = re... |
def get_latex_name ( func_in , ** kwargs ) :
"""Produce a latex formatted name for each function for use in labelling
results .
Parameters
func _ in : function
kwargs : dict , optional
Kwargs for function .
Returns
latex _ name : str
Latex formatted name for the function .""" | if isinstance ( func_in , functools . partial ) :
func = func_in . func
assert not set ( func_in . keywords ) & set ( kwargs ) , ( 'kwargs={0} and func_in.keywords={1} contain repeated keys' . format ( kwargs , func_in . keywords ) )
kwargs . update ( func_in . keywords )
else :
func = func_in
param_ind... |
def _bind_indirect_user ( self , ldap , con ) :
"""If using AUTH _ LDAP _ BIND _ USER bind this user before performing search
: param ldap : The ldap module reference
: param con : The ldap connection""" | indirect_user = self . auth_ldap_bind_user
if indirect_user :
indirect_password = self . auth_ldap_bind_password
log . debug ( "LDAP indirect bind with: {0}" . format ( indirect_user ) )
con . bind_s ( indirect_user , indirect_password )
log . debug ( "LDAP BIND indirect OK" ) |
def is_valid ( self ) :
"""Check integrity and validity of this frame .
: return : bool True if this frame is structurally valid .""" | conditions = [ self . protocol_id == 0 , # Modbus always uses protocol 0
2 <= self . length <= 260 , # Absolute length limits
len ( self . data ) == self . length - 2 , # Total length matches data length
]
return all ( conditions ) |
def from_dict ( cls , d ) :
"""Instantiate a Variable from a dictionary representation .""" | return cls ( d [ 'type' ] , tuple ( d [ 'parents' ] ) , list ( d [ 'properties' ] . items ( ) ) ) |
def request_uplink_info ( self , payload ) :
"""Get the uplink from the database and send the info to the agent .""" | # This request is received from an agent when it run for the first
# Send the uplink name ( physical port name that connectes compute
# node and switch fabric ) ,
agent = payload . get ( 'agent' )
config_res = self . get_agent_configurations ( agent )
LOG . debug ( 'configurations on %(agent)s is %(cfg)s' , ( { 'agent'... |
def string_tokenizer ( self , untokenized_string : str , include_blanks = False ) :
"""This function is based off CLTK ' s line tokenizer . Use this for strings
rather than . txt files .
input : ' 20 . u2 - sza - bi - la - kum \n 1 . a - na ia - as2 - ma - ah - { d } iszkur # \n 2.
qi2 - bi2 - ma \n 3 . um - ... | line_output = [ ]
assert isinstance ( untokenized_string , str ) , 'Incoming argument must be a string.'
if include_blanks :
tokenized_lines = untokenized_string . splitlines ( )
else :
tokenized_lines = [ line for line in untokenized_string . splitlines ( ) if line != r'\\n' ]
for line in tokenized_lines : # S... |
def _resolve_call ( self , table , column = '' , value = '' , ** kwargs ) :
"""Internal method to resolve the API wrapper call .""" | if not column :
return self . catalog ( table )
elif not value :
return self . catalog ( table , column )
# We have all the table , column , and value , and now need to
# ensure they ' re all strings and uppercase .
column = column . upper ( )
value = str ( value ) . upper ( )
data = self . call_api ( table , c... |
def main ( ) :
"""NAME
lnp _ magic . py
DESCRIPTION
makes equal area projections site by site
from specimen formatted file with
Fisher confidence ellipse using McFadden and McElhinny ( 1988)
technique for combining lines and planes
SYNTAX
lnp _ magic [ command line options ]
INPUT
takes magic fo... | if '-h' in sys . argv :
print ( main . __doc__ )
sys . exit ( )
dir_path = pmag . get_named_arg ( "-WD" , "." )
data_model = int ( float ( pmag . get_named_arg ( "-DM" , 3 ) ) )
fmt = pmag . get_named_arg ( "-fmt" , 'svg' )
if data_model == 2 :
in_file = pmag . get_named_arg ( '-f' , 'pmag_specimens.txt' )
... |
def _log ( self , level , fmt , args = None , extra = None , exc_info = None , inc_stackinfo = False , inc_multiproc = False ) :
"""Send a log message to all of the logging functions
for a given level as well as adding the
message to this logger instance ' s history .""" | if not self . enabled :
return
# Fail silently so that logging can easily be removed
log_record = self . _make_record ( level , fmt , args , extra , exc_info , inc_stackinfo , inc_multiproc )
logstr = log_record [ 'defaultfmt' ] . format ( ** log_record )
# whoah .
if self . keep_history :
self . history . appe... |
def packet2chain ( packet ) :
"""Fetch Scapy packet protocol chain .""" | if scapy_all is None :
raise ModuleNotFound ( "No module named 'scapy'" , name = 'scapy' )
chain = [ packet . name ]
payload = packet . payload
while not isinstance ( payload , scapy_all . packet . NoPayload ) :
chain . append ( payload . name )
payload = payload . payload
return ':' . join ( chain ) |
def Line ( pointa = ( - 0.5 , 0. , 0. ) , pointb = ( 0.5 , 0. , 0. ) , resolution = 1 ) :
"""Create a line
Parameters
pointa : np . ndarray or list
Location in [ x , y , z ] .
pointb : np . ndarray or list
Location in [ x , y , z ] .
resolution : int
number of pieces to divide line into""" | if np . array ( pointa ) . size != 3 :
raise TypeError ( 'Point A must be a length three tuple of floats.' )
if np . array ( pointb ) . size != 3 :
raise TypeError ( 'Point B must be a length three tuple of floats.' )
src = vtk . vtkLineSource ( )
src . SetPoint1 ( * pointa )
src . SetPoint2 ( * pointb )
src . ... |
async def pop_transaction_async ( self ) :
"""Decrement async transaction depth .""" | depth = self . transaction_depth_async ( )
if depth > 0 :
depth -= 1
self . _task_data . set ( 'depth' , depth )
if depth == 0 :
conn = self . _task_data . get ( 'conn' )
self . _async_conn . release ( conn )
else :
raise ValueError ( "Invalid async transaction depth value" ) |
def hex2pub ( pub_hex : str ) -> PublicKey :
"""Convert ethereum hex to EllipticCurvePublicKey
The hex should be 65 bytes , but ethereum public key only has 64 bytes
So have to add \x04
Parameters
pub _ hex : str
Ethereum public key hex string
Returns
coincurve . PublicKey
A secp256k1 public key cal... | uncompressed = decode_hex ( pub_hex )
if len ( uncompressed ) == 64 :
uncompressed = b"\x04" + uncompressed
return PublicKey ( uncompressed ) |
def read_raw ( self , length , * , error = None ) :
"""Read raw packet data .""" | if length is None :
length = len ( self )
raw = dict ( packet = self . _read_fileng ( length ) , error = error or None , )
return raw |
def export ( self , new_format , filename = None , chan = None , begtime = None , endtime = None ) :
"""Export current dataset to wonambi format ( . won ) .
Parameters
new _ format : str
Format for exported record : ' edf ' or ' wonambi '
filename : str or PosixPath
filename to export to
chan : list of ... | dataset = self . dataset
subj_id = dataset . header [ 'subj_id' ]
if filename is None :
filename = dataset . filename
data = dataset . read_data ( chan = chan , begtime = begtime , endtime = endtime )
if 'wonambi' == new_format :
write_wonambi ( data , filename , subj_id = subj_id )
elif 'edf' == new_format :
... |
def fromInputs ( self , inputs ) :
"""Extract the inputs associated with the child forms of this parameter
from the given dictionary and coerce them using C { self . coercer } .
@ type inputs : C { dict } mapping C { unicode } to C { list } of C { unicode }
@ param inputs : The contents of a form post , in th... | try :
values = inputs [ self . name ]
except KeyError :
raise ConfigurationError ( "Missing value for input: " + self . name )
return self . coerceMany ( values ) |
def save_file ( self , path : str , file_id : int = None , file_part : int = 0 , progress : callable = None , progress_args : tuple = ( ) ) :
"""Use this method to upload a file onto Telegram servers , without actually sending the message to anyone .
This is a utility method intended to be used * * only * * when ... | part_size = 512 * 1024
file_size = os . path . getsize ( path )
if file_size == 0 :
raise ValueError ( "File size equals to 0 B" )
if file_size > 1500 * 1024 * 1024 :
raise ValueError ( "Telegram doesn't support uploading files bigger than 1500 MiB" )
file_total_parts = int ( math . ceil ( file_size / part_size... |
def unlock ( self ) :
"""Closes the session to the database .""" | if not hasattr ( self , 'session' ) :
raise RuntimeError ( 'Error detected! The session that you want to close does not exist any more!' )
logger . debug ( "Closed database session of '%s'" % self . _database )
self . session . close ( )
del self . session |
def echo_info ( conn ) :
"""Print detected information .""" | click . echo ( "General information:" )
click . echo ( " Hostname: {}" . format ( conn . hostname ) )
click . echo ( " HW Family: {}" . format ( conn . family ) )
click . echo ( " HW Platform: {}" . format ( conn . platform ) )
click . echo ( " SW Type: {}" . format ( conn . os_type ) )
click . echo ( " SW Version: {}"... |
def get_metrics ( self , timestamp ) :
"""Get a Metric for each registered view .
Convert each registered view ' s associated ` ViewData ` into a ` Metric ` to
be exported .
: type timestamp : : class : ` datetime . datetime `
: param timestamp : The timestamp to use for metric conversions , usually
the c... | for vdl in self . _measure_to_view_data_list_map . values ( ) :
for vd in vdl :
metric = metric_utils . view_data_to_metric ( vd , timestamp )
if metric is not None :
yield metric |
def prt_goids ( self , prt ) :
"""Print all GO IDs in the plot , plus their color .""" | fmt = self . gosubdag . prt_attr [ 'fmta' ]
nts = sorted ( self . gosubdag . go2nt . values ( ) , key = lambda nt : [ nt . NS , nt . depth , nt . alt ] )
_get_color = self . pydotnodego . go2color . get
for ntgo in nts :
gostr = fmt . format ( ** ntgo . _asdict ( ) )
col = _get_color ( ntgo . GO , "" )
prt ... |
def gzip_files ( self ) :
"""Return a list of the files compressed by this link .
This returns all files that were explicitly marked for compression .""" | ret_list = [ ]
for key , val in self . file_dict . items ( ) : # For temp files we only want files that were marked for removal
if val & FileFlags . gz_mask :
ret_list . append ( key )
return ret_list |
def df ( self , version = None , tags = None , ext = None , ** kwargs ) :
"""Loads an instance of this dataset into a dataframe .
Parameters
version : str , optional
The version of the instance of this dataset .
tags : list of str , optional
The tags associated with the desired instance of this dataset . ... | ext = self . _find_extension ( version = version , tags = tags )
if ext is None :
attribs = "{}{}" . format ( "version={} and " . format ( version ) if version else "" , "tags={}" . format ( tags ) if tags else "" , )
raise MissingDatasetError ( "No dataset with {} in local store!" . format ( attribs ) )
fpath ... |
def on_message ( self , ws , message ) :
"""Websocket on _ message event handler
Saves message as RTMMessage in self . _ inbox""" | try :
data = json . loads ( message )
except Exception :
self . _set_error ( message , "decode message failed" )
else :
self . _inbox . put ( RTMMessage ( data ) ) |
def close ( self ) :
"""Connection ( s ) cleanup .""" | # TODO : DRY with workerLaunch . py
# Ensure everything is cleaned up on exit
scoop . logger . debug ( 'Closing broker on host {0}.' . format ( self . hostname ) )
# Terminate subprocesses
try :
self . shell . terminate ( )
except OSError :
pass
# Output child processes stdout and stderr to console
sys . stdout... |
def partition_app_list ( app_list , n ) :
""": param app _ list : A list of apps with models .
: param n : Number of buckets to divide into .
: return : Partition apps into n partitions , where the number of models in each list is roughly equal . We also factor
in the app heading .""" | num_rows = sum ( [ 1 + len ( x [ 'models' ] ) for x in app_list ] )
# + 1 for app title
num_rows_per_partition = num_rows / n
result = [ [ ] for i in range ( n ) ]
# start with n empty lists of lists
partition = 0
count = 0
for a in app_list : # will the app fit in this column or overflow ?
c = len ( a [ 'models' ]... |
def _find_snapshot ( self , name ) :
"""Find snapshot on remote by name or regular expression""" | remote_snapshots = self . _get_snapshots ( self . client )
for remote in reversed ( remote_snapshots ) :
if remote [ "Name" ] == name or re . match ( name , remote [ "Name" ] ) :
return remote
return None |
def urljoin ( base_url , url , allow_fragments = True ) :
'''Join URLs like ` ` urllib . parse . urljoin ` ` but allow scheme - relative URL .''' | if url . startswith ( '//' ) and len ( url ) > 2 :
scheme = base_url . partition ( ':' ) [ 0 ]
if scheme :
return urllib . parse . urljoin ( base_url , '{0}:{1}' . format ( scheme , url ) , allow_fragments = allow_fragments )
return urllib . parse . urljoin ( base_url , url , allow_fragments = allow_fra... |
def close_stream ( self ) :
"""Closes the stream . Performs cleanup .""" | self . keep_listening = False
self . stream . stop_stream ( )
self . stream . close ( )
self . pa . terminate ( ) |
def _bfgs_direction ( s , y , x , hessinv_estimate = None ) :
r"""Compute ` ` Hn ^ - 1 ( x ) ` ` for the L - BFGS method .
Parameters
s : sequence of ` LinearSpaceElement `
The ` ` s ` ` coefficients in the BFGS update , see Notes .
y : sequence of ` LinearSpaceElement `
The ` ` y ` ` coefficients in the ... | assert len ( s ) == len ( y )
r = x . copy ( )
alphas = np . zeros ( len ( s ) )
rhos = np . zeros ( len ( s ) )
for i in reversed ( range ( len ( s ) ) ) :
rhos [ i ] = 1.0 / y [ i ] . inner ( s [ i ] )
alphas [ i ] = rhos [ i ] * ( s [ i ] . inner ( r ) )
r . lincomb ( 1 , r , - alphas [ i ] , y [ i ] )
i... |
def normalize ( self ) :
"""Return a new time series with all values normalized to 0 to 1.
: return : ` None `""" | maximum = self . max ( )
if maximum :
self . values = [ value / maximum for value in self . values ] |
def send_transaction ( self , to : Address , startgas : int , value : int = 0 , data : bytes = b'' , ) -> bytes :
"""Helper to send signed messages .
This method will use the ` privkey ` provided in the constructor to
locally sign the transaction . This requires an extended server
implementation that accepts ... | if to == to_canonical_address ( constants . NULL_ADDRESS ) :
warnings . warn ( 'For contract creation the empty string must be used.' )
with self . _nonce_lock :
nonce = self . _available_nonce
gas_price = self . gas_price ( )
transaction = { 'data' : data , 'gas' : startgas , 'nonce' : nonce , 'value' ... |
def _cfgs_to_read ( self ) :
"""reads config files from various locations to build final config .""" | # use these files to extend / overwrite the conf _ values .
# Last red file always overwrites existing values !
cfg = Config . DEFAULT_CONFIG_FILE_NAME
filenames = [ self . default_config_file , cfg , # conf _ values in current directory
os . path . join ( os . path . expanduser ( '~' + os . path . sep ) , cfg ) , # co... |
def _set_i2c_speed ( self , i2c_speed ) :
"""Set I2C speed to one of ' 400kHz ' , ' 100kHz ' , 50kHz ' , ' 5kHz '""" | lower_bits_mapping = { '400kHz' : 3 , '100kHz' : 2 , '50kHz' : 1 , '5kHz' : 0 , }
if i2c_speed not in lower_bits_mapping :
raise ValueError ( 'Invalid i2c_speed' )
speed_byte = 0b01100000 | lower_bits_mapping [ i2c_speed ]
self . device . write ( bytearray ( [ speed_byte ] ) )
response = self . device . read ( 1 )
... |
def db ( context , data ) :
"""Insert or update ` data ` as a row into specified db table""" | table = context . params . get ( "table" , context . crawler . name )
params = context . params
params [ "table" ] = table
_recursive_upsert ( context , params , data ) |
def apply_migrations ( engine , connection , path ) :
"""Apply all migrations in a chronological order""" | # Get migrations applied
migrations_applied = get_migrations_applied ( engine , connection )
# print ( migrationsApplied )
# Get migrations folder
for file in get_migrations_files ( path ) : # Set vars
basename = os . path . basename ( os . path . dirname ( file ) )
# Skip migrations if they are already applied... |
def dark ( cls ) :
"Make the current foreground color dark ." | wAttributes = cls . _get_text_attributes ( )
wAttributes &= ~ win32 . FOREGROUND_INTENSITY
cls . _set_text_attributes ( wAttributes ) |
def check_sig ( package ) :
"""check if rpm has a signature , we don ' t care if it ' s valid or not
at the moment
Shamelessly stolen from Seth Vidal
http : / / yum . baseurl . org / download / misc / checksig . py""" | rpmroot = '/'
ts = rpm . TransactionSet ( rpmroot )
sigerror = 0
ts . setVSFlags ( 0 )
hdr = return_hdr ( ts , package )
sigerror , ( sigtype , sigdate , sigid ) = get_sig_info ( hdr )
if sigid == 'None' :
keyid = 'None'
else :
keyid = sigid [ - 8 : ]
if keyid != 'None' :
return True
else :
return False |
def remove_send_last_message ( self , connection ) :
"""Removes a send _ last _ message function previously registered
with the Dispatcher .
Args :
connection ( str ) : A locally unique identifier provided
by the receiver of messages .""" | if connection in self . _send_last_message :
del self . _send_last_message [ connection ]
LOGGER . debug ( "Removed send_last_message function " "for connection %s" , connection )
else :
LOGGER . warning ( "Attempted to remove send_last_message " "function for connection %s, but no " "send_last_message func... |
def load_layer_from_registry ( layer_path ) :
"""Helper method to load a layer from registry if its already there .
If the layer is not loaded yet , it will create the QgsMapLayer on the fly .
: param layer _ path : Layer source path .
: type layer _ path : str
: return : Vector layer
: rtype : QgsVectorL... | # reload the layer in case the layer path has no provider information
the_layer = load_layer ( layer_path ) [ 0 ]
layers = QgsProject . instance ( ) . mapLayers ( )
for _ , layer in list ( layers . items ( ) ) :
if full_layer_uri ( layer ) == full_layer_uri ( the_layer ) :
monkey_patch_keywords ( layer )
... |
def schedule_host_check ( self , host , check_time ) :
"""Schedule a check on a host
Format of the line that triggers function call : :
SCHEDULE _ HOST _ CHECK ; < host _ name > ; < check _ time >
: param host : host to check
: type host : alignak . object . host . Host
: param check _ time : time to chec... | host . schedule ( self . daemon . hosts , self . daemon . services , self . daemon . timeperiods , self . daemon . macromodulations , self . daemon . checkmodulations , self . daemon . checks , force = False , force_time = check_time )
self . send_an_element ( host . get_update_status_brok ( ) ) |
def get_opt_tags ( self , section , option , tags ) :
"""Supplement to ConfigParser . ConfigParser . get ( ) . This will search for an
option in [ section ] and if it doesn ' t find it will also try in
[ section - tag ] for every value of tag in tags .
Will raise a ConfigParser . Error if it cannot find a val... | # Need lower case tag name ; also exclude cases with tag = None
if tags :
tags = [ tag . lower ( ) for tag in tags if tag is not None ]
try :
return self . get ( section , option )
except ConfigParser . Error :
err_string = "No option '%s' in section [%s] " % ( option , section )
if not tags :
r... |
def populate_times ( self ) :
"""Populates all different meta data times that comes with measurement if
they are present .""" | stop_time = self . meta_data . get ( "stop_time" )
if stop_time :
stop_naive = datetime . utcfromtimestamp ( stop_time )
self . stop_time = stop_naive . replace ( tzinfo = tzutc ( ) )
creation_time = self . meta_data . get ( "creation_time" )
if creation_time :
creation_naive = datetime . utcfromtimestamp (... |
def add_edge ( self , start , end , ** kwargs ) :
"""Add an edge between two nodes .
The nodes will be automatically added if they are not present in the network .
Parameters
start : tuple
Both the start and end nodes should specify the time slice as
( node _ name , time _ slice ) . Here , node _ name can... | try :
if len ( start ) != 2 or len ( end ) != 2 :
raise ValueError ( 'Nodes must be of type (node, time_slice).' )
elif not isinstance ( start [ 1 ] , int ) or not isinstance ( end [ 1 ] , int ) :
raise ValueError ( 'Nodes must be of type (node, time_slice).' )
elif start [ 1 ] == end [ 1 ] ... |
def clean ( self ) :
"""Always raise the default error message , because we don ' t
care what they entered here .""" | raise forms . ValidationError ( self . error_messages [ 'invalid_login' ] , code = 'invalid_login' , params = { 'username' : self . username_field . verbose_name } ) |
def as_dict ( self ) :
"""Pre - serialisation of the meta data""" | drepr = { }
drepr [ "name" ] = self . name
drepr [ "time" ] = self . time
# error pre - serialisation
drepr [ "errors" ] = [ str ( err ) for err in self . errors ]
# warning pre - serialisation
drepr [ "warnings" ] = [ str ( warn ) for warn in self . warnings ]
return drepr |
def update ( * args , ** kwargs ) :
'''Update installed plugin package ( s ) .
Each plugin package must have a directory ( * * NOT * * a link ) containing a
` ` properties . yml ` ` file with a ` ` package _ name ` ` value in the following
directory :
< conda prefix > / share / microdrop / plugins / availab... | package_name = kwargs . pop ( 'package_name' , None )
# Only consider * * installed * * plugins ( see ` installed _ plugins ( ) ` docstring ) .
installed_plugins_ = installed_plugins ( only_conda = True )
if installed_plugins_ :
plugin_packages = [ plugin_i [ 'package_name' ] for plugin_i in installed_plugins_ ]
... |
def _get_id_from_username ( self , username ) :
"""Looks up a username ' s id
: param string username : Username to lookup
: returns : The id that matches username .""" | _mask = "mask[id, username]"
_filter = { 'users' : { 'username' : utils . query_filter ( username ) } }
user = self . list_users ( _mask , _filter )
if len ( user ) == 1 :
return [ user [ 0 ] [ 'id' ] ]
elif len ( user ) > 1 :
raise exceptions . SoftLayerError ( "Multiple users found with the name: %s" % userna... |
def list_to_csv_response ( data , title = 'report' , header = None , widths = None ) :
"""Make 2D list into a csv response for download data .""" | response = HttpResponse ( content_type = "text/csv; charset=UTF-8" )
cw = csv . writer ( response )
for row in chain ( [ header ] if header else [ ] , data ) :
cw . writerow ( [ force_text ( s ) . encode ( response . charset ) for s in row ] )
return response |
def __sort_up ( self ) :
"""Sort the updatable objects according to ascending order""" | if self . __do_need_sort_up :
self . __up_objects . sort ( key = cmp_to_key ( self . __up_cmp ) )
self . __do_need_sort_up = False |
def create ( cls , api , default_name = None , description = None ) :
"""http : / / docs . fiesta . cc / list - management - api . html # creating - a - group
200 character max on the description .""" | path = 'group'
data = { }
if default_name :
data [ 'default_group_name' ] = default_name
if description :
data [ 'description' ] = description
if api . domain :
data [ 'domain' ] = api . domain
response_data = api . request ( path , data = data )
id = response_data [ 'group_id' ]
group = cls ( api , id )
gr... |
def list_combiner ( value , mutator , * args , ** kwargs ) :
"""Expects the output of the source to be a list to which
the result of each mutator is appended .""" | value . append ( mutator ( * args , ** kwargs ) )
return value |
def _validate ( item ) :
"""Validate ( instance , prop name ) tuple""" | if not isinstance ( item , tuple ) or len ( item ) != 2 :
raise ValueError ( 'Linked items must be instance/prop-name tuple' )
if not isinstance ( item [ 0 ] , tuple ( LINK_OBSERVERS ) ) :
raise ValueError ( 'Only {} instances may be linked' . format ( ', ' . join ( [ link_cls . __name__ for link_cls in LINK_OB... |
def _filter_queryset ( self , perms , queryset ) :
"""Filter object objects by permissions of user in request .""" | user = self . request . user if self . request else AnonymousUser ( )
return get_objects_for_user ( user , perms , queryset ) |
def text_ratio ( self ) :
"""Return a measure of the sequences ' word similarity ( float in [ 0,1 ] ) .
Each word has weight equal to its length for this measure
> > > m = WordMatcher ( a = [ ' abcdef ' , ' 12 ' ] , b = [ ' abcdef ' , ' 34 ' ] ) # 3/4 of the text is the same
> > > ' % . 3f ' % m . ratio ( ) #... | return _calculate_ratio ( self . match_length ( ) , self . _text_length ( self . a ) + self . _text_length ( self . b ) , ) |
def fn2lun ( fname ) :
"""Internal undocumented command for mapping name of open file to
its FORTRAN ( F2C ) logical unit .
https : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / FORTRAN / spicelib / fn2lun . html
: param fname : name of the file to be mapped to its logical unit .
: type fname ... | fnameP = stypes . stringToCharP ( fname )
unit_out = ctypes . c_int ( )
fname_len = ctypes . c_int ( len ( fname ) + 1 )
libspice . fn2lun_ ( fnameP , ctypes . byref ( unit_out ) , fname_len )
return unit_out . value |
def _post ( self , data , file_to_upload = None ) :
"""Make the POST request .""" | # pylint : disable = E1101
params = { "JSONRPC" : simplejson . dumps ( data ) }
req = None
if file_to_upload :
req = http_core . HttpRequest ( self . write_url )
req . method = 'POST'
req . add_body_part ( "JSONRPC" , simplejson . dumps ( data ) , 'text/plain' )
upload = file ( file_to_upload , "rb" )
... |
def nearest_neighbors ( coordinates_a , coordinates_b , periodic , r = None , n = None ) :
'''Nearest neighbor search between two arrays of coordinates . Notice that
you can control the result by selecting neighbors either by radius * r * or
by number * n * . The algorithm uses a periodic variant of KDTree to r... | if r is None and n is None :
raise ValueError ( 'You should pass either the parameter n or r' )
coordinates_a = _check_coordinates ( coordinates_a )
coordinates_b = _check_coordinates ( coordinates_b )
periodic = _check_periodic ( periodic )
kdtree = PeriodicCKDTree ( periodic , coordinates_b )
if r is not None :
... |
def is_task_running ( self , task , connection_failure_control = None ) :
"""Check if a task is running according to : TASK _ PENDING _ STATES [ ' New ' , ' Starting ' ,
' Pending ' , ' Running ' , ' Suspended ' , ' Stopping ' ]
Args :
task ( dict ) : OneView Task resource .
connection _ failure _ control (... | if 'uri' in task :
try :
task = self . get ( task )
if connection_failure_control : # Updates last success
connection_failure_control [ 'last_success' ] = self . get_current_seconds ( )
if 'taskState' in task and task [ 'taskState' ] in TASK_PENDING_STATES :
return Tr... |
async def issuer_revoke_credential ( wallet_handle : int , blob_storage_reader_handle : int , rev_reg_id : str , cred_revoc_id : str ) -> str :
"""Revoke a credential identified by a cred _ revoc _ id ( returned by issuer _ create _ credential ) .
The corresponding credential definition and revocation registry mu... | logger = logging . getLogger ( __name__ )
logger . debug ( "issuer_revoke_credential: >>> wallet_handle: %r, blob_storage_reader_handle: %r, rev_reg_id: %r, " "cred_revoc_id: %r" , wallet_handle , blob_storage_reader_handle , rev_reg_id , cred_revoc_id )
if not hasattr ( issuer_revoke_credential , "cb" ) :
logger .... |
def send ( self , command , payload ) :
"""Send a WorkRequest to containing command and payload to the queue specified in config .
: param command : str : name of the command we want run by WorkQueueProcessor
: param payload : object : pickable data to be used when running the command""" | request = WorkRequest ( command , payload )
logging . info ( "Sending {} message to queue {}." . format ( request . command , self . queue_name ) )
# setting protocol to version 2 to be compatible with python2
self . connection . send_durable_message ( self . queue_name , pickle . dumps ( request , protocol = 2 ) )
log... |
def delete ( self , name , kind = None ) :
"""Removes an input from the collection .
: param ` kind ` : The kind of input :
- " ad " : Active Directory
- " monitor " : Files and directories
- " registry " : Windows Registry
- " script " : Scripts
- " splunktcp " : TCP , processed
- " tcp " : TCP , unp... | if kind is None :
self . service . delete ( self [ name ] . path )
else :
self . service . delete ( self [ name , kind ] . path )
return self |
def get_archiver ( self , kind ) :
"""Returns instance of archiver class specific to given kind
: param kind : archive kind""" | archivers = { 'tar' : TarArchiver , 'tbz2' : Tbz2Archiver , 'tgz' : TgzArchiver , 'zip' : ZipArchiver , }
return archivers [ kind ] ( ) |
def updateBar ( self , bar ) :
"""更新K线""" | self . count += 1
if not self . inited and self . count >= self . size :
self . inited = True
self . openArray [ 0 : self . size - 1 ] = self . openArray [ 1 : self . size ]
self . highArray [ 0 : self . size - 1 ] = self . highArray [ 1 : self . size ]
self . lowArray [ 0 : self . size - 1 ] = self . lowArray [ 1 ... |
def fancy_transpose ( data , roll = 1 ) :
"""Fancy transpose
This method transposes a multidimensional matrix .
Parameters
data : np . ndarray
Input data array
roll : int
Roll direction and amount . Default ( roll = 1)
Returns
np . ndarray transposed data
Notes
Adjustment to numpy . transpose
... | axis_roll = np . roll ( np . arange ( data . ndim ) , roll )
return np . transpose ( data , axes = axis_roll ) |
def _int_from_str ( string ) :
"""Convert string into integer
Raise :
TypeError if string is not a valid integer""" | float_num = float ( string )
int_num = int ( float_num )
if float_num == int_num :
return int_num
else : # Needed to handle pseudos with fractional charge
int_num = np . rint ( float_num )
logger . warning ( "Converting float %s to int %s" % ( float_num , int_num ) )
return int_num |
def to_python ( self , value ) :
"""Converts any value to a base . Version field .""" | if value is None or value == '' :
return value
if isinstance ( value , base . Version ) :
return value
if self . coerce :
return base . Version . coerce ( value , partial = self . partial )
else :
return base . Version ( value , partial = self . partial ) |
def get_template_names ( self ) :
"""Adds crud _ template _ name to default template names .""" | names = super ( CRUDMixin , self ) . get_template_names ( )
if self . crud_template_name :
names . append ( self . crud_template_name )
return names |
def filter ( self , filter_func ) :
"""Return a new SampleCollection containing only samples meeting the filter criteria .
Will pass any kwargs ( e . g . , field or skip _ missing ) used when instantiating the current class
on to the new SampleCollection that is returned .
Parameters
filter _ func : ` calla... | if callable ( filter_func ) :
return self . __class__ ( [ obj for obj in self if filter_func ( obj ) is True ] , ** self . _kwargs )
else :
raise OneCodexException ( "Expected callable for filter, got: {}" . format ( type ( filter_func ) . __name__ ) ) |
def run ( self , cmd ) :
"""Similar to profile . Profile . run .""" | import __main__
dict = __main__ . __dict__
return self . runctx ( cmd , dict , dict ) |
def set_value ( self , items , complete = False , on_projects = False , on_globals = False , projectname = None , base = '' , dtype = None , ** kwargs ) :
"""Set a value in the configuration
Parameters
items : dict
A dictionary whose keys correspond to the item in the configuration
and whose values are what... | def identity ( val ) :
return val
config = self . info ( complete = complete , on_projects = on_projects , on_globals = on_globals , projectname = projectname , return_dict = True , insert_id = False , ** kwargs )
if isinstance ( dtype , six . string_types ) :
dtype = getattr ( builtins , dtype )
elif dtype is ... |
def com_google_fonts_check_metadata_normal_style ( ttFont , font_metadata ) :
"""METADATA . pb font . style " normal " matches font internals ?""" | from fontbakery . utils import get_name_entry_strings
from fontbakery . constants import MacStyle
if font_metadata . style != "normal" :
yield SKIP , "This check only applies to normal fonts."
# FIXME : declare a common condition called " normal _ style "
else :
font_familyname = get_name_entry_strings ( tt... |
def decommission_brokers ( self , broker_ids ) :
"""Decommission a list of brokers trying to keep the replication group
the brokers belong to balanced .
: param broker _ ids : list of string representing valid broker ids in the cluster
: raises : InvalidBrokerIdError when the id is invalid .""" | groups = set ( )
for b_id in broker_ids :
try :
broker = self . cluster_topology . brokers [ b_id ]
except KeyError :
self . log . error ( "Invalid broker id %s." , b_id )
# Raise an error for now . As alternative we may ignore the
# invalid id and continue with the others .
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.