signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def title ( cls , message = None ) :
'''Set the title of the process''' | if message == None :
return getproctitle ( )
else :
setproctitle ( 'qless-py-worker %s' % message )
logger . info ( message ) |
def get_frequencies_with_eigenvectors ( self , q ) :
"""Calculate phonon frequencies and eigenvectors at a given q - point
Parameters
q : array _ like
A q - vector .
shape = ( 3 , )
Returns
( frequencies , eigenvectors )
frequencies : ndarray
Phonon frequencies
shape = ( bands , ) , dtype = ' doub... | self . _set_dynamical_matrix ( )
if self . _dynamical_matrix is None :
msg = ( "Dynamical matrix has not yet built." )
raise RuntimeError ( msg )
self . _dynamical_matrix . set_dynamical_matrix ( q )
dm = self . _dynamical_matrix . get_dynamical_matrix ( )
frequencies = [ ]
eigvals , eigenvectors = np . linalg ... |
def compute_laplacian_matrix ( self , copy = True , return_lapsym = False , ** kwargs ) :
"""Note : this function will compute the laplacian matrix . In order to acquire
the existing laplacian matrix use self . laplacian _ matrix as
comptute _ laplacian _ matrix ( ) will re - compute the laplacian matrix .
Pa... | if self . affinity_matrix is None :
self . compute_affinity_matrix ( )
kwds = self . laplacian_kwds . copy ( )
kwds . update ( kwargs )
kwds [ 'full_output' ] = return_lapsym
result = compute_laplacian_matrix ( self . affinity_matrix , self . laplacian_method , ** kwds )
if return_lapsym :
( self . laplacian_ma... |
def _parse_procedures ( self , contents , iface ) :
"""" Parses the list of procedures or signatures defined in the generic , operator
or assignment interface .
: arg contents : the text between the interface . . . end interface keywords .
: arg iface : the fortpy . elements . Interface instance that will own... | procs = contents . split ( "module procedure" )
stripped = [ p . strip ( ) for p in procs if p . strip ( ) != "" ]
for embed in stripped : # We want to first extract the name of the procedure , then find its element
# instance to append to the Interface instance ' s procedures list .
methods = re . split ( ",\s*" ,... |
def prepare_env ( app , env , docname ) :
"""Prepares the sphinx environment to store sphinx - needs internal data .""" | if not hasattr ( env , 'needs_all_needs' ) : # Used to store all needed information about all needs in document
env . needs_all_needs = { }
if not hasattr ( env , 'needs_functions' ) : # Used to store all registered functions for supporting dynamic need values .
env . needs_functions = { }
# needs _ functio... |
def sample ( self , bqm , apply_flux_bias_offsets = True , ** kwargs ) :
"""Sample from the given Ising model .
Args :
h ( list / dict ) :
Linear biases of the Ising model . If a list , the list ' s indices
are used as variable labels .
J ( dict of ( int , int ) : float ) :
Quadratic biases of the Ising... | child = self . child
if apply_flux_bias_offsets :
if self . flux_biases is not None :
kwargs [ FLUX_BIAS_KWARG ] = self . flux_biases
return child . sample ( bqm , ** kwargs ) |
def myreplace ( astr , thefind , thereplace ) :
"""in string astr replace all occurences of thefind with thereplace""" | alist = astr . split ( thefind )
new_s = alist . split ( thereplace )
return new_s |
def _get_lineage ( self , tax_id , merge_obsolete = True ) :
"""Return a list of [ ( rank , tax _ id ) ] describing the lineage of
tax _ id . If ` ` merge _ obsolete ` ` is True and ` ` tax _ id ` ` has been
replaced , use the corresponding value in table merged .""" | # Be sure we aren ' t working with an obsolete tax _ id
if merge_obsolete :
tax_id = self . _get_merged ( tax_id )
# Note : joining with ranks seems like a no - op , but for some
# reason it results in a faster query using sqlite , as well as
# an ordering from leaf - - > root . Might be a better idea to
# sort exp... |
def update_todo_menu ( self ) :
"""Update todo list menu""" | editorstack = self . get_current_editorstack ( )
results = editorstack . get_todo_results ( )
self . todo_menu . clear ( )
filename = self . get_current_filename ( )
for text , line0 in results :
icon = ima . icon ( 'todo' )
slot = lambda _checked , _l = line0 : self . load ( filename , goto = _l )
action =... |
def searchPageFor ( doc , pno , text , hit_max = 16 , quads = False ) :
"""Search for a string on a page .
Args :
pno : page number
text : string to be searched for
hit _ max : maximum hits
quads : return quads instead of rectangles
Returns :
a list of rectangles or quads , each containing an occurren... | return doc [ pno ] . searchFor ( text , hit_max = hit_max , quads = quads ) |
def _field_to_json ( field , row_value ) :
"""Convert a field into JSON - serializable values .
Args :
field ( : class : ` ~ google . cloud . bigquery . schema . SchemaField ` , ) :
The SchemaField to use for type conversion and field name .
row _ value ( Union [ Sequence [ list ] , any , ] ) :
Row data t... | if row_value is None :
return None
if field . mode == "REPEATED" :
return _repeated_field_to_json ( field , row_value )
if field . field_type == "RECORD" :
return _record_field_to_json ( field . fields , row_value )
return _scalar_field_to_json ( field , row_value ) |
def announced ( self , state , announcement ) :
'''This part of contract is just to let the guy know we are here .''' | state . problem = state . factory ( state . agent , ** announcement . payload )
state . medium . bid ( message . Bid ( ) ) |
def removeBinder ( self , name ) :
"""Remove a binder from a table""" | root = self . etree
t_bindings = root . find ( 'bindings' )
t_binder = t_bindings . find ( name )
if t_binder :
t_bindings . remove ( t_binder )
return True
return False |
def ccnot_circuit ( qubits : Qubits ) -> Circuit :
"""Standard decomposition of CCNOT ( Toffoli ) gate into
six CNOT gates ( Plus Hadamard and T gates . ) [ Nielsen2000 ] _
. . [ Nielsen2000]
M . A . Nielsen and I . L . Chuang , Quantum Computation and Quantum
Information , Cambridge University Press ( 2000... | if len ( qubits ) != 3 :
raise ValueError ( 'Expected 3 qubits' )
q0 , q1 , q2 = qubits
circ = Circuit ( )
circ += H ( q2 )
circ += CNOT ( q1 , q2 )
circ += T ( q2 ) . H
circ += CNOT ( q0 , q2 )
circ += T ( q2 )
circ += CNOT ( q1 , q2 )
circ += T ( q2 ) . H
circ += CNOT ( q0 , q2 )
circ += T ( q1 )
circ += T ( q2 )... |
def four_motor_swerve_drivetrain ( lr_motor , rr_motor , lf_motor , rf_motor , lr_angle , rr_angle , lf_angle , rf_angle , x_wheelbase = 2 , y_wheelbase = 2 , speed = 5 , deadzone = None , ) :
"""Four motors that can be rotated in any direction
If any motors are inverted , then you will need to multiply that moto... | if deadzone :
lf_motor = deadzone ( lf_motor )
lr_motor = deadzone ( lr_motor )
rf_motor = deadzone ( rf_motor )
rr_motor = deadzone ( rr_motor )
# Calculate speed of each wheel
lr = lr_motor * speed
rr = rr_motor * speed
lf = lf_motor * speed
rf = rf_motor * speed
# Calculate angle in radians
lr_rad = ... |
def rmon_alarm_entry_snmp_oid ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
rmon = ET . SubElement ( config , "rmon" , xmlns = "urn:brocade.com:mgmt:brocade-rmon" )
alarm_entry = ET . SubElement ( rmon , "alarm-entry" )
alarm_index_key = ET . SubElement ( alarm_entry , "alarm-index" )
alarm_index_key . text = kwargs . pop ( 'alarm_index' )
snmp_oid = ET . Sub... |
def set_condition ( self , condition , condition_instr = None ) :
"""Defines the condition which decides how the basic block exits
: param condition :
: type condition :
: param condition _ instr : If the ' condition ' argument is a Variable , then condition _ instr is None , else , condition _ instr should b... | assert ( isinstance ( condition , Numeric ) )
if condition_instr is not None :
assert ( isinstance ( condition_instr , CmpInstruction ) )
self . condition = condition
self . condition_instr = condition_instr
if condition_instr is not None :
if condition_instr . lhs not in self . defined_variables :
if i... |
def show_cationpi ( self ) :
"""Visualizes cation - pi interactions""" | grp = self . getPseudoBondGroup ( "Cation-Pi-%i" % self . tid , associateWith = [ self . model ] )
grp . lineWidth = 3
grp . lineType = self . chimera . Dash
for i , cat in enumerate ( self . plcomplex . pication ) :
m = self . model
r = m . newResidue ( "pseudoatoms" , " " , 1 , " " )
chargecenter = m . ne... |
def neg ( self , value , name = '' ) :
"""Integer negative :
name = - value""" | return self . sub ( values . Constant ( value . type , 0 ) , value , name = name ) |
def _read_record ( self , f , blk , chans ) :
"""Read raw data from a single EDF channel .
Parameters
i _ chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
numpy . ndarray
A vector with the data as written on file , in 16... | dat_in_rec = empty ( ( len ( chans ) , self . max_smp ) )
i_ch_in_dat = 0
for i_ch in chans :
offset , n_smp_per_chan = self . _offset ( blk , i_ch )
f . seek ( offset )
x = fromfile ( f , count = n_smp_per_chan , dtype = EDF_FORMAT )
ratio = int ( self . max_smp / n_smp_per_chan )
dat_in_rec [ i_ch... |
def __add_bootstrap_tour_step ( self , message , selector = None , name = None , title = None , alignment = None , duration = None ) :
"""Allows the user to add tour steps for a website .
@ Params
message - The message to display .
selector - The CSS Selector of the Element to attach to .
name - If creating... | if selector != "html" :
selector = self . __make_css_match_first_element_only ( selector )
element_row = "element: '%s'," % selector
else :
element_row = ""
if not duration :
duration = "0"
else :
duration = str ( float ( duration ) * 1000.0 )
step = ( """{
%s
title: ... |
def search_archive ( pattern , archive , verbosity = 0 , interactive = True ) :
"""Search pattern in archive members .""" | if not pattern :
raise util . PatoolError ( "empty search pattern" )
util . check_existing_filename ( archive )
if verbosity >= 0 :
util . log_info ( "Searching %r in %s ..." % ( pattern , archive ) )
res = _search_archive ( pattern , archive , verbosity = verbosity , interactive = interactive )
if res == 1 and... |
def off ( self ) :
"""Turn off curses""" | self . win . keypad ( 0 )
curses . nocbreak ( )
curses . echo ( )
try :
curses . curs_set ( 1 )
except :
pass
curses . endwin ( ) |
def single_qubit_op_to_framed_phase_form ( mat : np . ndarray ) -> Tuple [ np . ndarray , complex , complex ] :
"""Decomposes a 2x2 unitary M into U ^ - 1 * diag ( 1 , r ) * U * diag ( g , g ) .
U translates the rotation axis of M to the Z axis .
g fixes a global phase factor difference caused by the translatio... | vals , vecs = np . linalg . eig ( mat )
u = np . conj ( vecs ) . T
r = vals [ 1 ] / vals [ 0 ]
g = vals [ 0 ]
return u , r , g |
def ensure_context ( ** vars ) :
"""Ensures that a context is in the stack , creates one otherwise .""" | ctx = _context_stack . top
stacked = False
if not ctx :
ctx = Context ( )
stacked = True
_context_stack . push ( ctx )
ctx . update ( vars )
try :
yield ctx
finally :
if stacked :
_context_stack . pop ( ) |
def intervalCreateSimulateAnalyze ( netParams = None , simConfig = None , output = False , interval = None ) :
'''Sequence of commands create , simulate and analyse network''' | import os
from . . import sim
( pops , cells , conns , stims , rxd , simData ) = sim . create ( netParams , simConfig , output = True )
try :
if sim . rank == 0 :
if os . path . exists ( 'temp' ) :
for f in os . listdir ( 'temp' ) :
os . unlink ( 'temp/{}' . format ( f ) )
... |
def _updateNumbers ( self , linenumers ) :
"""add / remove line numbers""" | b = self . blockCount ( )
c = b - linenumers
if c > 0 : # remove lines numbers
for _ in range ( c ) : # remove last line :
self . setFocus ( )
storeCursorPos = self . textCursor ( )
self . moveCursor ( QtGui . QTextCursor . End , QtGui . QTextCursor . MoveAnchor )
self . moveCursor (... |
def checkout ( url , version = None ) :
"""Checks out latest version of item or repository .
: param url : URL of repo or item to check out .
: param version : Version number to check out .""" | from grit import Repo
r = Repo ( url )
def _write ( item ) :
log . debug ( 'writing: %s' % item . name )
if item . type != 'blob' :
return
if r . type in [ 'repo' , 'proxy' , 'local' ] :
path = os . path . join ( r . name , item . path )
pdir = os . path . dirname ( path )
if... |
def _kl_divergence_disagreement ( self , proba ) :
"""Calculate the Kullback - Leibler ( KL ) divergence disaagreement measure .
Parameters
proba : array - like , shape = ( n _ samples , n _ students , n _ class )
Returns
disagreement : list of float , shape = ( n _ samples )
The kl _ divergence of the gi... | n_students = np . shape ( proba ) [ 1 ]
consensus = np . mean ( proba , axis = 1 )
# shape = ( n _ samples , n _ class )
# average probability of each class across all students
consensus = np . tile ( consensus , ( n_students , 1 , 1 ) ) . transpose ( 1 , 0 , 2 )
kl = np . sum ( proba * np . log ( proba / consensus ) ,... |
def core_periphery_dir ( W , gamma = 1 , C0 = None , seed = None ) :
'''The optimal core / periphery subdivision is a partition of the network
into two nonoverlapping groups of nodes , a core group and a periphery
group . The number of core - group edges is maximized , and the number of
within periphery edges... | rng = get_rng ( seed )
n = len ( W )
np . fill_diagonal ( W , 0 )
if C0 == None :
C = rng . randint ( 2 , size = ( n , ) )
else :
C = C0 . copy ( )
# methodological note , the core - detection null model is not corrected
# for degree cf community detection ( to enable detection of hubs )
s = np . sum ( W )
p = ... |
def projects_from_metadata ( metadata ) :
"""Extract the project dependencies from a metadata spec .""" | projects = [ ]
for data in metadata :
meta = distlib . metadata . Metadata ( fileobj = io . StringIO ( data ) )
projects . extend ( pypi . just_name ( project ) for project in meta . run_requires )
return frozenset ( map ( packaging . utils . canonicalize_name , projects ) ) |
def update_with_result ( self , result ) :
"""Update item - model with result from host
State is sent from host after processing had taken place
and represents the events that took place ; including
log messages and completion status .
Arguments :
result ( dict ) : Dictionary following the Result schema""... | assert isinstance ( result , dict ) , "%s is not a dictionary" % result
for type in ( "instance" , "plugin" ) :
id = ( result [ type ] or { } ) . get ( "id" )
is_context = not id
if is_context :
item = self . instances [ 0 ]
else :
item = self . items . get ( id )
if item is None : #... |
def gauss_fit ( map_data , chs = None , mode = 'deg' , amplitude = 1 , x_mean = 0 , y_mean = 0 , x_stddev = None , y_stddev = None , theta = None , cov_matrix = None , noise = 0 , ** kwargs ) :
"""make a 2D Gaussian model and fit the observed data with the model .
Args :
map _ data ( xarray . Dataarray ) : Data... | if chs is None :
chs = np . ogrid [ 0 : 63 ]
# the number of channels would be changed
if len ( chs ) > 1 :
for n , ch in enumerate ( chs ) :
subdata = np . transpose ( np . full_like ( map_data [ : , : , ch ] , map_data . values [ : , : , ch ] ) )
subdata [ np . isnan ( subdata ) ] = 0
... |
def qteKeyPress ( self , msgObj ) :
"""Record the key presses .""" | # Unpack the data structure .
( srcObj , keysequence , macroName ) = msgObj . data
# Return immediately if the key sequence does not specify a
# macro ( yet ) .
if macroName is None :
return
# If the macro to repeat is this very macro then disable the
# macro proxy , otherwise execute the macro that would have run
... |
def from_cstr_to_pystr ( data , length ) :
"""Revert C pointer to Python str
Parameters
data : ctypes pointer
pointer to data
length : ctypes pointer
pointer to length of data""" | if PY3 :
res = [ ]
for i in range ( length . value ) :
try :
res . append ( str ( data [ i ] . decode ( 'ascii' ) ) )
except UnicodeDecodeError :
res . append ( str ( data [ i ] . decode ( 'utf-8' ) ) )
else :
res = [ ]
for i in range ( length . value ) :
... |
def get_sos_decomposition ( sdp , y_mat = None , threshold = 0.0 ) :
"""Given a solution of the dual problem , it returns the SOS
decomposition .
: param sdp : The SDP relaxation to be solved .
: type sdp : : class : ` ncpol2sdpa . sdp ` .
: param y _ mat : Optional parameter providing the dual solution of ... | if len ( sdp . monomial_sets ) != 1 :
raise Exception ( "Cannot automatically match primal and dual " + "variables." )
elif len ( sdp . y_mat [ 1 : ] ) != len ( sdp . constraints ) :
raise Exception ( "Cannot automatically match constraints with blocks " + "in the dual solution." )
elif sdp . status == "unsolve... |
def copy ( self ) :
"""Return a deep copy""" | result = Scalar ( self . size , self . deriv )
result . v = self . v
if self . deriv > 0 :
result . d [ : ] = self . d [ : ]
if self . deriv > 1 :
result . dd [ : ] = self . dd [ : ]
return result |
def mutations_batcher ( self , flush_count = FLUSH_COUNT , max_row_bytes = MAX_ROW_BYTES ) :
"""Factory to create a mutation batcher associated with this instance .
For example :
. . literalinclude : : snippets _ table . py
: start - after : [ START bigtable _ mutations _ batcher ]
: end - before : [ END bi... | return MutationsBatcher ( self , flush_count , max_row_bytes ) |
def works ( self , ids = None , query = None , filter = None , offset = None , limit = None , sample = None , sort = None , order = None , facet = None , select = None , cursor = None , cursor_max = 5000 , ** kwargs ) :
'''Search Crossref works
: param ids : [ Array ] DOIs ( digital object identifier ) or other i... | if ids . __class__ . __name__ != 'NoneType' :
return request ( self . mailto , self . base_url , "/works/" , ids , query , filter , offset , limit , sample , sort , order , facet , select , None , None , None , None , ** kwargs )
else :
return Request ( self . mailto , self . base_url , "/works/" , query , filt... |
def pointer_gate ( num_qubits , U ) :
"""Make a pointer gate on ` num _ qubits ` . The one - qubit gate U will act on the
qubit addressed by the pointer qubits interpreted as an unsigned binary
integer .
There are P = floor ( lg ( num _ qubits ) ) pointer qubits , and qubits numbered
N - 1
N - 2
N - P
... | ptr_bits = int ( floor ( np . log2 ( num_qubits ) ) )
data_bits = num_qubits - ptr_bits
ptr_state = 0
assert ptr_bits > 0
program = pq . Program ( )
program . defgate ( "CU" , controlled ( ptr_bits , U ) )
for _ , target_qubit , changed in gray ( ptr_bits ) :
if changed is None :
for ptr_qubit in range ( nu... |
def merge_contextual ( self , other ) :
"""Merge in contextual info from a template Compound .""" | # TODO : This is currently dependent on our data model ? Make more robust to schema changes
# Currently we assume all lists at Compound level , with 1 further potential nested level of lists
for k in self . keys ( ) : # print ( ' key : % s ' % k )
for item in self [ k ] : # print ( ' item : % s ' % item )
f... |
def determine_result ( self , returncode , returnsignal , output , isTimeout ) :
"""Parse the output of the tool and extract the verification result .
This method always needs to be overridden .
If the tool gave a result , this method needs to return one of the
benchexec . result . RESULT _ * strings .
Othe... | for line in output :
if "All test cases time out or crash, giving up!" in line :
return "Couldn't run: all seeds time out or crash"
if "ERROR: couldn't run FairFuzz" in line :
return "Couldn't run FairFuzz"
if "CRASHES FOUND" in line :
return result . RESULT_FALSE_REACH
if "DONE ... |
def _has_skip ( self , msg ) :
'''The message contains the skipping keyword no not .
: return type : Bool''' | for skip in self . skips :
if re . search ( skip , msg ) :
return True
return False |
def init ( self , acct : Account , payer_acct : Account , gas_limit : int , gas_price : int ) -> str :
"""This interface is used to call the TotalSupply method in ope4
that initialize smart contract parameter .
: param acct : an Account class that used to sign the transaction .
: param payer _ acct : an Accou... | func = InvokeFunction ( 'init' )
tx_hash = self . __sdk . get_network ( ) . send_neo_vm_transaction ( self . __hex_contract_address , acct , payer_acct , gas_limit , gas_price , func )
return tx_hash |
def _DropCommonSuffixes ( filename ) :
"""Drops common suffixes like _ test . cc or - inl . h from filename .
For example :
> > > _ DropCommonSuffixes ( ' foo / foo - inl . h ' )
' foo / foo '
> > > _ DropCommonSuffixes ( ' foo / bar / foo . cc ' )
' foo / bar / foo '
> > > _ DropCommonSuffixes ( ' foo ... | for suffix in ( 'test.cc' , 'regtest.cc' , 'unittest.cc' , 'inl.h' , 'impl.h' , 'internal.h' ) :
if ( filename . endswith ( suffix ) and len ( filename ) > len ( suffix ) and filename [ - len ( suffix ) - 1 ] in ( '-' , '_' ) ) :
return filename [ : - len ( suffix ) - 1 ]
return os . path . splitext ( filen... |
def default_marshaller ( obj ) :
"""Retrieve the state of the given object .
Calls the ` ` _ _ getstate _ _ ( ) ` ` method of the object if available , otherwise returns the
` ` _ _ dict _ _ ` ` of the object .
: param obj : the object to marshal
: return : the marshalled object state""" | if hasattr ( obj , '__getstate__' ) :
return obj . __getstate__ ( )
try :
return obj . __dict__
except AttributeError :
raise TypeError ( '{!r} has no __dict__ attribute and does not implement __getstate__()' . format ( obj . __class__ . __name__ ) ) |
def samplerate ( self ) :
"""The audio ' s sample rate ( an int ) .""" | if hasattr ( self . mgfile . info , 'sample_rate' ) :
return self . mgfile . info . sample_rate
elif self . type == 'opus' : # Opus is always 48kHz internally .
return 48000
return 0 |
def remove_entries_for_scope ( self , user_scope , scope_name , scope_value , key ) :
"""RemoveEntriesForScope .
[ Preview API ] Remove the entry or entries under the specified path
: param str user _ scope : User - Scope at which to remove the value . Should be " me " for the current user or " host " for all u... | route_values = { }
if user_scope is not None :
route_values [ 'userScope' ] = self . _serialize . url ( 'user_scope' , user_scope , 'str' )
if scope_name is not None :
route_values [ 'scopeName' ] = self . _serialize . url ( 'scope_name' , scope_name , 'str' )
if scope_value is not None :
route_values [ 'sc... |
async def update_intervals_data ( self ) :
"""Update intervals data json for specified time period .""" | url = '{}/users/{}/intervals' . format ( API_URL , self . userid )
intervals = await self . device . api_get ( url )
if intervals is None :
_LOGGER . error ( 'Unable to fetch eight intervals data.' )
else :
self . intervals = intervals [ 'intervals' ] |
def meter_data_from_csv ( filepath_or_buffer , tz = None , start_col = "start" , value_col = "value" , gzipped = False , freq = None , ** kwargs ) :
"""Load meter data from a CSV file .
Default format : :
start , value
2017-01-01T00:00:00 + 00:00,0.31
2017-01-02T00:00:00 + 00:00,0.4
2017-01-03T00:00:00 + ... | read_csv_kwargs = { "usecols" : [ start_col , value_col ] , "dtype" : { value_col : np . float64 } , "parse_dates" : [ start_col ] , "index_col" : start_col , }
if gzipped :
read_csv_kwargs . update ( { "compression" : "gzip" } )
# allow passing extra kwargs
read_csv_kwargs . update ( kwargs )
df = pd . read_csv ( ... |
def parquet_file ( self , hdfs_dir , schema = None , name = None , database = None , external = True , like_file = None , like_table = None , persist = False , ) :
"""Make indicated parquet file in HDFS available as an Ibis table .
The table created can be optionally named and persisted , otherwise a
unique nam... | name , database = self . _get_concrete_table_path ( name , database , persist = persist )
# If no schema provided , need to find some absolute path to a file in
# the HDFS directory
if like_file is None and like_table is None and schema is None :
file_name = self . hdfs . _find_any_file ( hdfs_dir )
like_file =... |
def filter_international_words ( buf ) :
"""We define three types of bytes :
alphabet : english alphabets [ a - zA - Z ]
international : international characters [ \x80 - \xFF ]
marker : everything else [ ^ a - zA - Z \x80 - \xFF ]
The input buffer can be thought to contain a series of words delimited
by ... | filtered = bytearray ( )
# This regex expression filters out only words that have at - least one
# international character . The word may include one marker character at
# the end .
words = re . findall ( b'[a-zA-Z]*[\x80-\xFF]+[a-zA-Z]*[^a-zA-Z\x80-\xFF]?' , buf )
for word in words :
filtered . extend ( word [ : -... |
def delete_whitespaces ( self , arg ) :
"""Removes newlines , tabs and whitespaces at the beginning , the end and if there is more than one .
: param arg : A string , the string which shell be cleaned
: return : A string , the cleaned string""" | # Deletes whitespaces after a newline
arg = re . sub ( re_newline_spc , '' , arg )
# Deletes every whitespace , tabulator , newline at the beginning of the string
arg = re . sub ( re_starting_whitespc , '' , arg )
# Deletes whitespace or tabulator if followed by whitespace or tabulator
arg = re . sub ( re_multi_spc_tab... |
def build_options ( func ) :
"""Add " build " Click options to function .
: param function func : The function to wrap .
: return : The wrapped function .
: rtype : function""" | func = click . option ( '-a' , '--banner-greatest-tag' , is_flag = True , help = 'Override banner-main-ref to be the tag with the highest version number.' ) ( func )
func = click . option ( '-A' , '--banner-recent-tag' , is_flag = True , help = 'Override banner-main-ref to be the most recent committed tag.' ) ( func )
... |
def purge_stream ( self , stream_id , remove_definition = False , sandbox = None ) :
"""Clears all the data in a given stream and the calculated intervals
: param stream _ id : The stream id
: param remove _ definition : Whether to remove the stream definition as well
: param sandbox : The sandbox id
: retu... | if sandbox is not None :
raise NotImplementedError
if stream_id not in self . streams :
raise StreamNotFoundError ( stream_id )
self . data [ stream_id ] = StreamInstanceCollection ( )
self . streams [ stream_id ] . calculated_intervals = TimeIntervals ( )
if remove_definition :
del self . data [ stream_id ... |
def get_effective_agent_id ( self ) :
"""Gets the Id of the effective agent in use by this session .
If is _ authenticated ( ) is true , then the effective agent may be
the same as the agent returned by get _ authenticated _ agent ( ) . If
is _ authenticated ( ) is false , then the effective agent may be a
... | if self . is_authenticated ( ) :
return self . _proxy . get_authentication ( ) . get_agent_id ( )
elif self . _proxy is not None and self . _proxy . has_effective_agent ( ) :
return self . _proxy . get_effective_agent_id ( )
else :
return Id ( identifier = 'MC3GUE$T@MIT.EDU' , namespace = 'osid.agent.Agent'... |
def phi_s ( spin1x , spin1y , spin2x , spin2y ) :
"""Returns the sum of the in - plane perpendicular spins .""" | phi1 = phi_from_spinx_spiny ( spin1x , spin1y )
phi2 = phi_from_spinx_spiny ( spin2x , spin2y )
return ( phi1 + phi2 ) % ( 2 * numpy . pi ) |
def _get_number_from_fmt ( fmt ) :
"""Helper function for extract _ values ,
figures out string length from format string .""" | if '%' in fmt : # its datetime
return len ( ( "{0:" + fmt + "}" ) . format ( dt . datetime . now ( ) ) )
else : # its something else
fmt = fmt . lstrip ( '0' )
return int ( re . search ( '[0-9]+' , fmt ) . group ( 0 ) ) |
def disconnect_all ( self , context , ports ) :
"""Disconnect All Command , will the assign all the vnics on the vm to the default network ,
which is sign to be disconnected
: param models . QualiDriverModels . ResourceRemoteCommandContext context : the context the command runs on
: param list [ string ] port... | resource_details = self . _parse_remote_model ( context )
# execute command
res = self . command_wrapper . execute_command_with_connection ( context , self . virtual_switch_disconnect_command . disconnect_all , resource_details . vm_uuid )
return set_command_result ( result = res , unpicklable = False ) |
def register_error_code ( code , exception_type , domain = 'core' ) :
"""Register a new error code""" | Logger . _error_code_to_exception [ code ] = ( exception_type , domain )
Logger . _domain_codes [ domain ] . add ( code ) |
def set_until ( self , frame , lineno = None ) :
"""Stop when the current line number in frame is greater than lineno or
when returning from frame .""" | if lineno is None :
lineno = frame . f_lineno + 1
self . _set_stopinfo ( frame , lineno ) |
def longest_bitonic_sequence ( array : list ) -> int :
"""This function calculates the longest bitonic subsequence in a given list .
A bitonic sequence is a sequence of numbers which is first strictly increasing then after a point strictly decreasing .
Examples :
> > > longest _ bitonic _ sequence ( [ 0 , 8 ,... | n = len ( array )
inc_subseq = [ 1 ] * n
for i in range ( n ) :
for j in range ( i ) :
if array [ i ] > array [ j ] and inc_subseq [ i ] < inc_subseq [ j ] + 1 :
inc_subseq [ i ] = inc_subseq [ j ] + 1
dec_subseq = [ 1 ] * n
for i in reversed ( range ( n - 1 ) ) :
for j in reversed ( range (... |
def break_at_capitals ( input_text ) :
"""This function splits the given string at each occurrence of a uppercase letter .
Args :
input _ text : A string containing mixed ( upper and lower case ) characters
Returns :
A list of words extracted by splitting at each uppercase character .
Examples :
> > > b... | import re
return re . findall ( '[A-Z][^A-Z]*' , input_text ) |
def _build_namespace_dict ( cls , obj , dots = False ) :
"""Recursively replaces all argparse . Namespace and optparse . Values
with dicts and drops any keys with None values .
Additionally , if dots is True , will expand any dot delimited
keys .
: param obj : Namespace , Values , or dict to iterate over . ... | # We expect our root object to be a dict , but it may come in as
# a namespace
obj = namespace_to_dict ( obj )
# We only deal with dictionaries
if not isinstance ( obj , dict ) :
return obj
# Get keys iterator
keys = obj . keys ( ) if PY3 else obj . iterkeys ( )
if dots : # Dots needs sorted keys to prevent parents... |
def read_pkginfo ( filename ) :
"""Help us read the pkginfo without accessing _ _ init _ _""" | COMMENT_CHAR = '#'
OPTION_CHAR = '='
options = { }
f = open ( filename )
for line in f :
if COMMENT_CHAR in line :
line , comment = line . split ( COMMENT_CHAR , 1 )
if OPTION_CHAR in line :
option , value = line . split ( OPTION_CHAR , 1 )
option = option . strip ( )
value = val... |
def generateFeatures ( numFeatures ) :
"""Return string features .
If < = 62 features are requested , output will be single character
alphanumeric strings . Otherwise , output will be [ " F1 " , " F2 " , . . . ]""" | # Capital letters , lowercase letters , numbers
candidates = ( [ chr ( i + 65 ) for i in xrange ( 26 ) ] + [ chr ( i + 97 ) for i in xrange ( 26 ) ] + [ chr ( i + 48 ) for i in xrange ( 10 ) ] )
if numFeatures > len ( candidates ) :
candidates = [ "F{}" . format ( i ) for i in xrange ( numFeatures ) ]
return ca... |
def from_backend ( self , dagobah_id ) :
"""Reconstruct this Dagobah instance from the backend .""" | logger . debug ( 'Reconstructing Dagobah instance from backend with ID {0}' . format ( dagobah_id ) )
rec = self . backend . get_dagobah_json ( dagobah_id )
if not rec :
raise DagobahError ( 'dagobah with id %s does not exist ' 'in backend' % dagobah_id )
self . _construct_from_json ( rec ) |
def _write_var_data_sparse ( self , f , zVar , var , dataType , numElems , recVary , oneblock ) :
'''Writes a VVR and a VXR for this block of sparse data
Parameters :
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var : int
The variable number
dataType : int
The CDF data t... | rec_start = oneblock [ 0 ]
rec_end = oneblock [ 1 ]
indata = oneblock [ 2 ]
numValues = self . _num_values ( zVar , var )
# Convert oneblock [ 2 ] into a byte stream
_ , data = self . _convert_data ( dataType , numElems , numValues , indata )
# Gather dimension information
if zVar :
vdr_offset = self . zvarsinfo [ ... |
def statement ( self ) :
"""statement : assign _ statement
| expression
| control
| empty
Feature For Loop adds :
| loop
Feature Func adds :
| func
| return statement""" | if self . cur_token . type == TokenTypes . VAR :
self . tokenizer . start_saving ( self . cur_token )
self . variable ( )
peek_var = self . cur_token
self . tokenizer . replay ( )
self . eat ( )
if peek_var . type == TokenTypes . ASSIGN :
return self . assign_statement ( )
else :
... |
def renderForSignal ( self , stm : Union [ HdlStatement , List [ HdlStatement ] ] , s : RtlSignalBase , connectOut ) -> Optional [ Tuple [ LNode , Union [ RtlSignalBase , LPort ] ] ] :
"""Walk statement and render nodes which are representing
hardware components ( MUX , LATCH , FF , . . . ) for specified signal""... | # filter statements for this signal only if required
if not isinstance ( stm , HdlStatement ) :
stm = list ( walkStatementsForSig ( stm , s ) )
if not stm :
return None
elif len ( stm ) != 1 :
raise NotImplementedError ( "deduced MUX" )
else :
stm = stm [ 0 ]
# render assignment ... |
def install ( self , force_install = False ) :
"""Installs an app . Blocks until the installation is complete , or raises : exc : ` AppInstallError ` if it fails .
While this method runs , " progress " events will be emitted regularly with the following signature : : :
( sent _ this _ interval , sent _ total , ... | if not ( force_install or self . _bundle . should_permit_install ( ) ) :
raise AppInstallError ( "This pbw is not supported on this platform." )
if self . _pebble . firmware_version . major < 3 :
self . _install_legacy2 ( )
else :
self . _install_modern ( ) |
def getCollapseRequestsFn ( self ) :
"""Helper function to determine which collapseRequests function to use
from L { _ collapseRequests } , or None for no merging""" | # first , seek through builder , global , and the default
collapseRequests_fn = self . config . collapseRequests
if collapseRequests_fn is None :
collapseRequests_fn = self . master . config . collapseRequests
if collapseRequests_fn is None :
collapseRequests_fn = True
# then translate False and True properly
i... |
def _load_compiled ( self , file_path ) :
"""Accepts a path to a compiled plugin and returns a module object .
file _ path : A string that represents a complete file path to a compiled
plugin .""" | name = os . path . splitext ( os . path . split ( file_path ) [ - 1 ] ) [ 0 ]
plugin_directory = os . sep . join ( os . path . split ( file_path ) [ 0 : - 1 ] )
compiled_directory = os . path . join ( plugin_directory , '__pycache__' )
# Use glob to autocomplete the filename .
compiled_file = glob . glob ( os . path . ... |
def getConstructorArguments ( ) :
"""Return constructor argument associated with ColumnPooler .
@ return defaults ( list ) a list of args and default values for each argument""" | argspec = inspect . getargspec ( ColumnPooler . __init__ )
return argspec . args [ 1 : ] , argspec . defaults |
def address ( self ) :
"""The full proxied address to this page""" | path = urlsplit ( self . target ) . path
suffix = '/' if not path or path . endswith ( '/' ) else ''
return '%s%s/%s%s' % ( self . _ui_address [ : - 1 ] , self . _proxy_prefix , self . route , suffix ) |
def load ( self ) :
"""Loads the children for this record item .
: return < bool > | changed""" | if self . __loaded :
return False
self . __loaded = True
self . setChildIndicatorPolicy ( self . DontShowIndicatorWhenChildless )
# loads the children for this widget
tree = self . treeWidget ( )
if tree . groupBy ( ) :
grps = self . childRecords ( ) . grouped ( tree . groupBy ( ) )
for grp , records in grp... |
def read_next_maf ( file , species_to_lengths = None , parse_e_rows = False ) :
"""Read the next MAF block from ` file ` and return as an ` Alignment `
instance . If ` parse _ i _ rows ` is true , empty components will be created
when e rows are encountered .""" | alignment = Alignment ( species_to_lengths = species_to_lengths )
# Attributes line
line = readline ( file , skip_blank = True )
if not line :
return None
fields = line . split ( )
if fields [ 0 ] != 'a' :
raise Exception ( "Expected 'a ...' line" )
alignment . attributes = parse_attributes ( fields [ 1 : ] )
i... |
def retry ( * dargs , ** dkw ) :
"""Wrap a function with a new ` Retrying ` object .
: param dargs : positional arguments passed to Retrying object
: param dkw : keyword arguments passed to the Retrying object""" | # support both @ retry and @ retry ( ) as valid syntax
if len ( dargs ) == 1 and callable ( dargs [ 0 ] ) :
return retry ( ) ( dargs [ 0 ] )
else :
def wrap ( f ) :
if asyncio and asyncio . iscoroutinefunction ( f ) :
r = AsyncRetrying ( * dargs , ** dkw )
elif tornado and hasattr ( ... |
def set ( self , section , key , value , comment = None ) :
"""Set config value with data type transformation ( to str )
: param str section : Section to set config for
: param str key : Key to set config for
: param value : Value for key . It can be any primitive type .
: param str comment : Comment for th... | self . _read_sources ( )
if ( section , key ) in self . _dot_keys :
section , key = self . _dot_keys [ ( section , key ) ]
elif section in self . _dot_keys :
section = self . _dot_keys [ section ]
if not isinstance ( value , str ) :
value = str ( value )
self . _parser . set ( section , key , value )
self .... |
def make_article_info_dates ( self ) :
"""Makes the section containing important dates for the article : typically
Received , Accepted , and Published .""" | dates_div = etree . Element ( 'div' , { 'id' : 'article-dates' } )
d = './front/article-meta/history/date'
received = self . article . root . xpath ( d + "[@date-type='received']" )
accepted = self . article . root . xpath ( d + "[@date-type='accepted']" )
if received :
b = etree . SubElement ( dates_div , 'b' )
... |
def processPayment ( self , amount , fees , paidOnline = True , methodName = None , methodTxn = None , submissionUser = None , collectedByUser = None , forceFinalize = False , status = None , notify = None ) :
'''When a payment processor makes a successful payment against an invoice , it can call this method
whic... | epsilon = .01
paymentTime = timezone . now ( )
logger . info ( 'Processing payment and creating registration objects if applicable.' )
# The payment history record is primarily for convenience , and passed values are not
# validated . Payment processing apps should keep individual transaction records with
# a ForeignKe... |
def getmembers ( self ) :
"""Gets members ( vars ) from all scopes , using both runtime and static .
This method will attempt both static and runtime getmembers . This is the
recommended way of getting available members .
Returns :
Set of available vars .
Raises :
NotImplementedError if any scope fails ... | names = set ( )
for scope in self . scopes :
if isinstance ( scope , type ) :
names . update ( structured . getmembers_static ( scope ) )
else :
names . update ( structured . getmembers_runtime ( scope ) )
return names |
def make_basename ( self , fn = None , ext = None ) :
"""make a filesystem - compliant basename for this file""" | fb , oldext = os . path . splitext ( os . path . basename ( fn or self . fn ) )
ext = ext or oldext . lower ( )
fb = String ( fb ) . hyphenify ( ascii = True )
return '' . join ( [ fb , ext ] ) |
def get_path_contents ( self , project , provider_name , service_endpoint_id = None , repository = None , commit_or_branch = None , path = None ) :
"""GetPathContents .
[ Preview API ] Gets the contents of a directory in the given source code repository .
: param str project : Project ID or project name
: par... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if provider_name is not None :
route_values [ 'providerName' ] = self . _serialize . url ( 'provider_name' , provider_name , 'str' )
query_parameters = { }
if service_endpoint_id is n... |
def parse_security_group ( self , global_params , region , group ) :
"""Parse a single Redsfhit security group
: param global _ params : Parameters shared for all regions
: param region : Name of the AWS region
: param security ) _ group : Security group""" | vpc_id = group [ 'VpcId' ] if 'VpcId' in group and group [ 'VpcId' ] else ec2_classic
manage_dictionary ( self . vpcs , vpc_id , VPCConfig ( self . vpc_resource_types ) )
security_group = { }
security_group [ 'name' ] = group [ 'GroupName' ]
security_group [ 'id' ] = group [ 'GroupId' ]
security_group [ 'description' ]... |
def check_if_not ( x , * checks , ** params ) :
"""Run checks only if parameters are not equal to a specified value
Parameters
x : excepted value
Checks not run if parameters equal x
checks : function
Unnamed arguments , check functions to be run
params : object
Named arguments , parameters to be chec... | for p in params :
if params [ p ] is not x and params [ p ] != x :
[ check ( ** { p : params [ p ] } ) for check in checks ] |
def _rle_decode ( data ) :
"""Decodes run - length - encoded ` data ` .""" | if not data :
return data
new = b''
last = b''
for cur in data :
if last == b'\0' :
new += last * cur
last = b''
else :
new += last
last = bytes ( [ cur ] )
return new + last |
def _renew_token ( self , retry = True ) :
"""Renew expired ThreatConnect Token .""" | self . renewing = True
self . log . info ( 'Renewing ThreatConnect Token' )
self . log . info ( 'Current Token Expiration: {}' . format ( self . _token_expiration ) )
try :
params = { 'expiredToken' : self . _token }
url = '{}/appAuth' . format ( self . _token_url )
r = get ( url , params = params , verify ... |
def append_field ( self , header , value , mask = None ) :
"""Append a match field .
Argument Description
header match field header ID which is defined automatically in
` ` ofproto ` `
value match field value
mask mask value to the match field
The available ` ` header ` ` is as follows .
Header ID Des... | self . fields . append ( OFPMatchField . make ( header , value , mask ) ) |
def contacted ( self ) :
""": retuns : A boolean indicating whether the logged in user has contacted
the owner of this profile .""" | try :
contacted_span = self . _contacted_xpb . one_ ( self . profile_tree )
except :
return False
else :
timestamp = contacted_span . replace ( 'Last contacted ' , '' )
return helpers . parse_date_updated ( timestamp ) |
def check_photometry_categorize ( x , y , levels , tags = None ) :
'''Put every point in its category .
levels must be sorted .''' | x = numpy . asarray ( x )
y = numpy . asarray ( y )
ys = y . copy ( )
ys . sort ( )
# Mean of the upper half
m = ys [ len ( ys ) // 2 : ] . mean ( )
y /= m
m = 1.0
s = ys [ len ( ys ) // 2 : ] . std ( )
result = [ ]
if tags is None :
tags = list ( six . moves . range ( len ( levels ) + 1 ) )
for l , t in zip ( leve... |
def set_cluster_info ( self , aws_access_key_id = None , aws_secret_access_key = None , aws_region = None , aws_availability_zone = None , vpc_id = None , subnet_id = None , master_elastic_ip = None , disallow_cluster_termination = None , enable_ganglia_monitoring = None , node_bootstrap_file = None , master_instance_t... | self . disallow_cluster_termination = disallow_cluster_termination
self . enable_ganglia_monitoring = enable_ganglia_monitoring
self . node_bootstrap_file = node_bootstrap_file
self . set_node_configuration ( master_instance_type , slave_instance_type , initial_nodes , max_nodes , slave_request_type , fallback_to_ondem... |
def get_reference_repository ( self , reference : Optional [ Path ] , repo : str ) -> Optional [ Path ] :
"""Returns a repository to use in clone command , if there is one to be referenced .
Either provided by the user of generated from already cloned branches ( master is preferred ) .
: param reference : Path ... | if reference is not None :
return reference . absolute ( )
repo_path = self . get_path_to_repo ( repo )
if not repo_path . exists ( ) :
return None
master = repo_path / "master"
if master . exists ( ) and master . is_dir ( ) :
return master
for existing_branch in repo_path . iterdir ( ) :
if not existin... |
def check_run ( check , env , rate , times , pause , delay , log_level , as_json , break_point ) :
"""Run an Agent check .""" | envs = get_configured_envs ( check )
if not envs :
echo_failure ( 'No active environments found for `{}`.' . format ( check ) )
echo_info ( 'See what is available to start via `ddev env ls {}`.' . format ( check ) )
abort ( )
if not env :
if len ( envs ) > 1 :
echo_failure ( 'Multiple active env... |
def chunk_generator ( N , n ) :
"""Returns a generator of slice objects .
Parameters
N : int
The size of one of the dimensions of a two - dimensional array .
n : int
The number of arrays of shape ( ' N ' , ' get _ chunk _ size ( N , n ) ' ) that fit into
memory .
Returns
Slice objects of the type ' ... | chunk_size = get_chunk_size ( N , n )
for start in range ( 0 , N , chunk_size ) :
yield slice ( start , min ( start + chunk_size , N ) ) |
async def set_endpoint_for_did ( wallet_handle : int , did : str , address : str , transport_key : str ) -> None :
"""Set / replaces endpoint information for the given DID .
: param wallet _ handle : Wallet handle ( created by open _ wallet ) .
: param did : The DID to resolve endpoint .
: param address : The... | logger = logging . getLogger ( __name__ )
logger . debug ( "set_endpoint_for_did: >>> wallet_handle: %r, did: %r, address: %r, transport_key: %r" , wallet_handle , did , address , transport_key )
if not hasattr ( set_endpoint_for_did , "cb" ) :
logger . debug ( "set_endpoint_for_did: Creating callback" )
set_en... |
def is_provider_configured ( opts , provider , required_keys = ( ) , log_message = True , aliases = ( ) ) :
'''Check and return the first matching and fully configured cloud provider
configuration .''' | if ':' in provider :
alias , driver = provider . split ( ':' )
if alias not in opts [ 'providers' ] :
return False
if driver not in opts [ 'providers' ] [ alias ] :
return False
for key in required_keys :
if opts [ 'providers' ] [ alias ] [ driver ] . get ( key , None ) is None :... |
def _database_default_options ( self , name ) :
"""Get a Database instance with the default settings .""" | return self . get_database ( name , codec_options = DEFAULT_CODEC_OPTIONS , read_preference = ReadPreference . PRIMARY , write_concern = DEFAULT_WRITE_CONCERN ) |
def _purge_children ( self ) :
"""Find dead children and put a response on the result queue .
: return :""" | for task_id , p in six . iteritems ( self . _running_tasks ) :
if not p . is_alive ( ) and p . exitcode :
error_msg = 'Task {} died unexpectedly with exit code {}' . format ( task_id , p . exitcode )
p . task . trigger_event ( Event . PROCESS_FAILURE , p . task , error_msg )
elif p . timeout_tim... |
def pairs ( self , strand , cutoff = 0.001 , temp = 37.0 , pseudo = False , material = None , dangles = 'some' , sodium = 1.0 , magnesium = 0.0 ) :
'''Compute the pair probabilities for an ordered complex of strands .
Runs the \' pairs \' command .
: param strand : Strand on which to run pairs . Strands must be... | # Set the material ( will be used to set command material flag )
material = self . _set_material ( strand , material )
# Set up command flags
cmd_args = self . _prep_cmd_args ( temp , dangles , material , pseudo , sodium , magnesium , multi = False )
# Set up the input file and run the command . Note : no STDOUT
lines ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.