signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def read_int8 ( self , little_endian = True ) :
"""Read 1 byte as a signed integer value from the stream .
Args :
little _ endian ( bool ) : specify the endianness . ( Default ) Little endian .
Returns :
int :""" | if little_endian :
endian = "<"
else :
endian = ">"
return self . unpack ( '%sb' % endian ) |
def setIndexes ( self , indexes ) :
"""Sets the list of indexed lookups for this schema to the inputted list .
: param indexes | [ < orb . Index > , . . ]""" | self . __indexes = { }
for name , index in indexes . items ( ) :
self . __indexes [ name ] = index
index . setSchema ( self ) |
def internal_minimum_spanning_tree ( mr_distances ) :
"""Compute the ' internal ' minimum spanning tree given a matrix of mutual
reachability distances . Given a minimum spanning tree the ' internal '
graph is the subgraph induced by vertices of degree greater than one .
Parameters
mr _ distances : array ( ... | single_linkage_data = mst_linkage_core ( mr_distances )
min_span_tree = single_linkage_data . copy ( )
for index , row in enumerate ( min_span_tree [ 1 : ] , 1 ) :
candidates = np . where ( isclose ( mr_distances [ int ( row [ 1 ] ) ] , row [ 2 ] ) ) [ 0 ]
candidates = np . intersect1d ( candidates , single_lin... |
def profile_setting_default_args ( ij ) :
"""Build the default args for this profile .
Args :
ij ( dict ) : The install . json contents .
Returns :
dict : The default args for a Job or Playbook App .""" | # build default args
profile_default_args = OrderedDict ( )
profile_default_args [ 'api_default_org' ] = '$env.API_DEFAULT_ORG'
profile_default_args [ 'api_access_id' ] = '$env.API_ACCESS_ID'
profile_default_args [ 'api_secret_key' ] = '$envs.API_SECRET_KEY'
profile_default_args [ 'tc_api_path' ] = '$env.TC_API_PATH'
p... |
def _disc_kn ( clearness_index , airmass , max_airmass = 12 ) :
"""Calculate Kn for ` disc `
Parameters
clearness _ index : numeric
airmass : numeric
max _ airmass : float
airmass > max _ airmass is set to max _ airmass before being used
in calculating Kn .
Returns
Kn : numeric
am : numeric
airm... | # short names for equations
kt = clearness_index
am = airmass
am = np . minimum ( am , max_airmass )
# GH 450
# powers of kt will be used repeatedly , so compute only once
kt2 = kt * kt
# about the same as kt * * 2
kt3 = kt2 * kt
# 5-10x faster than kt * * 3
bools = ( kt <= 0.6 )
a = np . where ( bools , 0.512 - 1.56 *... |
def addReadGroupSet ( self ) :
"""Adds a new ReadGroupSet into this repo .""" | self . _openRepo ( )
dataset = self . _repo . getDatasetByName ( self . _args . datasetName )
dataUrl = self . _args . dataFile
indexFile = self . _args . indexFile
parsed = urlparse . urlparse ( dataUrl )
# TODO , add https support and others when they have been
# tested .
if parsed . scheme in [ 'http' , 'ftp' ] :
... |
def _set_url ( self , url ) :
"""Set a new URL for the data server . If we ' re unable to contact
the given url , then the original url is kept .""" | original_url = self . _url
try :
self . _update_index ( url )
except :
self . _url = original_url
raise |
def Parse ( self , stat , file_object , knowledge_base ) :
"""Parse a ntp config into rdf .""" | _ , _ = stat , knowledge_base
# TODO ( hanuszczak ) : This parser only allows single use because it messes
# with its state . This should be fixed .
field_parser = NtpdFieldParser ( )
for line in field_parser . ParseEntries ( utils . ReadFileBytesAsUnicode ( file_object ) ) :
field_parser . ParseLine ( line )
yield... |
def region_interface_areas ( regions , areas , voxel_size = 1 , strel = None ) :
r"""Calculates the interfacial area between all pairs of adjecent regions
Parameters
regions : ND - array
An image of the pore space partitioned into individual pore regions .
Note that zeros in the image will not be considered... | print ( '_' * 60 )
print ( 'Finding interfacial areas between each region' )
from skimage . morphology import disk , square , ball , cube
im = regions . copy ( )
if im . ndim != im . squeeze ( ) . ndim :
warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np... |
def find_urls ( observatory , frametype , start , end , on_gaps = 'error' , connection = None , ** connection_kw ) :
"""Find the URLs of files of a given data type in a GPS interval .
See also
gwdatafind . http . HTTPConnection . find _ urls
FflConnection . find _ urls
for details on the underlying method (... | return connection . find_urls ( observatory , frametype , start , end , on_gaps = on_gaps ) |
def get_mcu_definition ( self , project_file ) :
"""Parse project file to get mcu definition""" | # TODO : check the extension here if it ' s valid IAR project or we
# should at least check if syntax is correct check something IAR defines and return error if not
project_file = join ( getcwd ( ) , project_file )
ewp_dic = xmltodict . parse ( file ( project_file ) , dict_constructor = dict )
mcu = MCU_TEMPLATE
try :
... |
def _encrypt_data_key ( self , data_key , algorithm , encryption_context ) :
"""Performs the provider - specific key encryption actions .
: param data _ key : Unencrypted data key
: type data _ key : : class : ` aws _ encryption _ sdk . structures . RawDataKey `
or : class : ` aws _ encryption _ sdk . structu... | # Raw key string to EncryptedData
encrypted_wrapped_key = self . config . wrapping_key . encrypt ( plaintext_data_key = data_key . data_key , encryption_context = encryption_context )
# EncryptedData to EncryptedDataKey
return aws_encryption_sdk . internal . formatting . serialize . serialize_wrapped_key ( key_provider... |
def new_payment_query_listener ( sender , order = None , payment = None , ** kwargs ) :
"""Here we fill only two obligatory fields of payment , and leave signal handler""" | payment . amount = order . total
payment . currency = order . currency
logger . debug ( "new_payment_query_listener, amount=%s, currency=%s" , payment . amount , payment . currency ) |
def randmio_und ( R , itr , seed = None ) :
'''This function randomizes an undirected network , while preserving the
degree distribution . The function does not preserve the strength
distribution in weighted networks .
Parameters
W : NxN np . ndarray
undirected binary / weighted connection matrix
itr : ... | if not np . all ( R == R . T ) :
raise BCTParamError ( "Input must be undirected" )
rng = get_rng ( seed )
R = R . copy ( )
n = len ( R )
i , j = np . where ( np . tril ( R ) )
k = len ( i )
itr *= k
# maximum number of rewiring attempts per iteration
max_attempts = np . round ( n * k / ( n * ( n - 1 ) ) )
# actual... |
def access_vlan ( self , inter_type , inter , vlan_id ) :
"""Add a L2 Interface to a specific VLAN .
Args :
inter _ type : The type of interface you want to configure . Ex .
tengigabitethernet , gigabitethernet , fortygigabitethernet .
inter : The ID for the interface you want to configure . Ex . 1/0/1
vl... | config = ET . Element ( 'config' )
interface = ET . SubElement ( config , 'interface' , xmlns = ( "urn:brocade.com:mgmt:" "brocade-interface" ) )
int_type = ET . SubElement ( interface , inter_type )
name = ET . SubElement ( int_type , 'name' )
name . text = inter
switchport = ET . SubElement ( int_type , 'switchport' ... |
def on_message ( self , opcode , message ) :
"""The primary dispatch function to handle incoming WebSocket messages .
: param int opcode : The opcode of the message that was received .
: param bytes message : The data contained within the message .""" | self . logger . debug ( "processing {0} (opcode: 0x{1:02x}) message" . format ( self . _opcode_names . get ( opcode , 'UNKNOWN' ) , opcode ) )
if opcode == self . _opcode_close :
self . close ( )
elif opcode == self . _opcode_ping :
if len ( message ) > 125 :
self . close ( )
return
self . s... |
def to_array ( self ) :
"""Serializes this PassportElementErrorFiles to a dictionary .
: return : dictionary representation of this object .
: rtype : dict""" | array = super ( PassportElementErrorFiles , self ) . to_array ( )
array [ 'source' ] = u ( self . source )
# py2 : type unicode , py3 : type str
array [ 'type' ] = u ( self . type )
# py2 : type unicode , py3 : type str
array [ 'file_hashes' ] = self . _as_array ( self . file_hashes )
# type list of str
array [ 'messag... |
def time_signature_event ( self , meter = ( 4 , 4 ) ) :
"""Return a time signature event for meter .""" | numer = a2b_hex ( '%02x' % meter [ 0 ] )
denom = a2b_hex ( '%02x' % int ( log ( meter [ 1 ] , 2 ) ) )
return self . delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer + denom + '\x18\x08' |
def targets_from_background ( back_cnn , work_dir , data ) :
"""Retrieve target and antitarget BEDs from background CNN file .""" | target_file = os . path . join ( work_dir , "%s.target.bed" % dd . get_sample_name ( data ) )
anti_file = os . path . join ( work_dir , "%s.antitarget.bed" % dd . get_sample_name ( data ) )
if not utils . file_exists ( target_file ) :
with file_transaction ( data , target_file ) as tx_out_file :
out_base = ... |
def __warn_user_if_wd_maybe_unreadable ( self , abs_remote_path ) :
"""Check directories above the remote module and issue a warning if
they are not traversable by all users .
The reasoning behind this is mainly aimed at set - ups with a
centralized Hadoop cluster , accessed by all users , and where
the Had... | host , port , path = hdfs . path . split ( abs_remote_path )
if host == '' and port == 0 : # local file system
host_port = "file:///"
else : # FIXME : this won ' t work with any scheme other than
# hdfs : / / ( e . g . , s3)
host_port = "hdfs://%s:%s/" % ( host , port )
path_pieces = path . strip ( '/' ) . spli... |
def have_same_chars ( s0 : str , s1 : str ) -> bool :
"""Checks if two strings have the same unique characters .
: param s0 : The first string to compare
: param s1 : The second string to compare
: return : True if both strings have the same unique characters , False otherwise
> > > have _ same _ chars ( ' ... | # Convert both strings to a set to filter out duplicates
set_s0 = set ( s0 )
set_s1 = set ( s1 )
# If the sets are equal , the strings have the same characters
return set_s0 == set_s1 |
def add_bucket_key_data ( self , bucket , key , data , bucket_type = None ) :
"""Adds a bucket / key / keydata triple to the inputs .
: param bucket : the bucket
: type bucket : string
: param key : the key or list of keys
: type key : string
: param data : the key - specific data
: type data : string ,... | if self . _input_mode == 'bucket' :
raise ValueError ( 'Already added a bucket, can\'t add an object.' )
elif self . _input_mode == 'query' :
raise ValueError ( 'Already added a query, can\'t add an object.' )
else :
if isinstance ( key , Iterable ) and not isinstance ( key , string_types ) :
if buc... |
def recall_at_k ( model , test_interactions , train_interactions = None , k = 10 , user_features = None , item_features = None , preserve_rows = False , num_threads = 1 , check_intersections = True , ) :
"""Measure the recall at k metric for a model : the number of positive items in
the first k positions of the r... | if num_threads < 1 :
raise ValueError ( "Number of threads must be 1 or larger." )
ranks = model . predict_rank ( test_interactions , train_interactions = train_interactions , user_features = user_features , item_features = item_features , num_threads = num_threads , check_intersections = check_intersections , )
ra... |
def sort_reverse_chronologically ( self ) :
"""Sorts the measurements of this buffer in reverse chronological order""" | self . measurements . sort ( key = lambda m : m . timestamp , reverse = True ) |
def ndarr2str ( arr , encoding = 'ascii' ) :
"""This is used to ensure that the return value of arr . tostring ( )
is actually a string . This will prevent lots of if - checks in calling
code . As of numpy v1.6.1 ( in Python 3.2.3 ) , the tostring ( ) function
still returns type ' bytes ' , not ' str ' as it ... | # be fast , don ' t check - just assume ' arr ' is a numpy array - the tostring
# call will fail anyway if not
retval = arr . tostring ( )
# would rather check " if isinstance ( retval , bytes ) " , but support 2.5.
# could rm the if PY3K check , but it makes this faster on 2 . x .
if PY3K and not isinstance ( retval ,... |
def modify_rest_retry ( self , total = 8 , connect = None , read = None , redirect = None , status = None , method_whitelist = urllib3 . util . retry . Retry . DEFAULT_METHOD_WHITELIST , status_forcelist = None , backoff_factor = 0.705883 , raise_on_redirect = True , raise_on_status = True , respect_retry_after_header ... | # Cloudgenix responses with 502/504 are usually recoverable . Use them if no list specified .
if status_forcelist is None :
status_forcelist = ( 413 , 429 , 502 , 503 , 504 )
retry = urllib3 . util . retry . Retry ( total = total , connect = connect , read = read , redirect = redirect , status = status , method_whi... |
def random_alphanum ( length ) :
"""Return a random string of ASCII letters and digits .
: param int length : The length of string to return
: returns : A random string
: rtype : str""" | charset = string . ascii_letters + string . digits
return random_string ( length , charset ) |
def hdepth ( tag ) :
"""Compute an h tag ' s " outline depth " .
E . g . , h1 at top level is 1 , h1 in a section is 2 , h2 at top level is 2.""" | if not _heading_re . search ( tag . name ) :
raise TaskError ( "Can't compute heading depth of non-heading {}" . format ( tag ) )
depth = int ( tag . name [ 1 ] , 10 )
# get the 2 from ' h2'
cursor = tag
while cursor :
if cursor . name == 'section' :
depth += 1
cursor = cursor . parent
return depth |
def update_offer_comment ( self , offer_comment_id , offer_comment_dict ) :
"""Updates an offer comment
: param offer _ comment _ id : the offer comment id
: param offer _ comment _ dict : dict
: return : dict""" | return self . _create_put_request ( resource = OFFER_COMMENTS , billomat_id = offer_comment_id , send_data = offer_comment_dict ) |
def count ( tex ) :
"""Extract all labels , then count the number of times each is referenced in
the provided file . Does not follow \ includes .""" | # soupify
soup = TexSoup ( tex )
# extract all unique labels
labels = set ( label . string for label in soup . find_all ( 'label' ) )
# create dictionary mapping label to number of references
return dict ( ( label , soup . find_all ( '\ref{%s}' % label ) ) for label in labels ) |
def stop_event ( self , event_type ) :
"""Stop dispatching the given event .
It is not an error to attempt to stop an event that was never started ,
the request will just be silently ignored .""" | if event_type in self . __timers :
pyglet . clock . unschedule ( self . __timers [ event_type ] ) |
def extern_project_multi ( self , context_handle , val , field_str_ptr , field_str_len ) :
"""Given a Key for ` obj ` , and a field name , project the field as a list of Keys .""" | c = self . _ffi . from_handle ( context_handle )
obj = c . from_value ( val [ 0 ] )
field_name = self . to_py_str ( field_str_ptr , field_str_len )
return c . vals_buf ( tuple ( c . to_value ( p ) for p in getattr ( obj , field_name ) ) ) |
def delete_before ( self , segment_info ) :
"""Delete all base backups and WAL before a given segment
This is the most commonly - used deletion operator ; to delete
old backups and WAL .""" | # This will delete all base backup data before segment _ info .
self . _delete_base_backups_before ( segment_info )
# This will delete all WAL segments before segment _ info .
self . _delete_wals_before ( segment_info )
if self . deleter :
self . deleter . close ( ) |
def _one_prob_per_shard ( args : Dict [ str , Any ] ) -> float :
"""Returns the probability of getting a one measurement on a state shard .""" | index = args [ 'index' ]
state = _state_shard ( args ) * _one_projector ( args , index )
norm = np . linalg . norm ( state )
return norm * norm |
def call_on_each_endpoint ( self , callback ) :
"""Find all server endpoints defined in the swagger spec and calls ' callback ' for each ,
with an instance of EndpointData as argument .""" | if 'paths' not in self . swagger_dict :
return
for path , d in list ( self . swagger_dict [ 'paths' ] . items ( ) ) :
for method , op_spec in list ( d . items ( ) ) :
data = EndpointData ( path , method )
# Which server method handles this endpoint ?
if 'x-bind-server' not in op_spec :
... |
def path2url ( p ) :
"""Return file : / / URL from a filename .""" | # Python 3 is a bit different and does a better job .
if sys . version_info . major >= 3 and sys . version_info . minor >= 4 :
import pathlib
return pathlib . Path ( p ) . as_uri ( )
else :
return six . moves . urllib . parse . urljoin ( 'file:' , six . moves . urllib . request . pathname2url ( p ) ) |
def start ( self ) :
"""Starts the OplogWatcher .""" | oplog = self . connection . local [ 'oplog.rs' ]
if self . ts is None :
cursor = oplog . find ( ) . sort ( '$natural' , - 1 )
obj = cursor [ 0 ]
if obj :
self . ts = obj [ 'ts' ]
else : # In case no oplogs are present .
self . ts = None
if self . ts :
logging . info ( 'Watching oplog... |
def hill_climbing_stochastic ( problem , iterations_limit = 0 , viewer = None ) :
'''Stochastic hill climbing .
If iterations _ limit is specified , the algorithm will end after that
number of iterations . Else , it will continue until it can ' t find a
better node than the current one .
Requires : SearchPr... | return _local_search ( problem , _random_best_expander , iterations_limit = iterations_limit , fringe_size = 1 , stop_when_no_better = iterations_limit == 0 , viewer = viewer ) |
def run ( self , sensor_graph , model ) :
"""Run this optimization pass on the sensor graph
If necessary , information on the device model being targeted
can be found in the associated model argument .
Args :
sensor _ graph ( SensorGraph ) : The sensor graph to optimize
model ( DeviceModel ) : The device ... | # This check can be done if there is 1 input and it is count = = 1
# and the stream type is input or unbuffered
for node , inputs , outputs in sensor_graph . iterate_bfs ( ) :
if node . num_inputs != 1 :
continue
input_a , trigger_a = node . inputs [ 0 ]
if input_a . selector . match_type not in [ D... |
def uintersect1d ( arr1 , arr2 , assume_unique = False ) :
"""Find the sorted unique elements of the two input arrays .
A wrapper around numpy . intersect1d that preserves units . All input arrays
must have the same units . See the documentation of numpy . intersect1d for
full details .
Examples
> > > fro... | v = np . intersect1d ( arr1 , arr2 , assume_unique = assume_unique )
v = _validate_numpy_wrapper_units ( v , [ arr1 , arr2 ] )
return v |
def new_connection ( self ) :
"""Make a new connection .""" | if not self . prepared :
self . prepare ( )
con = sqlite3 . connect ( self . path , isolation_level = self . isolation )
con . row_factory = self . factory
if self . text_fact :
con . text_factory = self . text_fact
return con |
def call_temperature ( * args , ** kwargs ) :
'''Set the mired color temperature . More : http : / / en . wikipedia . org / wiki / Mired
Arguments :
* * * value * * : 150 ~ 500.
Options :
* * * id * * : Specifies a device ID . Can be a comma - separated values . All , if omitted .
CLI Example :
. . code... | res = dict ( )
if 'value' not in kwargs :
raise CommandExecutionError ( "Parameter 'value' (150~500) is missing" )
try :
value = max ( min ( int ( kwargs [ 'value' ] ) , 500 ) , 150 )
except Exception as err :
raise CommandExecutionError ( "Parameter 'value' does not contains an integer" )
devices = _get_li... |
def create ( self , qname ) :
'''Create RackSpace Queue .''' | try :
if self . exists ( qname ) :
log . error ( 'Queues "%s" already exists. Nothing done.' , qname )
return True
self . conn . create ( qname )
return True
except pyrax . exceptions as err_msg :
log . error ( 'RackSpace API got some problems during creation: %s' , err_msg )
return Fals... |
def is_finished ( self ) :
"""Returns whether all trials have finished running .""" | if self . _total_time > self . _global_time_limit :
logger . warning ( "Exceeded global time limit {} / {}" . format ( self . _total_time , self . _global_time_limit ) )
return True
trials_done = all ( trial . is_finished ( ) for trial in self . _trials )
return trials_done and self . _search_alg . is_finished ... |
def _parse_common ( text , ** options ) :
"""Tries to parse the string as a common datetime format .
: param text : The string to parse .
: type text : str
: rtype : dict or None""" | m = COMMON . match ( text )
has_date = False
year = 0
month = 1
day = 1
if not m :
raise ParserError ( "Invalid datetime string" )
if m . group ( "date" ) : # A date has been specified
has_date = True
year = int ( m . group ( "year" ) )
if not m . group ( "monthday" ) : # No month and day
month ... |
def register ( self , func ) :
"""Register function to templates .""" | if callable ( func ) :
self . functions [ func . __name__ ] = func
return func |
def dtw ( x , y , dist , warp = 1 , w = inf , s = 1.0 ) :
"""Computes Dynamic Time Warping ( DTW ) of two sequences .
: param array x : N1 * M array
: param array y : N2 * M array
: param func dist : distance used as cost measure
: param int warp : how many shifts are computed .
: param int w : window siz... | assert len ( x )
assert len ( y )
assert isinf ( w ) or ( w >= abs ( len ( x ) - len ( y ) ) )
assert s > 0
r , c = len ( x ) , len ( y )
if not isinf ( w ) :
D0 = full ( ( r + 1 , c + 1 ) , inf )
for i in range ( 1 , r + 1 ) :
D0 [ i , max ( 1 , i - w ) : min ( c + 1 , i + w + 1 ) ] = 0
D0 [ 0 , 0 ... |
def get_ansible_by_id ( self , ansible_id ) :
"""Return a ansible with that id or None .""" | for elem in self . ansible_hosts :
if elem . id == ansible_id :
return elem
return None |
def _run_callback ( self , callback : Callable [ [ ] , Any ] ) -> None :
"""Runs a callback with error handling .
. . versionchanged : : 6.0
CancelledErrors are no longer logged .""" | try :
ret = callback ( )
if ret is not None :
from tornado import gen
# Functions that return Futures typically swallow all
# exceptions and store them in the Future . If a Future
# makes it out to the IOLoop , ensure its exception ( if any )
# gets logged too .
t... |
def _set_sport_number_lt_udp ( self , v , load = False ) :
"""Setter method for sport _ number _ lt _ udp , mapped from YANG variable / ipv6 _ acl / ipv6 / access _ list / extended / seq / sport _ number _ lt _ udp ( union )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = [ RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'pim-auto-rp' : { 'value' : 496 } , u'domain' : { 'value' : 53 } , u'tacacs' : { 'value' : 49 } , u'snmp' : { 'value' : 161 } ... |
def get_siblings ( self ) :
"""Get a list of sibling accounts associated with provided account .""" | method = 'GET'
endpoint = '/rest/v1.1/users/{}/siblings' . format ( self . client . sauce_username )
return self . client . request ( method , endpoint ) |
def line_prompt4var ( self , * args ) :
"""% % prompt4var - Prompt for macro variables that will
be assigned to the SAS session . The variables will be
prompted each time the line magic is executed .
Example :
% prompt4var libpath file1
filename myfile " ~ & file1 . " ;
libname data " & libpath " ;""" | prmpt = OrderedDict ( )
for arg in args :
assert isinstance ( arg , str )
prmpt [ arg ] = False
if not len ( self . code ) :
if self . kernel . mva is None :
self . kernel . _allow_stdin = True
self . kernel . _start_sas ( )
self . kernel . mva . submit ( code = self . code , results = "... |
def timesync_send ( self , tc1 , ts1 , force_mavlink1 = False ) :
'''Time synchronization message .
tc1 : Time sync timestamp 1 ( int64 _ t )
ts1 : Time sync timestamp 2 ( int64 _ t )''' | return self . send ( self . timesync_encode ( tc1 , ts1 ) , force_mavlink1 = force_mavlink1 ) |
async def answer_media_group ( self , media : typing . Union [ MediaGroup , typing . List ] , disable_notification : typing . Union [ base . Boolean , None ] = None , reply = False ) -> typing . List [ Message ] :
"""Use this method to send a group of photos or videos as an album .
Source : https : / / core . tel... | return await self . bot . send_media_group ( self . chat . id , media = media , disable_notification = disable_notification , reply_to_message_id = self . message_id if reply else None ) |
def set_laplacian_matrix ( self , laplacian_mat ) :
"""Parameters
laplacian _ mat : sparse matrix ( N _ obs , N _ obs ) .
The Laplacian matrix to input .""" | laplacian_mat = check_array ( laplacian_mat , accept_sparse = sparse_formats )
if laplacian_mat . shape [ 0 ] != laplacian_mat . shape [ 1 ] :
raise ValueError ( "Laplacian matrix is not square" )
self . laplacian_matrix = laplacian_mat |
def do_transaction ( args ) :
"""Runs the transaction list or show command , printing to the console
Args :
args : The parsed arguments sent to the command at runtime""" | rest_client = RestClient ( args . url , args . user )
if args . subcommand == 'list' :
transactions = rest_client . list_transactions ( )
keys = ( 'transaction_id' , 'family' , 'version' , 'size' , 'payload' )
headers = tuple ( k . upper ( ) if k != 'version' else 'VERS' for k in keys )
def parse_txn_ro... |
def _download_single_image ( label_path : Path , img_tuple : tuple , i : int , timeout : int = 4 ) -> None :
"""Downloads a single image from Google Search results to ` label _ path `
given an ` img _ tuple ` that contains ` ( fname , url ) ` of an image to download .
` i ` is just an iteration number ` int ` .... | suffix = re . findall ( r'\.\w+?(?=(?:\?|$))' , img_tuple [ 1 ] )
suffix = suffix [ 0 ] . lower ( ) if len ( suffix ) > 0 else '.jpg'
fname = f"{i:08d}{suffix}"
download_url ( img_tuple [ 1 ] , label_path / fname , timeout = timeout ) |
def capture_insert ( self , * , exclude_fields = ( ) ) :
"""Apply : meth : ` . TriggerLogAbstract . capture _ insert _ from _ model ` for this log .""" | return self . capture_insert_from_model ( self . table_name , self . record_id , exclude_fields = exclude_fields ) |
def _nth_of_year ( self , nth , day_of_week ) :
"""Modify to the given occurrence of a given day of the week
in the current year . If the calculated occurrence is outside ,
the scope of the current year , then return False and no
modifications are made . Use the supplied consts
to indicate the desired day _... | if nth == 1 :
return self . first_of ( "year" , day_of_week )
dt = self . first_of ( "year" )
year = dt . year
for i in range ( nth - ( 1 if dt . day_of_week == day_of_week else 0 ) ) :
dt = dt . next ( day_of_week )
if year != dt . year :
return False
return self . on ( self . year , dt . month , dt . day ... |
def selection_r ( x_bounds , x_types , clusteringmodel_gmm_good , clusteringmodel_gmm_bad , num_starting_points = 100 , minimize_constraints_fun = None ) :
'''Call selection''' | minimize_starting_points = [ lib_data . rand ( x_bounds , x_types ) for i in range ( 0 , num_starting_points ) ]
outputs = selection ( x_bounds , x_types , clusteringmodel_gmm_good , clusteringmodel_gmm_bad , minimize_starting_points , minimize_constraints_fun )
return outputs |
def reset ( vm_ , ** kwargs ) :
'''Reset a VM by emulating the reset button on a physical machine
: param vm _ : domain name
: param connection : libvirt connection URI , overriding defaults
. . versionadded : : 2019.2.0
: param username : username to connect with , overriding defaults
. . versionadded : ... | conn = __get_conn ( ** kwargs )
dom = _get_domain ( conn , vm_ )
# reset takes a flag , like reboot , but it is not yet used
# so we just pass in 0
# see : http : / / libvirt . org / html / libvirt - libvirt . html # virDomainReset
ret = dom . reset ( 0 ) == 0
conn . close ( )
return ret |
def CopyNote ( self , part , measure_id , new_note ) :
'''handles copying the latest note into the measure note list .
done at end of note loading to make sure staff _ id is right as staff id could be encountered
any point during the note tag
: param part : the part class to copy it into
: param measure _ i... | if part . getMeasure ( measure_id , self . data [ "staff_id" ] ) is None :
part . addEmptyMeasure ( measure_id , self . data [ "staff_id" ] )
measure = part . getMeasure ( measure_id , self . data [ "staff_id" ] )
voice_obj = measure . getVoice ( self . data [ "voice" ] )
if voice_obj is None :
measure . addVoi... |
def _translate_src_oprnd ( self , operand ) :
"""Translate source operand to a SMT expression .""" | if isinstance ( operand , ReilRegisterOperand ) :
return self . _translate_src_register_oprnd ( operand )
elif isinstance ( operand , ReilImmediateOperand ) :
return smtsymbol . Constant ( operand . size , operand . immediate )
else :
raise Exception ( "Invalid operand type" ) |
def remove_child_objective_bank ( self , objective_bank_id , child_id ) :
"""Removes a child from an objective bank .
arg : objective _ bank _ id ( osid . id . Id ) : the ` ` Id ` ` of an
objective bank
arg : child _ id ( osid . id . Id ) : the ` ` Id ` ` of the child
raise : NotFound - ` ` objective _ bank... | # Implemented from template for
# osid . resource . BinHierarchyDesignSession . remove _ child _ bin _ template
if self . _catalog_session is not None :
return self . _catalog_session . remove_child_catalog ( catalog_id = objective_bank_id , child_id = child_id )
return self . _hierarchy_session . remove_child ( id... |
def data_received ( self , data ) :
"""Got response on RTSP session .
Manage time out handle since response came in a reasonable time .
Update session parameters with latest response .
If state is playing schedule keep - alive .""" | self . time_out_handle . cancel ( )
self . session . update ( data . decode ( ) )
if self . session . state == STATE_STARTING :
self . transport . write ( self . method . message . encode ( ) )
self . time_out_handle = self . loop . call_later ( TIME_OUT_LIMIT , self . time_out )
elif self . session . state == ... |
def sysctl ( state , host , name , value , persist = False , persist_file = '/etc/sysctl.conf' , ) :
'''Edit sysctl configuration .
+ name : name of the sysctl setting to ensure
+ value : the value or list of values the sysctl should be
+ persist : whether to write this sysctl to the config
+ persist _ file... | string_value = ( ' ' . join ( value ) if isinstance ( value , list ) else value )
existing_value = host . fact . sysctl . get ( name )
if not existing_value or existing_value != value :
yield 'sysctl {0}={1}' . format ( name , string_value )
if persist :
yield files . line ( state , host , persist_file , '{0}[[... |
def get ( url , ** kwargs ) :
"""Wrapper for ` request . get ` function to set params .""" | headers = kwargs . get ( 'headers' , { } )
headers [ 'User-Agent' ] = config . USER_AGENT
# overwrite
kwargs [ 'headers' ] = headers
timeout = kwargs . get ( 'timeout' , config . TIMEOUT )
kwargs [ 'timeout' ] = timeout
kwargs [ 'verify' ] = False
# no SSLError
logger . debug ( "Getting: %s" , url )
return requests . g... |
def generate ( env ) :
"""Add Builders and construction variables for lib to an Environment .""" | SCons . Tool . createStaticLibBuilder ( env )
SCons . Tool . createSharedLibBuilder ( env )
SCons . Tool . createProgBuilder ( env )
env [ 'AR' ] = 'mwld'
env [ 'ARCOM' ] = '$AR $ARFLAGS -library -o $TARGET $SOURCES'
env [ 'LIBDIRPREFIX' ] = '-L'
env [ 'LIBDIRSUFFIX' ] = ''
env [ 'LIBLINKPREFIX' ] = '-l'
env [ 'LIBLINK... |
def add_monitor ( self , pattern , callback , limit = 80 ) :
"""Calls the given function whenever the given pattern matches the
incoming data .
. . HINT : :
If you want to catch all incoming data regardless of a
pattern , use the Protocol . data _ received _ event event instead .
Arguments passed to the c... | self . buffer . add_monitor ( pattern , partial ( callback , self ) , limit ) |
def predicatesIn ( G : Graph , n : Node ) -> Set [ TriplePredicate ] :
"""predicatesIn ( G , n ) is the set of predicates in arcsIn ( G , n ) .""" | return { p for _ , p in G . subject_predicates ( n ) } |
def push ( collector , image , ** kwargs ) :
"""Push an image""" | if not image . image_index :
raise BadOption ( "The chosen image does not have a image_index configuration" , wanted = image . name )
tag = kwargs [ "artifact" ]
if tag is NotSpecified :
tag = collector . configuration [ "harpoon" ] . tag
if tag is not NotSpecified :
image . tag = tag
Builder ( ) . make_ima... |
def reset_aggregations ( self ) :
"""Remove all aggregations added to the search object""" | temp_search = self . search . to_dict ( )
if 'aggs' in temp_search . keys ( ) :
del temp_search [ 'aggs' ]
self . search . from_dict ( temp_search )
self . parent_agg_counter = 0
self . child_agg_counter = 0
self . child_agg_counter_dict = defaultdict ( int ) |
def _increment ( sign , integer_part , non_repeating_part , base ) :
"""Return an increment radix .
: param int sign : - 1 , 0 , or 1 as appropriate
: param integer _ part : the integer part
: type integer _ part : list of int
: param non _ repeating _ part : the fractional part
: type non _ repeating _ p... | ( carry , non_repeating_part ) = Nats . carry_in ( non_repeating_part , 1 , base )
( carry , integer_part ) = Nats . carry_in ( integer_part , carry , base )
return Radix ( sign , integer_part if carry == 0 else [ carry ] + integer_part , non_repeating_part , [ ] , base , False ) |
def register_task_with_maintenance_window ( WindowId = None , Targets = None , TaskArn = None , ServiceRoleArn = None , TaskType = None , TaskParameters = None , Priority = None , MaxConcurrency = None , MaxErrors = None , LoggingInfo = None , ClientToken = None ) :
"""Adds a new task to a Maintenance Window .
Se... | pass |
def list_file_volumes ( self , datacenter = None , username = None , storage_type = None , ** kwargs ) :
"""Returns a list of file volumes .
: param datacenter : Datacenter short name ( e . g . : dal09)
: param username : Name of volume .
: param storage _ type : Type of volume : Endurance or Performance
: ... | if 'mask' not in kwargs :
items = [ 'id' , 'username' , 'capacityGb' , 'bytesUsed' , 'serviceResource.datacenter[name]' , 'serviceResourceBackendIpAddress' , 'activeTransactionCount' , 'fileNetworkMountAddress' , 'replicationPartnerCount' ]
kwargs [ 'mask' ] = ',' . join ( items )
_filter = utils . NestedDict (... |
def set_step ( self , value , block_events = False ) :
"""Sets the step of the number box .
Setting block _ events = True will temporarily block the widget from
sending any signals when setting the value .""" | if block_events :
self . block_events ( )
self . _widget . setSingleStep ( value )
if block_events :
self . unblock_events ( ) |
def notify_state_name_change ( self , model , prop_name , info ) :
"""Checks whether the name of a state was changed and change the tab label accordingly""" | # avoid updates or checks because of execution status updates
if is_execution_status_update_notification_from_state_machine_model ( prop_name , info ) :
return
overview = NotificationOverview ( info , False , self . __class__ . __name__ )
changed_model = overview [ 'model' ] [ - 1 ]
method_name = overview [ 'method... |
def psdump ( self , filename = None , ** kargs ) :
"""psdump ( filename = None , layer _ shift = 0 , rebuild = 1)
Creates an EPS file describing a packet . If filename is not provided a temporary file is created and gs is called .""" | canvas = self . canvas_dump ( ** kargs )
if filename is None :
fname = get_temp_file ( autoext = ".eps" )
canvas . writeEPSfile ( fname )
subprocess . Popen ( [ conf . prog . psreader , fname + ".eps" ] )
else :
canvas . writeEPSfile ( filename ) |
def union ( self , another_is ) :
"""Return the union between self and ` ` another _ is ` ` .
Parameters
another _ is : ` IntervalSet `
an IntervalSet object .
Returns
interval : ` IntervalSet `
the union of self with ` ` another _ is ` ` .""" | result = IntervalSet ( )
if another_is . empty ( ) :
result . _intervals = self . _intervals
elif self . empty ( ) :
result . _intervals = another_is . _intervals
else : # res has no overlapping intervals
result . _intervals = IntervalSet . merge ( self . _intervals , another_is . _intervals , lambda in_a ,... |
def _basic_return ( self , args , msg ) :
"""return a failed message
This method returns an undeliverable message that was
published with the " immediate " flag set , or an unroutable
message published with the " mandatory " flag set . The reply
code and text provide information about the reason that the
... | reply_code = args . read_short ( )
reply_text = args . read_shortstr ( )
exchange = args . read_shortstr ( )
routing_key = args . read_shortstr ( )
self . returned_messages . put ( ( reply_code , reply_text , exchange , routing_key , msg ) ) |
def _next_channel ( self ) :
"""you are holding the lock""" | chanid = self . _channel_counter
while self . _channels . get ( chanid ) is not None :
self . _channel_counter = ( self . _channel_counter + 1 ) & 0xffffff
chanid = self . _channel_counter
self . _channel_counter = ( self . _channel_counter + 1 ) & 0xffffff
return chanid |
def detect_hooks ( ) :
"""Returns True if the import hooks are installed , False if not .""" | flog . debug ( 'Detecting hooks ...' )
present = any ( [ hasattr ( hook , 'RENAMER' ) for hook in sys . meta_path ] )
if present :
flog . debug ( 'Detected.' )
else :
flog . debug ( 'Not detected.' )
return present |
def retrieve ( pdb_id , cache_dir = None , bio_cache = None ) :
'''Creates a FASTA object by using a cached copy of the file if it exists or by retrieving the file from the RCSB .''' | pdb_id = pdb_id . upper ( )
if bio_cache :
return FASTA ( bio_cache . get_fasta_contents ( pdb_id ) )
# Check to see whether we have a cached copy
if cache_dir :
filename = os . path . join ( cache_dir , "%s.fasta" % pdb_id )
if os . path . exists ( filename ) :
return FASTA ( read_file ( filename )... |
def echo_worker ( self ) :
"""The ` echo _ worker ` works through the ` self . received _ transfers ` queue and spawns
` self . on _ transfer ` greenlets for all not - yet - seen transfers .""" | log . debug ( 'echo worker' , qsize = self . received_transfers . qsize ( ) )
while self . stop_signal is None :
if self . received_transfers . qsize ( ) > 0 :
transfer = self . received_transfers . get ( )
if transfer in self . seen_transfers :
log . debug ( 'duplicate transfer ignored'... |
def permute ( self , ba ) :
"""Permute the bitarray ba inplace .""" | c = ba . copy ( )
for i in xrange ( len ( self . mapping ) ) :
ba [ i ] = c [ self . mapping [ i ] ]
return ba |
def _key_digest ( self , secret_key ) :
'''a helper method for creating a base 64 encoded secret key and digest
: param secret _ key : string with key to encrypt / decrypt data
: return : string with base64 key , string with base64 digest''' | from hashlib import md5 , sha256
from base64 import b64encode
key_bytes = sha256 ( secret_key . encode ( 'utf-8' ) ) . digest ( )
key_b64 = b64encode ( key_bytes ) . decode ( )
digest_bytes = md5 ( key_bytes ) . digest ( )
digest_b64 = b64encode ( digest_bytes ) . decode ( )
return key_b64 , digest_b64 |
def fetch_country_by_ip ( ip ) :
"""Fetches country code by IP
Returns empty string if the request fails in non - 200 code .
Uses the ipdata . co service which has the following rules :
* Max 1500 requests per day
See : https : / / ipdata . co / docs . html # python - library""" | iplookup = ipdata . ipdata ( )
data = iplookup . lookup ( ip )
if data . get ( 'status' ) != 200 :
return ''
return data . get ( 'response' , { } ) . get ( 'country_code' , '' ) |
def find_word_prob ( word_string , word_total = sum ( WORD_DISTRIBUTION . values ( ) ) ) :
'''Finds the relative probability of the word appearing given context of a base corpus .
Returns this probability value as a float instance .''' | if word_string is None :
return 0
elif isinstance ( word_string , str ) :
return WORD_DISTRIBUTION [ word_string ] / word_total
else :
raise InputError ( "string or none type variable not passed as argument to find_word_prob" ) |
def list_projects ( self ) :
"""Lists all deployed projects . First class , maps to Scrapyd ' s
list projects endpoint .""" | url = self . _build_url ( constants . LIST_PROJECTS_ENDPOINT )
json = self . client . get ( url , timeout = self . timeout )
return json [ 'projects' ] |
def move_to_position ( cls , resource_id , to_position , new_parent_id = noop , db_session = None , * args , ** kwargs ) :
"""Moves node to new location in the tree
: param resource _ id : resource to move
: param to _ position : new position
: param new _ parent _ id : new parent id
: param db _ session : ... | db_session = get_db_session ( db_session )
# lets lock rows to prevent bad tree states
resource = ResourceService . lock_resource_for_update ( resource_id = resource_id , db_session = db_session )
ResourceService . lock_resource_for_update ( resource_id = resource . parent_id , db_session = db_session )
same_branch = F... |
def update ( self , key_vals = None , overwrite = True ) :
"""Locked keys will be overwritten unless overwrite = False .
Otherwise , written keys will be added to the " locked " list .""" | if not key_vals :
return
write_items = self . _update ( key_vals , overwrite )
self . _root . _root_set ( self . _path , write_items )
self . _root . _write ( commit = True ) |
def prepare_timestamp_millis ( data , schema ) :
"""Converts datetime . datetime object to int timestamp with milliseconds""" | if isinstance ( data , datetime . datetime ) :
if data . tzinfo is not None :
delta = ( data - epoch )
return int ( delta . total_seconds ( ) * MLS_PER_SECOND )
t = int ( time . mktime ( data . timetuple ( ) ) ) * MLS_PER_SECOND + int ( data . microsecond / 1000 )
return t
else :
return ... |
def print_state ( state : State , file : TextIO = None ) -> None :
"""Print a state vector""" | state = state . vec . asarray ( )
for index , amplitude in np . ndenumerate ( state ) :
ket = "" . join ( [ str ( n ) for n in index ] )
print ( ket , ":" , amplitude , file = file ) |
def clip_gradients ( batch_result , model , max_grad_norm ) :
"""Clip gradients to a given maximum length""" | if max_grad_norm is not None :
grad_norm = torch . nn . utils . clip_grad_norm_ ( filter ( lambda p : p . requires_grad , model . parameters ( ) ) , max_norm = max_grad_norm )
else :
grad_norm = 0.0
batch_result [ 'grad_norm' ] = grad_norm |
def transitive_edges ( graph ) :
"""Return a list of transitive edges .
Example of transitivity within graphs : A - > B , B - > C , A - > C
in this case the transitive edge is : A - > C
@ attention : This function is only meaningful for directed acyclic graphs .
@ type graph : digraph
@ param graph : Digr... | # if the graph contains a cycle we return an empty array
if not len ( find_cycle ( graph ) ) == 0 :
return [ ]
tranz_edges = [ ]
# create an empty array that will contain all the tuples
# run trough all the nodes in the graph
for start in topological_sorting ( graph ) : # find all the successors on the path for the... |
def encode_positions ( self , positions : mx . sym . Symbol , data : mx . sym . Symbol ) -> mx . sym . Symbol :
""": param positions : ( batch _ size , )
: param data : ( batch _ size , num _ embed )
: return : ( batch _ size , num _ embed )""" | # ( batch _ size , 1)
positions = mx . sym . expand_dims ( positions , axis = 1 )
# ( num _ embed , )
channels = mx . sym . arange ( 0 , self . num_embed // 2 )
# (1 , num _ embed , )
scaling = mx . sym . expand_dims ( 1. / mx . sym . pow ( 10000 , ( 2 * channels ) / self . num_embed ) , axis = 0 )
# ( batch _ size , n... |
def wrap_results ( self , ** kwargs ) :
"""Wrap returned http response into a well formatted dict
: param kwargs : this dict param should contains following keys :
fd : file directory to
url : the test url fo the result
files _ count : the number of files under har / directory
: return ( dict ) : the resu... | if 'fd' not in kwargs or 'url' not in kwargs or 'files_count' not in kwargs :
logging . error ( "Missing arguments in wrap_results function" )
return { }
external = kwargs [ 'external' ] if 'external' in kwargs else None
fd = kwargs [ 'fd' ]
url = kwargs [ 'url' ]
length = kwargs [ 'files_count' ]
results = { }... |
def xdr ( self ) :
"""Packs and base64 encodes this : class : ` Transaction ` as an XDR
string .""" | tx = Xdr . StellarXDRPacker ( )
tx . pack_Transaction ( self . to_xdr_object ( ) )
return base64 . b64encode ( tx . get_buffer ( ) ) |
def render_registered ( url_id , remote_info ) :
"""Render template file for the registered user , which has some of the values
prefilled .
Args :
url _ id ( str ) : Seeder URL id .
remote _ info ( dict ) : Informations read from Seeder .
Returns :
str : Template filled with data .""" | return template ( read_index_template ( ) , registered = True , url = remote_info [ "url" ] , seeder_data = json . dumps ( remote_info ) , url_id = url_id , ) |
def value_map ( f , m , * args , ** kwargs ) :
'''value _ map ( f , mapping ) yields a persistent map whose keys are the same as those of the given dict
or mapping object and whose values , for each key k are f ( mapping [ k ] ) .
value _ map ( f , mapping , * args , * * kw ) additionally passes the given argum... | if is_lazy_map ( m ) :
return lazy_value_map ( f , m , * args , ** kwargs )
else :
return ps . pmap ( { k : f ( v , * args , ** kwargs ) for ( k , v ) in six . iteritems ( m ) } ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.