signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def unescape ( cls , text : str ) -> str :
"""Replace escape sequence with corresponding characters .
Args :
text : Text to unescape .""" | chop = text . split ( "\\" , 1 )
try :
return ( chop [ 0 ] if len ( chop ) == 1 else chop [ 0 ] + cls . unescape_map [ chop [ 1 ] [ 0 ] ] + cls . unescape ( chop [ 1 ] [ 1 : ] ) )
except KeyError :
raise InvalidArgument ( text ) from None |
def show_stats ( self , verbose = False , ** kwargs ) :
"""Show statistics on the found proxies .
Useful for debugging , but you can also use if you ' re interested .
: param verbose : Flag indicating whether to print verbose stats
. . deprecated : : 0.2.0
Use : attr : ` verbose ` instead of : attr : ` full... | if kwargs :
verbose = True
warnings . warn ( '`full` in `show_stats` is deprecated, ' 'use `verbose` instead.' , DeprecationWarning , )
found_proxies = self . unique_proxies . values ( )
num_working_proxies = len ( [ p for p in found_proxies if p . is_working ] )
if not found_proxies :
print ( 'Proxy not fo... |
def _get_path ( self , name ) :
"""Get the destination class path .
: param name : The name
: type name : str
: rtype : str""" | path = self . option ( "path" )
if path is None :
path = self . _get_seeders_path ( )
return os . path . join ( path , "%s.py" % name ) |
def _create_gate_variables ( self , input_shape , dtype ) :
"""Initialize the variables used for the gates .""" | if len ( input_shape ) != 2 :
raise ValueError ( "Rank of shape must be {} not: {}" . format ( 2 , len ( input_shape ) ) )
input_size = input_shape . dims [ 1 ] . value
b_shape = [ 4 * self . _hidden_size ]
equiv_input_size = self . _hidden_size + input_size
initializer = basic . create_linear_initializer ( equiv_i... |
def create ( self , data ) :
"""Create object from the given data .
The given data may or may not have been validated prior to calling
this function . This function will try its best in creating the object .
If the resulting object cannot be produced , raises ` ` ValidationError ` ` .
The spec can affect ho... | # todo : copy - paste code from representation . validate - > refactor
if data is None :
return None
prototype = { }
errors = { }
# create and populate the prototype
for field_name , field_spec in self . spec . fields . items ( ) :
try :
value = self . _create_value ( data , field_name , self . spec )
... |
def cluster_autocomplete ( self , text , line , start_index , end_index ) :
"autocomplete for the use command , obtain list of clusters first" | if not self . CACHED_CLUSTERS :
clusters = [ cluster . name for cluster in api . get_all_clusters ( ) ]
self . CACHED_CLUSTERS = clusters
if text :
return [ cluster for cluster in self . CACHED_CLUSTERS if cluster . startswith ( text ) ]
else :
return self . CACHED_CLUSTERS |
def homeautoswitch ( self , cmd , ain = None , param = None ) :
"""Call a switch method .
Should only be used by internal library functions .""" | assert self . sid , "Not logged in"
params = { 'switchcmd' : cmd , 'sid' : self . sid , }
if param is not None :
params [ 'param' ] = param
if ain :
params [ 'ain' ] = ain
url = self . base_url + '/webservices/homeautoswitch.lua'
response = self . session . get ( url , params = params , timeout = 10 )
response ... |
def _spawn_redis_connection_thread ( self ) :
"""Spawns a redis connection thread""" | self . logger . debug ( "Spawn redis connection thread" )
self . redis_connected = False
self . _redis_thread = Thread ( target = self . _setup_redis )
self . _redis_thread . setDaemon ( True )
self . _redis_thread . start ( ) |
def values ( self ) :
"""Returns a list of values for this field for this instance . It ' s a list
so we can accomodate many - to - many fields .""" | # This import is deliberately inside the function because it causes
# some settings to be imported , and we don ' t want to do that at the
# module level .
if self . field . rel :
if isinstance ( self . field . rel , models . ManyToOneRel ) :
objs = getattr ( self . instance . instance , self . field . name... |
def _run_transient ( self , t ) :
"""Performs a transient simulation according to the specified settings
updating ' b ' and calling ' _ t _ run _ reactive ' at each time step .
Stops after reaching the end time ' t _ final ' or after achieving the
specified tolerance ' t _ tolerance ' . Stores the initial and... | tf = self . settings [ 't_final' ]
dt = self . settings [ 't_step' ]
to = self . settings [ 't_output' ]
tol = self . settings [ 't_tolerance' ]
t_pre = self . settings [ 't_precision' ]
s = self . settings [ 't_scheme' ]
res_t = 1e+06
# Initialize the residual
if not isinstance ( to , list ) : # Make sure ' tf ' and '... |
def handle_profile_save ( self , sender , instance , ** kwargs ) :
"""Custom handler for user profile save""" | self . handle_save ( instance . user . __class__ , instance . user ) |
def create_manager ( self , instance , superclass ) :
"""Dynamically create a RelatedManager to handle the back side of the ( G ) FK""" | rel_model = self . rating_model
rated_model = self . rated_model
class RelatedManager ( superclass ) :
def get_query_set ( self ) :
qs = RatingsQuerySet ( rel_model , rated_model = rated_model )
return qs . filter ( ** ( self . core_filters ) )
def add ( self , * objs ) :
lookup_kwargs =... |
def get_query_uri ( self ) :
"""Return the uri used for queries on time series data .""" | # Query URI has extra path we don ' t want so strip it off here
query_uri = self . service . settings . data [ 'query' ] [ 'uri' ]
query_uri = urlparse ( query_uri )
return query_uri . scheme + '://' + query_uri . netloc |
def item ( self ) :
"""ToDo
> > > from hydpy . core . examples import prepare _ full _ example _ 1
> > > prepare _ full _ example _ 1 ( )
> > > from hydpy import HydPy , TestIO , XMLInterface , pub
> > > hp = HydPy ( ' LahnH ' )
> > > pub . timegrids = ' 1996-01-01 ' , ' 1996-01-06 ' , ' 1d '
> > > with... | target = f'{self.master.name}.{self.name}'
if self . master . name == 'nodes' :
master = self . master . name
itemgroup = self . master . master . name
else :
master = self . master . master . name
itemgroup = self . master . master . master . name
itemclass = _ITEMGROUP2ITEMCLASS [ itemgroup ]
if itemg... |
def cmd_fft ( args ) :
'''display fft from log''' | from MAVProxy . modules . lib import mav_fft
if len ( args ) > 0 :
condition = args [ 0 ]
else :
condition = None
child = multiproc . Process ( target = mav_fft . mavfft_display , args = [ mestate . filename , condition ] )
child . start ( ) |
def sample_radius ( self , n ) :
"""Sample the radial distribution ( deg ) from the 2D stellar density .
Output is elliptical radius in true projected coordinates .""" | edge = self . edge if self . edge < 20 * self . extension else 20 * self . extension
radius = np . linspace ( 0 , edge , 1.e5 )
pdf = self . _pdf ( radius ) * np . sin ( np . radians ( radius ) )
cdf = np . cumsum ( pdf )
cdf /= cdf [ - 1 ]
fn = scipy . interpolate . interp1d ( cdf , list ( range ( 0 , len ( cdf ) ) ) ... |
def _symbol_extract ( self , regex , plus = True , brackets = False ) :
"""Extracts a symbol or full symbol from the current line ,
optionally including the character under the cursor .
: arg regex : the compiled regular expression to use for extraction .
: arg plus : when true , the character under the curso... | charplus = self . pos [ 1 ] + ( 1 if plus else - 1 )
consider = self . current_line [ : charplus ] [ : : - 1 ]
# We want to remove matching pairs of brackets so that derived types
# that have arrays still get intellisense .
if brackets == True : # The string has already been reversed , just run through it .
rightb ... |
def read_dict ( self , dictionary , source = '<dict>' ) :
"""Read configuration from a dictionary .
Keys are section names , values are dictionaries with keys and values
that should be present in the section . If the used dictionary type
preserves order , sections and their keys will be added in order .
All... | elements_added = set ( )
for section , keys in dictionary . items ( ) :
section = str ( section )
try :
self . add_section ( section )
except ( DuplicateSectionError , ValueError ) :
if self . _strict and section in elements_added :
raise
elements_added . add ( section )
... |
def predict_proba ( self , X ) :
"""Probability estimates .
The returned estimates for all classes are ordered by the
label of classes .
Parameters
X : List of ndarrays , one for each training example .
Each training example ' s shape is ( string1 _ len , string2 _ len , n _ features , where
string1 _ l... | parameters = np . ascontiguousarray ( self . parameters . T )
predictions = [ _Model ( self . _state_machine , x ) . predict ( parameters , self . viterbi ) for x in X ]
predictions = np . array ( [ [ probability for _ , probability in sorted ( prediction . items ( ) ) ] for prediction in predictions ] )
return predict... |
def _merge_includes ( self ) :
"""If " include " option exists in " default . cfg " ,
read the file ( glob - match ) in the directory .""" | raw_include_path = self . get_global_include ( )
if raw_include_path :
abs_include_path = self . _get_global_include_abs_path ( raw_include_path )
self . _validate_global_include ( abs_include_path )
self . set_global_include ( abs_include_path )
for infile in glob . glob ( abs_include_path ) :
... |
def _set_replicator ( self , v , load = False ) :
"""Setter method for replicator , mapped from YANG variable / tunnel _ settings / system / tunnel / replicator ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ replicator is considered as a private
method ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = replicator . replicator , is_container = 'container' , presence = False , yang_name = "replicator" , rest_name = "replicator" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_pa... |
def project_tags ( self ) :
"""List all git tags made to the project .
: return :""" | request_url = "{}git/tags" . format ( self . create_basic_url ( ) )
return_value = self . _call_api ( request_url )
return return_value [ 'tags' ] |
def upper ( self ) :
"""Returns this query with the Upper function added to its list .
: return < Query >""" | q = self . copy ( )
q . addFunction ( Query . Function . Upper )
return q |
def selection ( self ) :
"""A complete | Selection | object of all " supplying " and " routing "
elements and required nodes .
> > > from hydpy import RiverBasinNumbers2Selection
> > > rbns2s = RiverBasinNumbers2Selection (
. . . ( 111 , 113 , 1129 , 11269 , 1125 , 11261,
. . . 11262 , 1123 , 1124 , 1122 ... | return selectiontools . Selection ( self . selection_name , self . nodes , self . elements ) |
def setCompactProtocol ( self ) :
"""Set the compact protocol .""" | self . _compact = True
self . _serial . write ( bytes ( self . _BAUD_DETECT ) )
self . _log and self . _log . debug ( "Compact protocol has been set." ) |
def simplify ( self ) :
"""Simplify the Expr .""" | d = defaultdict ( float )
for term in self . terms :
term = term . simplify ( )
d [ term . ops ] += term . coeff
return Expr . from_terms_iter ( Term . from_ops_iter ( k , d [ k ] ) for k in sorted ( d , key = repr ) if d [ k ] ) |
def decode_cli_arg ( arg ) :
"""Turn a bytestring provided by ` argparse ` into unicode .
: param arg : The bytestring to decode .
: return : The argument as a unicode object .
: raises ValueError : If arg is None .""" | if arg is None :
raise ValueError ( 'Argument cannot be None' )
if sys . version_info . major == 3 : # already decoded
return arg
return arg . decode ( sys . getfilesystemencoding ( ) ) |
def to_range_strings ( seglist ) :
"""Turn a segment list into a list of range strings as could be parsed
by from _ range _ strings ( ) . A typical use for this function is in
machine - generating configuration files or command lines for other
programs .
Example :
> > > from pycbc _ glue . segments import... | # preallocate the string list
ranges = [ None ] * len ( seglist )
# iterate over segments
for i , seg in enumerate ( seglist ) :
if not seg :
ranges [ i ] = str ( seg [ 0 ] )
elif ( seg [ 0 ] is segments . NegInfinity ) and ( seg [ 1 ] is segments . PosInfinity ) :
ranges [ i ] = ":"
elif ( ... |
def _compute_probabilities ( miner_data , wait_blocks , sample_size ) :
"""Computes the probabilities that a txn will be accepted at each of the gas
prices accepted by the miners .""" | miner_data_by_price = tuple ( sorted ( miner_data , key = operator . attrgetter ( 'low_percentile_gas_price' ) , reverse = True , ) )
for idx in range ( len ( miner_data_by_price ) ) :
low_percentile_gas_price = miner_data_by_price [ idx ] . low_percentile_gas_price
num_blocks_accepting_price = sum ( m . num_bl... |
def get_drop_index_sql ( self , index , table = None ) :
"""Returns the SQL to drop an index from a table .
: param index : The index
: type index : Index or str
: param table : The table
: type table : Table or str or None
: rtype : str""" | if isinstance ( index , Index ) :
index = index . get_quoted_name ( self )
return "DROP INDEX %s" % index |
def _from_rest_reject_update ( model ) :
"""Reject any field updates not allowed on POST
This is done on fields with ` reject _ update = True ` .""" | dirty = model . dirty_fields
fields = model . get_fields_by_prop ( 'reject_update' , True )
reject = [ ]
for field in fields :
if field in dirty :
reject . append ( field )
if reject :
mod_fail ( 'These fields cannot be updated: %s' % ', ' . join ( reject ) ) |
def div ( self , y ) :
r"""Compute the divergence of a signal defined on the edges .
The divergence : math : ` z ` of a signal : math : ` y ` is defined as
. . math : : z = \ operatorname { div } _ \ mathcal { G } y = D y ,
where : math : ` D ` is the differential operator : attr : ` D ` .
The value of the ... | y = np . asanyarray ( y )
if y . shape [ 0 ] != self . Ne :
raise ValueError ( 'First dimension must be the number of edges ' 'G.Ne = {}, got {}.' . format ( self . Ne , y . shape ) )
return self . D . dot ( y ) |
def get_id_from_cstring ( name ) :
"""Return variable type id given the C - storage name""" | for key in list ( LogTocElement . types . keys ( ) ) :
if ( LogTocElement . types [ key ] [ 0 ] == name ) :
return key
raise KeyError ( 'Type [%s] not found in LogTocElement.types!' % name ) |
def apply_flat ( self , config , namespace_separator = '_' , prefix = '' ) : # type : ( Dict [ str , Any ] , str , str ) - > None
"""Apply additional configuration from a flattened dictionary
This will look for dictionary items that match flattened keys from base _ config and apply their values on the
current c... | self . _init_flat_pointers ( )
for key_stack , ( container , orig_key ) in self . _flat_pointers . items ( ) :
flat_key = '{prefix}{joined_key}' . format ( prefix = prefix , joined_key = namespace_separator . join ( key_stack ) )
if flat_key in config :
container [ orig_key ] = config [ flat_key ] |
def record ( self , tags , measurement_map , timestamp , attachments = None ) :
"""records stats with a set of tags""" | assert all ( vv >= 0 for vv in measurement_map . values ( ) )
for measure , value in measurement_map . items ( ) :
if measure != self . _registered_measures . get ( measure . name ) :
return
view_datas = [ ]
for measure_name , view_data_list in self . _measure_to_view_data_list_map . items ( ) :
... |
def minizinc_version ( ) :
"""Returns the version of the found minizinc executable .""" | vs = _run_minizinc ( '--version' )
m = re . findall ( 'version ([\d\.]+)' , vs )
if not m :
raise RuntimeError ( 'MiniZinc executable not found.' )
return m [ 0 ] |
def read_pattern ( text_str , patterns , terminate_on_match = False , postprocess = str ) :
"""General pattern reading on an input string
Args :
text _ str ( str ) : the input string to search for patterns
patterns ( dict ) : A dict of patterns , e . g . ,
{ " energy " : r " energy \\ ( sigma - > 0 \\ ) \\ ... | compiled = { key : re . compile ( pattern , re . MULTILINE | re . DOTALL ) for key , pattern in patterns . items ( ) }
matches = defaultdict ( list )
for key , pattern in compiled . items ( ) :
for match in pattern . finditer ( text_str ) :
matches [ key ] . append ( [ postprocess ( i ) for i in match . gro... |
def __crawler_stop ( self ) :
"""Mark the crawler as stopped .
Note :
If : attr : ` _ _ stopped ` is True , the main thread will be stopped . Every piece of code that gets
executed after : attr : ` _ _ stopped ` is True could cause Thread exceptions and or race conditions .""" | if self . __stopping :
return
self . __stopping = True
self . __wait_for_current_threads ( )
self . queue . move_bulk ( [ QueueItem . STATUS_QUEUED , QueueItem . STATUS_IN_PROGRESS ] , QueueItem . STATUS_CANCELLED )
self . __crawler_finish ( )
self . __stopped = True |
def PushTask ( self , task ) :
"""Pushes a task onto the heap .
Args :
task ( Task ) : task .
Raises :
ValueError : if the size of the storage file is not set in the task .""" | storage_file_size = getattr ( task , 'storage_file_size' , None )
if not storage_file_size :
raise ValueError ( 'Task storage file size not set.' )
if task . file_entry_type == dfvfs_definitions . FILE_ENTRY_TYPE_DIRECTORY :
weight = 1
else :
weight = storage_file_size
task . merge_priority = weight
heap_va... |
def toXml ( cls , data , xparent = None ) :
"""Converts the inputted element to a Python object by looking through
the IO addons for the element ' s tag .
: param data | < variant >
xparent | < xml . etree . ElementTree . Element > | | None
: return < xml . etree . ElementTree . Element >""" | if data is None :
return None
# store XmlObjects separately from base types
if isinstance ( data , XmlObject ) :
name = 'object'
else :
name = type ( data ) . __name__
addon = cls . byName ( name )
if not addon :
raise RuntimeError ( '{0} is not a supported XML tag' . format ( name ) )
return addon . sa... |
def encrypt ( payload , public_key ) :
"""Encrypt a payload using an encrypted JSON wrapper .
See : https : / / diaspora . github . io / diaspora _ federation / federation / encryption . html
: param payload : Payload document as a string .
: param public _ key : Public key of recipient as an RSA object .
:... | iv , key , encrypter = EncryptedPayload . get_iv_key_encrypter ( )
aes_key_json = EncryptedPayload . get_aes_key_json ( iv , key )
cipher = PKCS1_v1_5 . new ( public_key )
aes_key = b64encode ( cipher . encrypt ( aes_key_json ) )
padded_payload = pkcs7_pad ( payload . encode ( "utf-8" ) , AES . block_size )
encrypted_m... |
def B4PB ( self ) :
'''判斷是否為四大買點''' | return self . ckMinsGLI and ( self . B1 or self . B2 or self . B3 or self . B4 ) |
def count ( self ) :
"""count : get number of nodes in tree
Args : None
Returns : int""" | total = len ( self . children )
for child in self . children :
total += child . count ( )
return total |
def _execute_task ( self , * , dependency , input_args , intermediate_results , monitor ) :
"""Executes a task of the workflow .
: param dependency : A workflow dependency
: type dependency : Dependency
: param input _ args : External task parameters .
: type input _ args : dict
: param intermediate _ res... | task = dependency . task
inputs = tuple ( intermediate_results [ self . uuid_dict [ input_task . private_task_config . uuid ] ] for input_task in dependency . inputs )
kw_inputs = input_args . get ( task , { } )
if isinstance ( kw_inputs , tuple ) :
inputs += kw_inputs
kw_inputs = { }
LOGGER . debug ( "Computin... |
def optimize_no ( self ) :
'''all options set to default''' | self . optimization = 0
self . relax = False
self . gc_sections = False
self . ffunction_sections = False
self . fdata_sections = False
self . fno_inline_small_functions = False |
def tag_details ( tag , nodenames ) :
"""Used in media and graphics to extract data from their parent tags""" | details = { }
details [ 'type' ] = tag . name
details [ 'ordinal' ] = tag_ordinal ( tag )
# Ordinal value
if tag_details_sibling_ordinal ( tag ) :
details [ 'sibling_ordinal' ] = tag_details_sibling_ordinal ( tag )
# Asset name
if tag_details_asset ( tag ) :
details [ 'asset' ] = tag_details_asset ( tag )
objec... |
def add_project ( self , ) :
"""Add a project and store it in the self . projects
: returns : None
: rtype : None
: raises : None""" | i = self . prj_tablev . currentIndex ( )
item = i . internalPointer ( )
if item :
project = item . internal_data ( )
if self . _atype :
self . _atype . projects . add ( project )
elif self . _dep :
self . _dep . projects . add ( project )
else :
project . users . add ( self . _us... |
def get_text ( self ) :
"""Get the text in its current state .""" | return u'' . join ( u'{0}' . format ( b ) for b in self . text ) |
def ordered ( start , edges , predicate = None , inverse = False ) :
"""Depth first edges from a SciGraph response .""" | s , o = 'sub' , 'obj'
if inverse :
s , o = o , s
for edge in edges :
if predicate is not None and edge [ 'pred' ] != predicate :
print ( 'scoop!' )
continue
if edge [ s ] == start :
yield edge
yield from Graph . ordered ( edge [ o ] , edges , predicate = predicate ) |
def build_scope ( resource , method ) :
"""Compute the name of the scope for oauth
: param Resource resource : the resource manager
: param str method : an http method
: return str : the name of the scope""" | if ResourceList in inspect . getmro ( resource ) and method == 'GET' :
prefix = 'list'
else :
method_to_prefix = { 'GET' : 'get' , 'POST' : 'create' , 'PATCH' : 'update' , 'DELETE' : 'delete' }
prefix = method_to_prefix [ method ]
if ResourceRelationship in inspect . getmro ( resource ) :
prefix... |
def _read_name ( self , bufr , idx , strings_offset ) :
"""Return a ( platform _ id , name _ id , name ) 3 - tuple like ( 0 , 1 , ' Arial ' )
for the name at * idx * position in * bufr * . * strings _ offset * is the
index into * bufr * where actual name strings begin . The returned name
is a unicode string .... | platform_id , encoding_id , lang_id , name_id , length , str_offset = ( self . _name_header ( bufr , idx ) )
name = self . _read_name_text ( bufr , platform_id , encoding_id , strings_offset , str_offset , length )
return platform_id , name_id , name |
def clearFixedEffect ( self ) :
"""erase all fixed effects""" | self . A = [ ]
self . F = [ ]
self . F_any = np . zeros ( ( self . N , 0 ) )
self . clear_cache ( ) |
def get_transaction_details ( tx_hash , coin_symbol = 'btc' , limit = None , tx_input_offset = None , tx_output_offset = None , include_hex = False , show_confidence = False , confidence_only = False , api_key = None ) :
"""Takes a tx _ hash , coin _ symbol , and limit and returns the transaction details
Optional... | assert is_valid_hash ( tx_hash ) , tx_hash
assert is_valid_coin_symbol ( coin_symbol ) , coin_symbol
added = 'txs/{}{}' . format ( tx_hash , '/confidence' if confidence_only else '' )
url = make_url ( coin_symbol , added )
params = { }
if api_key :
params [ 'token' ] = api_key
if limit :
params [ 'limit' ] = li... |
def _read_tags ( self ) :
"""Fill in the _ tags dict from the tags file .
Args :
None
Returns :
True
Todo :
Figure what could go wrong and at least acknowledge the
the fact that Murphy was an optimist .""" | tags = self . _config . get ( 'tags' , { } )
logging . info ( 'Tags:' )
for tag_name in tags . keys ( ) :
tag = { }
tag [ 'Key' ] = tag_name
tag [ 'Value' ] = tags [ tag_name ]
self . _tags . append ( tag )
logging . info ( '{} = {}' . format ( tag_name , tags [ tag_name ] ) )
logging . debug ( json... |
def geost_1d ( * args , ** kwargs ) : # ( lon , lat , nu ) : OR ( dst , nu )
"""; GEOST _ 1D : Compute geostrophic speeds from a sea level dataset < br / >
; Reference : Powell , B . S . , et R . R . Leben ( 2004 ) , An Optimal Filter for < br / >
; Geostrophic Mesoscale Currents from Along - Track Satellite Al... | lon = args [ 0 ]
lat = args [ 1 ]
dst = args [ 2 ] if len ( args ) == 4 else calcul_distance ( lat , lon ) * 1e3
# distance in meters
nu = args [ 3 ] if len ( args ) == 4 else args [ 2 ]
isVector = len ( np . shape ( nu ) ) == 1
# Reshape nu if vector
if isVector :
nu = np . reshape ( nu , ( len ( nu ) , 1 ) )
nt =... |
def make_image ( imagesize , voxval = 0 , spacing = None , origin = None , direction = None , has_components = False , pixeltype = 'float' ) :
"""Make an image with given size and voxel value or given a mask and vector
ANTsR function : ` makeImage `
Arguments
shape : tuple / ANTsImage
input image size or ma... | if isinstance ( imagesize , iio . ANTsImage ) :
img = imagesize . clone ( )
sel = imagesize > 0
if voxval . ndim > 1 :
voxval = voxval . flatten ( )
if ( len ( voxval ) == int ( ( sel > 0 ) . sum ( ) ) ) or ( len ( voxval ) == 0 ) :
img [ sel ] = voxval
else :
raise ValueErro... |
def DELETE_SLICE_0 ( self , instr ) :
'obj [ : ] = expr' | value = self . ast_stack . pop ( )
kw = dict ( lineno = instr . lineno , col_offset = 0 )
slice = _ast . Slice ( lower = None , step = None , upper = None , ** kw )
subscr = _ast . Subscript ( value = value , slice = slice , ctx = _ast . Del ( ) , ** kw )
delete = _ast . Delete ( targets = [ subscr ] , ** kw )
self . a... |
def on_created ( self , event ) :
"""Function called everytime a new file is created .
Args :
event : Event to process .""" | self . _logger . debug ( 'Detected create event on watched path: %s' , event . src_path )
self . _process_event ( event ) |
def effect_repertoire ( self , mechanism , purview ) :
"""Return the effect repertoire of a mechanism over a purview .
Args :
mechanism ( tuple [ int ] ) : The mechanism for which to calculate the
effect repertoire .
purview ( tuple [ int ] ) : The purview over which to calculate the
effect repertoire .
... | # If the purview is empty , the distribution is empty , so return the
# multiplicative identity .
if not purview :
return np . array ( [ 1.0 ] )
# Use a frozenset so the arguments to ` _ single _ node _ effect _ repertoire `
# can be hashed and cached .
mechanism = frozenset ( mechanism )
# Preallocate the repertoi... |
def write ( self , data , timeout_s = None ) :
'''Write to serial port .
Waits for serial connection to be established before writing .
Parameters
data : str or bytes
Data to write to serial port .
timeout _ s : float , optional
Maximum number of seconds to wait for serial connection to be
established... | self . connected . wait ( timeout_s )
self . protocol . transport . write ( data ) |
def sync ( ) :
'''Sync portage / overlay trees and update the eix database
CLI Example :
. . code - block : : bash
salt ' * ' eix . sync''' | # Funtoo patches eix to use ' ego sync '
if __grains__ [ 'os' ] == 'Funtoo' :
cmd = 'eix-sync -q'
else :
cmd = 'eix-sync -q -C "--ask" -C "n"'
if 'makeconf.features_contains' in __salt__ and __salt__ [ 'makeconf.features_contains' ] ( 'webrsync-gpg' ) : # GPG sign verify is supported only for " webrsync "
i... |
def writeTypes ( self , fd ) :
"""write out types module to file descriptor .""" | print >> fd , '#' * 50
print >> fd , '# file: %s.py' % self . getTypesModuleName ( )
print >> fd , '#'
print >> fd , '# schema types generated by "%s"' % self . __class__
print >> fd , '# %s' % ' ' . join ( sys . argv )
print >> fd , '#'
print >> fd , '#' * 50
print >> fd , TypesHeaderContainer ( )
self . gatherName... |
def change_text ( self , text , fname , pattern = None , expect = None , shutit_pexpect_child = None , before = False , force = False , delete = False , note = None , replace = False , line_oriented = True , create = True , loglevel = logging . DEBUG ) :
"""Change text in a file .
Returns None if there was no mat... | shutit_global . shutit_global_object . yield_to_draw ( )
shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child
expect = expect or self . get_current_shutit_pexpect_session ( ) . default_expect
shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( ... |
def postSolve ( self ) :
'''This method adds consumption at m = 0 to the list of stable arm points ,
then constructs the consumption function as a cubic interpolation over
those points . Should be run after the backshooting routine is complete .
Parameters
none
Returns
none''' | # Add bottom point to the stable arm points
self . solution [ 0 ] . mNrm_list . insert ( 0 , 0.0 )
self . solution [ 0 ] . cNrm_list . insert ( 0 , 0.0 )
self . solution [ 0 ] . MPC_list . insert ( 0 , self . MPCmax )
# Construct an interpolation of the consumption function from the stable arm points
self . solution [ ... |
def weighted_average_to_nodes ( x1 , x2 , data , interpolator ) :
"""Weighted average of scattered data to the nodal points
of a triangulation using the barycentric coordinates as
weightings .
Parameters
x1 , x2 : 1D arrays arrays of x , y or lon , lat ( radians )
data : 1D array of data to be lumped to t... | import numpy as np
gridded_data = np . zeros ( interpolator . npoints )
norm = np . zeros ( interpolator . npoints )
count = np . zeros ( interpolator . npoints , dtype = np . int )
bcc , nodes = interpolator . containing_simplex_and_bcc ( x1 , x2 )
# Beware vectorising the reduction operation ! !
for i in range ( 0 , ... |
def curse_add_line ( self , msg , decoration = "DEFAULT" , optional = False , additional = False , splittable = False ) :
"""Return a dict with .
Where :
msg : string
decoration :
DEFAULT : no decoration
UNDERLINE : underline
BOLD : bold
TITLE : for stat title
PROCESS : for process name
STATUS : f... | return { 'msg' : msg , 'decoration' : decoration , 'optional' : optional , 'additional' : additional , 'splittable' : splittable } |
def _compare_vector ( arr1 , arr2 , rel_tol ) :
"""Compares two vectors ( python lists ) for approximate equality .
Each array contains floats or strings convertible to floats
This function returns True if both arrays are of the same length
and each value is within the given relative tolerance .""" | length = len ( arr1 )
if len ( arr2 ) != length :
return False
for i in range ( length ) :
element_1 = float ( arr1 [ i ] )
element_2 = float ( arr2 [ i ] )
diff = abs ( abs ( element_1 ) - abs ( element_2 ) )
if diff != 0.0 :
rel = _reldiff ( element_1 , element_2 )
# For a basis se... |
def run_bootstrap_post_init ( self , config ) :
"""runs a script after initdb or custom bootstrap script is called and waits until completion .""" | cmd = config . get ( 'post_bootstrap' ) or config . get ( 'post_init' )
if cmd :
r = self . _local_connect_kwargs
if 'host' in r : # ' / tmp ' = > ' % 2Ftmp ' for unix socket path
host = quote_plus ( r [ 'host' ] ) if r [ 'host' ] . startswith ( '/' ) else r [ 'host' ]
else :
host = ''
... |
def json_engine ( self , req ) : # pylint : disable = R0201 , W0613
"""Return torrent engine data .""" | try :
return stats . engine_data ( config . engine )
except ( error . LoggableError , xmlrpc . ERRORS ) as torrent_exc :
raise exc . HTTPInternalServerError ( str ( torrent_exc ) ) |
def sub_working_days ( self , day , delta , extra_working_days = None , extra_holidays = None , keep_datetime = False ) :
"""Substract ` delta ` working days to the date .
This method is a shortcut / helper . Users may want to use either : :
cal . add _ working _ days ( my _ date , - 7)
cal . sub _ working _ ... | delta = abs ( delta )
return self . add_working_days ( day , - delta , extra_working_days , extra_holidays , keep_datetime = keep_datetime ) |
def get_queryset ( self , request ) :
"""Limit Pages to those that belong to the request ' s user .""" | qs = super ( VISAVariableAdmin , self ) . get_queryset ( request )
return qs . filter ( device__protocol_id = PROTOCOL_ID ) |
def _wrapper_find_one ( self , filter_ = None , * args , ** kwargs ) :
"""Convert record to a dict that has no key error""" | return self . __collect . find_one ( filter_ , * args , ** kwargs ) |
def _linear_predictor ( self , X = None , modelmat = None , b = None , term = - 1 ) :
"""linear predictor
compute the linear predictor portion of the model
ie multiply the model matrix by the spline basis coefficients
Parameters
at least 1 of ( X , modelmat )
and
at least 1 of ( b , feature )
X : arra... | if modelmat is None :
modelmat = self . _modelmat ( X , term = term )
if b is None :
b = self . coef_ [ self . terms . get_coef_indices ( term ) ]
return modelmat . dot ( b ) . flatten ( ) |
def newton ( self , start_x = None , tolerance = 1.0e-6 ) :
"""Optimise value of x using newton gauss""" | if start_x is None :
start_x = self . _analytical_fitter . fit ( self . _c )
return optimise_newton ( start_x , self . _a , self . _c , tolerance ) |
def write_data ( self , write_finished_cb ) :
"""Write trajectory data to the Crazyflie""" | self . _write_finished_cb = write_finished_cb
data = bytearray ( )
for poly4D in self . poly4Ds :
data += struct . pack ( '<ffffffff' , * poly4D . x . values )
data += struct . pack ( '<ffffffff' , * poly4D . y . values )
data += struct . pack ( '<ffffffff' , * poly4D . z . values )
data += struct . pac... |
def substitute ( script , submap ) :
"""Check for presence of template indicator and if found , perform
variable substition on script based on template type , returning
script .""" | match = config . TEMPLATE_RE . search ( script )
if match :
template_type = match . groupdict ( ) [ 'type' ]
try :
return config . TEMPLATE_TYPEMAP [ template_type ] ( script , submap )
except KeyError :
logger . error ( 'Unsupported template type: %s' % template_type )
raise
return ... |
def _check_html_response ( self , response ) :
"""Checks if the API Key is valid and if the request returned a 200 status ( ok )""" | error1 = "Access to this form requires a valid API key. For more info see: http://www.clublog.org/need_api.php"
error2 = "Invalid or missing API Key"
if response . status_code == requests . codes . ok :
return True
else :
err_str = "HTTP Status Code: " + str ( response . status_code ) + " HTTP Response: " + str... |
def authorize_redirect ( self , redirect_uri : str = None , client_id : str = None , client_secret : str = None , extra_params : Dict [ str , Any ] = None , scope : str = None , response_type : str = "code" , ) -> None :
"""Redirects the user to obtain OAuth authorization for this service .
Some providers require... | handler = cast ( RequestHandler , self )
args = { "response_type" : response_type }
if redirect_uri is not None :
args [ "redirect_uri" ] = redirect_uri
if client_id is not None :
args [ "client_id" ] = client_id
if extra_params :
args . update ( extra_params )
if scope :
args [ "scope" ] = " " . join (... |
def _callback_set_qs_value ( self , key , val , success ) :
"""Push state to QSUSB , retry with backoff .""" | set_url = URL_SET . format ( self . _url , key , val )
with self . _lock :
for _repeat in range ( 1 , 6 ) :
set_result = requests . get ( set_url )
if set_result . status_code == 200 :
set_result = set_result . json ( )
if set_result . get ( 'data' , 'NO REPLY' ) != 'NO REPLY... |
def returner ( load ) :
'''Return data to the local job cache''' | serial = salt . payload . Serial ( __opts__ )
# if a minion is returning a standalone job , get a jobid
if load [ 'jid' ] == 'req' :
load [ 'jid' ] = prep_jid ( nocache = load . get ( 'nocache' , False ) )
jid_dir = salt . utils . jid . jid_dir ( load [ 'jid' ] , _job_dir ( ) , __opts__ [ 'hash_type' ] )
if os . pa... |
def add ( self , doc ) :
"""Add a doc ' s annotations to the binder for serialization .""" | array = doc . to_array ( self . attrs )
if len ( array . shape ) == 1 :
array = array . reshape ( ( array . shape [ 0 ] , 1 ) )
self . tokens . append ( array )
spaces = doc . to_array ( SPACY )
assert array . shape [ 0 ] == spaces . shape [ 0 ]
spaces = spaces . reshape ( ( spaces . shape [ 0 ] , 1 ) )
self . spac... |
def build_model ( self ) :
'''Find out the type of model configured and dispatch the request to the appropriate method''' | if self . model_config [ 'model-type' ] :
return self . build_red ( )
elif self . model_config [ 'model-type' ] :
return self . buidl_hred ( )
else :
raise Error ( "Unrecognized model type '{}'" . format ( self . model_config [ 'model-type' ] ) ) |
def readGyroRange ( self ) :
"""Read range of gyroscope .
@ return an int value . It should be one of the following values ( GYRO _ RANGE _ 250DEG )
@ see GYRO _ RANGE _ 250DEG
@ see GYRO _ RANGE _ 500DEG
@ see GYRO _ RANGE _ 1KDEG
@ see GYRO _ RANGE _ 2KDEG""" | raw_data = self . _readByte ( self . REG_GYRO_CONFIG )
raw_data = ( raw_data | 0xE7 ) ^ 0xE7
return raw_data |
def sent_tokenize ( context ) :
"""Cut the given context into sentences .
Avoid a linebreak in between paried symbols , float numbers , and some abbrs .
Nothing will be discard after sent _ tokeinze , simply ' ' . join ( sents ) will get the original context .
Evey whitespace , tab , linebreak will be kept . ... | # Define the regular expression
paired_symbols = [ ( "(" , ")" ) , ( "[" , "]" ) , ( "{" , "}" ) ]
paired_patterns = [ "%s.*?%s" % ( re . escape ( lt ) , re . escape ( rt ) ) for lt , rt in paired_symbols ]
number_pattern = [ '\d+\.\d+' ]
arr_pattern = [ '(?: \w\.){2,3}|(?:\A|\s)(?:\w\.){2,3}|[A-Z]\. [a-z]|\svs\. |et a... |
def ext_process ( listname , hostname , url , filepath , msg ) :
"""Here ' s where you put your code to deal with the just archived message .
Arguments here are the list name , the host name , the URL to the just
archived message , the file system path to the just archived message and
the message object .
T... | from pyes import ES
from pyes . exceptions import ClusterBlockException , NoServerAvailable
import datetime
# CHANGE this settings to reflect your configuration
_ES_SERVERS = [ '127.0.0.1:9500' ]
# I prefer thrift
_indexname = "mailman"
_doctype = "mail"
date = datetime . datetime . today ( )
try :
iconn = ES ( _ES... |
def plot_CI ( ax , sampler , modelidx = 0 , sed = True , confs = [ 3 , 1 , 0.5 ] , e_unit = u . eV , label = None , e_range = None , e_npoints = 100 , threads = None , last_step = False , ) :
"""Plot confidence interval .
Parameters
ax : ` matplotlib . Axes `
Axes to plot on .
sampler : ` emcee . EnsembleSa... | confs . sort ( reverse = True )
modelx , CI = _calc_CI ( sampler , modelidx = modelidx , confs = confs , e_range = e_range , e_npoints = e_npoints , last_step = last_step , threads = threads , )
# pick first confidence interval curve for units
f_unit , sedf = sed_conversion ( modelx , CI [ 0 ] [ 0 ] . unit , sed )
for ... |
def _message_address_generate ( self , beacon_config ) :
"""Generate address for request / response message .
: param beacon _ config : server or client configuration . Client configuration is used for request and server configuration for response
: return : bytes""" | address = None
if beacon_config [ 'wasp-general::network::beacon' ] [ 'public_address' ] != '' :
address = str ( WIPV4SocketInfo . parse_address ( beacon_config [ 'wasp-general::network::beacon' ] [ 'public_address' ] ) ) . encode ( 'ascii' )
if address is not None :
address = WBeaconGouverneurMessenger . __mes... |
def do_execute ( self ) :
"""The actual execution of the actor .
: return : None if successful , otherwise error message
: rtype : str""" | for s in self . resolve_option ( "strings" ) :
self . _output . append ( Token ( s ) )
return None |
def angular_crossmatch_against_catalogue ( self , objectList , searchPara = { } , search_name = "" , brightnessFilter = False , physicalSearch = False , classificationType = False ) :
"""* perform an angular separation crossmatch against a given catalogue in the database and annotate the crossmatch with some value ... | self . log . debug ( 'starting the ``angular_crossmatch_against_catalogue`` method' )
self . log . info ( "STARTING %s SEARCH" % ( search_name , ) )
start_time = time . time ( )
# DEFAULTS
# print search _ name , classificationType
magnitudeLimitFilter = None
upperMagnitudeLimit = False
lowerMagnitudeLimit = False
cata... |
def pack ( header , s ) :
"""Pack a string into MXImageRecord .
Parameters
header : IRHeader
Header of the image record .
` ` header . label ` ` can be a number or an array . See more detail in ` ` IRHeader ` ` .
s : str
Raw image string to be packed .
Returns
s : str
The packed string .
Example... | header = IRHeader ( * header )
if isinstance ( header . label , numbers . Number ) :
header = header . _replace ( flag = 0 )
else :
label = np . asarray ( header . label , dtype = np . float32 )
header = header . _replace ( flag = label . size , label = 0 )
s = label . tostring ( ) + s
s = struct . pack... |
def do_print ( self , url_data ) :
"""Determine if URL entry should be logged or not .""" | if self . verbose :
return True
if self . warnings and url_data . warnings :
return True
return not url_data . valid |
def onEnable ( self ) :
"""The configuration containing this function has been enabled by host .
Endpoints become working files , so submit some read operations .""" | trace ( 'onEnable' )
self . _disable ( )
self . _aio_context . submit ( self . _aio_recv_block_list )
self . _real_onCanSend ( )
self . _enabled = True |
def calculate_dimensions ( image_size , desired_size ) :
"""Return the Tuple with the arguments to pass to Image . crop .
If the image is smaller than than the desired _ size Don ' t do
anything . Otherwise , first calculate the ( truncated ) center and then
take half the width and height ( truncated again ) ... | current_x , current_y = image_size
target_x , target_y = desired_size
if current_x < target_x and current_y < target_y :
return None
if current_x > target_x :
new_x0 = floor ( current_x / 2 )
new_x = new_x0 - ceil ( target_x / 2 )
new_width = target_x
else :
new_x = 0
new_width = current_x
if cu... |
def run_command ( cmd , out , ignore_errors = False ) :
"""We want to both send subprocess output to stdout or another file
descriptor as the subprocess runs , * and * capture the actual exception
message on errors . CalledProcessErrors do not reliably contain the
underlying exception in either the ' message ... | tempdir = tempfile . mkdtemp ( )
output_file = os . path . join ( tempdir , "stderr" )
original_cmd = " " . join ( cmd )
p = subprocess . Popen ( cmd , stdout = out , stderr = subprocess . PIPE )
t = subprocess . Popen ( [ "tee" , output_file ] , stdin = p . stderr , stdout = out )
t . wait ( )
p . communicate ( )
p . ... |
def create_vip ( self , vip_request_ids ) :
"""Method to create vip request
param vip _ request _ ids : vip _ request ids""" | uri = 'api/v3/vip-request/deploy/%s/' % vip_request_ids
return super ( ApiVipRequest , self ) . post ( uri ) |
def sameState ( s1 , s2 ) :
"""sameState ( s1 , s2)
Note :
state : = [ nfaclosure : Long , [ arc ] , accept : Boolean ]
arc : = [ label , arrow : Int , nfaClosure : Long ]""" | if ( len ( s1 [ 1 ] ) != len ( s2 [ 1 ] ) ) or ( s1 [ 2 ] != s2 [ 2 ] ) :
return False
for arcIndex in range ( 0 , len ( s1 [ 1 ] ) ) :
arc1 = s1 [ 1 ] [ arcIndex ]
arc2 = s2 [ 1 ] [ arcIndex ]
if arc1 [ : - 1 ] != arc2 [ : - 1 ] :
return False
return True |
def checked ( self , value ) :
"""Setter for * * self . _ _ checked * * attribute .
: param value : Attribute value .
: type value : bool""" | if value is not None :
assert type ( value ) is bool , "'{0}' attribute: '{1}' type is not 'bool'!" . format ( "checked" , value )
self . set_checked ( value ) |
def _traverse_dict ( self , input_dict , resolution_data , resolver_method ) :
"""Traverse a dictionary to resolve intrinsic functions on every value
: param input _ dict : Input dictionary to traverse
: param resolution _ data : Data that the ` resolver _ method ` needs to operate
: param resolver _ method :... | for key , value in input_dict . items ( ) :
input_dict [ key ] = self . _traverse ( value , resolution_data , resolver_method )
return input_dict |
def get_send_command ( self , send ) :
"""Internal helper function to get command that ' s really sent""" | shutit_global . shutit_global_object . yield_to_draw ( )
if send is None :
return send
cmd_arr = send . split ( )
if cmd_arr and cmd_arr [ 0 ] in ( 'md5sum' , 'sed' , 'head' ) :
newcmd = self . get_command ( cmd_arr [ 0 ] )
send = send . replace ( cmd_arr [ 0 ] , newcmd )
return send |
def gstd ( data , channels = None ) :
"""Calculate the geometric std . dev . of the events in an FCSData object .
Parameters
data : FCSData or numpy array
NxD flow cytometry data where N is the number of events and D is
the number of parameters ( aka channels ) .
channels : int or str or list of int or li... | # Slice data to take statistics from
if channels is None :
data_stats = data
else :
data_stats = data [ : , channels ]
# Calculate and return statistic
return np . exp ( np . std ( np . log ( data_stats ) , axis = 0 ) ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.