signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_formats ( self , id , ** data ) :
"""GET / formats / : id /
Gets a : format : ` format ` by ID as ` ` format ` ` .""" | return self . get ( "/formats/{0}/" . format ( id ) , data = data ) |
def run ( self ) :
"""! @ brief SWV reader thread routine .
Starts the probe receiving SWO data by calling DebugProbe . swo _ start ( ) . For as long as the
thread runs , it reads SWO data from the probe and passes it to the SWO parser created in
init ( ) . When the thread is signaled to stop , it calls Debug... | # Stop SWO first in case the probe already had it started . Ignore if this fails .
try :
self . _session . probe . swo_stop ( )
except exceptions . ProbeError :
pass
self . _session . probe . swo_start ( self . _swo_clock )
while not self . _shutdown_event . is_set ( ) :
data = self . _session . probe . swo... |
def execute ( self , eopatch ) :
"""Execute computation of local binary patterns on input eopatch
: param eopatch : Input eopatch
: type eopatch : eolearn . core . EOPatch
: return : EOPatch instance with new key holding the LBP image .
: rtype : eolearn . core . EOPatch""" | for feature_type , feature_name , new_feature_name in self . feature :
eopatch [ feature_type ] [ new_feature_name ] = self . _compute_lbp ( eopatch [ feature_type ] [ feature_name ] )
return eopatch |
def xpnsl ( h1 , h2 , use_threads = True ) :
"""Cross - population version of the NSL statistic .
Parameters
h1 : array _ like , int , shape ( n _ variants , n _ haplotypes )
Haplotype array for the first population .
h2 : array _ like , int , shape ( n _ variants , n _ haplotypes )
Haplotype array for th... | # check inputs
h1 = asarray_ndim ( h1 , 2 )
check_integer_dtype ( h1 )
h2 = asarray_ndim ( h2 , 2 )
check_integer_dtype ( h2 )
check_dim0_aligned ( h1 , h2 )
h1 = memoryview_safe ( h1 )
h2 = memoryview_safe ( h2 )
if use_threads and multiprocessing . cpu_count ( ) > 1 : # use multiple threads
# setup threadpool
poo... |
def set_xticklabels_position ( self , row , column , position ) :
"""Specify the position of the axis tick labels .
This is generally only useful for multiplots containing only one
row . This can be used to e . g . alternatively draw the tick labels
on the bottom or the top of the subplot .
: param row , co... | subplot = self . get_subplot_at ( row , column )
subplot . set_xticklabels_position ( position ) |
def user_topic_ids ( user ) :
"""Retrieve the list of topics IDs a user has access to .""" | if user . is_super_admin ( ) or user . is_read_only_user ( ) :
query = sql . select ( [ models . TOPICS ] )
else :
query = ( sql . select ( [ models . JOINS_TOPICS_TEAMS . c . topic_id ] ) . select_from ( models . JOINS_TOPICS_TEAMS . join ( models . TOPICS , sql . and_ ( models . JOINS_TOPICS_TEAMS . c . topic... |
def after ( self , i , sibling , name = None ) :
"""Adds siblings after the current tag .""" | self . parent . _insert ( sibling , idx = self . _own_index + 1 + i , name = name )
return self |
def get_pages ( self , url , page = 1 , page_size = 100 , yield_pages = False , ** filters ) :
"""Get all pages at url , yielding individual results
: param url : the url to fetch
: param page : start from this page
: param page _ size : results per page
: param yield _ pages : yield whole pages rather than... | n = 0
for page in itertools . count ( page ) :
r = self . request ( url , page = page , page_size = page_size , ** filters )
n += len ( r [ 'results' ] )
log . debug ( "Got {url} page {page} / {pages}" . format ( url = url , ** r ) )
if yield_pages :
yield r
else :
for row in r [ 're... |
def set_variant ( self , identity , experiment_name , variant_name ) :
"""Set the variant for a specific user .
: param identity a unique user identifier
: param experiment _ name the string name of the experiment
: param variant _ name the string name of the variant""" | try :
experiment = model . Experiment . get_by ( name = experiment_name )
variant = model . Variant . get_by ( name = variant_name )
if experiment and variant and model . Participant . query . filter ( and_ ( model . Participant . identity == identity , model . Participant . experiment_id == experiment . id... |
async def cancel ( self ) :
"""Coroutine to cancel this request / stream .
Client will send RST _ STREAM frame to the server , so it will be
explicitly informed that there is nothing to expect from the client
regarding this request / stream .""" | if self . _cancel_done :
raise ProtocolError ( 'Stream was already cancelled' )
with self . _wrapper :
await self . _stream . reset ( )
# TODO : specify error code
self . _cancel_done = True |
def from_dict ( cls , data ) :
"""Create a new Measurement subclass instance using the given dict .
If Measurement . name _ from _ class was previously called with this data ' s
associated Measurement sub - class in Python , the returned object will be
an instance of that sub - class . If the measurement name... | args = [ ]
if 'id' in data and 'data' in data :
measurement_class = CanMessage
args . append ( "Bus %s: 0x%x" % ( data . get ( 'bus' , '?' ) , data [ 'id' ] ) )
args . append ( data [ 'data' ] )
# TODO grab bus
else :
measurement_class = cls . _class_from_name ( data [ 'name' ] )
if measurement_... |
def check_mem_usage ( soft_percent = None , hard_percent = None ) :
"""Display a warning if we are running out of memory""" | soft_percent = soft_percent or config . memory . soft_mem_limit
hard_percent = hard_percent or config . memory . hard_mem_limit
used_mem_percent = psutil . virtual_memory ( ) . percent
if used_mem_percent > hard_percent :
raise MemoryError ( 'Using more memory than allowed by configuration ' '(Used: %d%% / Allowed:... |
def get ( cls ) :
"""Get the current API key .
if one has not been given via ' set ' the env var STEAMODD _ API _ KEY will
be checked instead .""" | apikey = cls . __api_key or cls . __api_key_env_var
if apikey :
return apikey
else :
raise APIKeyMissingError ( "API key not set" ) |
def sam_conversions ( self , sam_file , depth = True ) :
"""Convert sam files to bam files , then sort and index them for later use .
: param bool depth : also calculate coverage over each position""" | cmd = self . tools . samtools + " view -bS " + sam_file + " > " + sam_file . replace ( ".sam" , ".bam" ) + "\n"
cmd += self . tools . samtools + " sort " + sam_file . replace ( ".sam" , ".bam" ) + " -o " + sam_file . replace ( ".sam" , "_sorted.bam" ) + "\n"
cmd += self . tools . samtools + " index " + sam_file . repla... |
def rpm_send ( self , rpm1 , rpm2 , force_mavlink1 = False ) :
'''RPM sensor output
rpm1 : RPM Sensor1 ( float )
rpm2 : RPM Sensor2 ( float )''' | return self . send ( self . rpm_encode ( rpm1 , rpm2 ) , force_mavlink1 = force_mavlink1 ) |
def calc_bounds ( xy , entity ) :
"""For an entity with width and height attributes , determine
the bounding box if were positioned at ` ` ( x , y ) ` ` .""" | left , top = xy
right , bottom = left + entity . width , top + entity . height
return [ left , top , right , bottom ] |
def path_manager_callback ( self ) :
"""Spyder path manager""" | from spyder . widgets . pathmanager import PathManager
self . remove_path_from_sys_path ( )
project_path = self . projects . get_pythonpath ( )
dialog = PathManager ( self , self . path , project_path , self . not_active_path , sync = True )
dialog . redirect_stdio . connect ( self . redirect_internalshell_stdio )
dial... |
def roundrobin ( * iterables ) :
"""roundrobin ( ' ABC ' , ' D ' , ' EF ' ) - - > A D E B F C""" | raise NotImplementedError ( 'not sure if this implementation is correct' )
# http : / / stackoverflow . com / questions / 11125212 / interleaving - lists - in - python
# sentinel = object ( )
# return ( x for x in chain ( * zip _ longest ( fillvalue = sentinel , * iterables ) ) if x is not sentinel )
pending = len ( it... |
def get_logged_in_account ( token_manager = None , app_url = defaults . APP_URL ) :
"""get the account details for logged in account of the auth token _ manager""" | return get_logged_in_account ( token_manager = token_manager , app_url = app_url ) [ 'id' ] |
def resizeEvent ( self , event ) :
"""Updates the position of the additional buttons when this widget \
resizes .
: param event | < QResizeEvet >""" | super ( XTabBar , self ) . resizeEvent ( event )
self . resized . emit ( ) |
def apply_signature ( cls , instance , async = True , countdown = None , is_heavy_task = False , ** kwargs ) :
"""Serialize input data and apply signature""" | serialized_instance = utils . serialize_instance ( instance )
signature = cls . get_task_signature ( instance , serialized_instance , ** kwargs )
link = cls . get_success_signature ( instance , serialized_instance , ** kwargs )
link_error = cls . get_failure_signature ( instance , serialized_instance , ** kwargs )
if a... |
def initialize_plot ( self , data = None , ax = None , make_plot = True , clear = False , draw = False , remove = False , priority = None ) :
"""Initialize the plot for a data array
Parameters
data : InteractiveArray or ArrayList , optional
Data object that shall be visualized .
- If not None and ` plot ` i... | if data is None and self . data is not None :
data = self . data
else :
self . data = data
self . ax = ax
if data is None : # nothing to do if no data is given
return
self . no_auto_update = not ( not self . no_auto_update or not data . psy . no_auto_update )
data . psy . plotter = self
if not make_plot : #... |
def eidos_process_jsonld ( ) :
"""Process an EIDOS JSON - LD and return INDRA Statements .""" | if request . method == 'OPTIONS' :
return { }
response = request . body . read ( ) . decode ( 'utf-8' )
body = json . loads ( response )
eidos_json = body . get ( 'jsonld' )
ep = eidos . process_json_str ( eidos_json )
return _stmts_from_proc ( ep ) |
def better ( old_value , new_value , mode ) :
"""Check if new value is better than the old value""" | if ( old_value is None or np . isnan ( old_value ) ) and ( new_value is not None and not np . isnan ( new_value ) ) :
return True
if mode == 'min' :
return new_value < old_value
elif mode == 'max' :
return new_value > old_value
else :
raise RuntimeError ( f"Mode '{mode}' value is not supported" ) |
def populate_extra_files ( ) :
"""Creates a list of non - python data files to include in package distribution""" | out = [ 'cauldron/settings.json' ]
for entry in glob . iglob ( 'cauldron/resources/examples/**/*' , recursive = True ) :
out . append ( entry )
for entry in glob . iglob ( 'cauldron/resources/templates/**/*' , recursive = True ) :
out . append ( entry )
for entry in glob . iglob ( 'cauldron/resources/web/**/*' ... |
def parse_assertion ( self , keys = None ) :
"""Parse the assertions for a saml response .
: param keys : A string representing a RSA key or a list of strings
containing RSA keys .
: return : True if the assertions are parsed otherwise False .""" | if self . context == "AuthnQuery" : # can contain one or more assertions
pass
else : # This is a saml2int limitation
try :
assert ( len ( self . response . assertion ) == 1 or len ( self . response . encrypted_assertion ) == 1 or self . assertion is not None )
except AssertionError :
raise E... |
def make_requester ( self , my_args = None ) :
"""make a new requester instance and handle it from driver
: param my _ args : dict like { request _ q } . Default : None
: return : created requester proxy""" | LOGGER . debug ( "natsd.Driver.make_requester" )
if my_args is None :
raise exceptions . ArianeConfError ( 'requester factory arguments' )
if not self . configuration_OK or self . connection_args is None :
raise exceptions . ArianeConfError ( 'NATS connection arguments' )
requester = Requester . start ( my_args... |
def unregister_a_problem ( self , prob ) :
"""Remove the problem from our problems list
and check if we are still ' impacted '
: param prob : problem to remove
: type prob : alignak . objects . schedulingitem . SchedulingItem
: return : None""" | self . source_problems . remove ( prob . uuid )
# For know if we are still an impact , maybe our dependencies
# are not aware of the remove of the impact state because it ' s not ordered
# so we can just look at if we still have some problem in our list
if not self . source_problems :
self . is_impact = False
#... |
def _update_with_calls ( result_file , cnv_file ) :
"""Update bounds with calls from CNVkit , inferred copy numbers and p - values from THetA .""" | results = { }
with open ( result_file ) as in_handle :
in_handle . readline ( )
# header
_ , _ , cs , ps = in_handle . readline ( ) . strip ( ) . split ( )
for i , ( c , p ) in enumerate ( zip ( cs . split ( ":" ) , ps . split ( "," ) ) ) :
results [ i ] = ( c , p )
cnvs = { }
with open ( cnv_fi... |
def AND ( classical_reg1 , classical_reg2 ) :
"""Produce an AND instruction .
NOTE : The order of operands was reversed in pyQuil < = 1.9 .
: param classical _ reg1 : The first classical register , which gets modified .
: param classical _ reg2 : The second classical register or immediate value .
: return :... | left , right = unpack_reg_val_pair ( classical_reg1 , classical_reg2 )
return ClassicalAnd ( left , right ) |
def move_to_element ( self , to_element ) :
"""Moving the mouse to the middle of an element .
: Args :
- to _ element : The WebElement to move to .""" | if self . _driver . w3c :
self . w3c_actions . pointer_action . move_to ( to_element )
self . w3c_actions . key_action . pause ( )
else :
self . _actions . append ( lambda : self . _driver . execute ( Command . MOVE_TO , { 'element' : to_element . id } ) )
return self |
def _free_array ( self , handle : int ) :
"""Frees the memory for the array with the given handle .
Args :
handle : The handle of the array whose memory should be freed . This
handle must come from the _ create _ array method .""" | with self . _lock :
if self . _arrays [ handle ] is not None :
self . _arrays [ handle ] = None
self . _count -= 1 |
def _fast_write ( self , outfile , value ) :
"""Function for fast writing to motor files .""" | outfile . truncate ( 0 )
outfile . write ( str ( int ( value ) ) )
outfile . flush ( ) |
def pushd ( directory : str ) -> None :
"""Context manager : changes directory and preserves the original on exit .
Example :
. . code - block : : python
with pushd ( new _ directory ) :
# do things""" | previous_dir = os . getcwd ( )
os . chdir ( directory )
yield
os . chdir ( previous_dir ) |
def pre_freeze_hook ( self ) :
"""Pre : meth : ` dtoolcore . ProtoDataSet . freeze ` actions .
This method is called at the beginning of the
: meth : ` dtoolcore . ProtoDataSet . freeze ` method .
It may be useful for remote storage backends to generate
caches to remove repetitive time consuming calls""" | allowed = set ( [ v [ 0 ] for v in _STRUCTURE_PARAMETERS . values ( ) ] )
for d in os . listdir ( self . _abspath ) :
if d not in allowed :
msg = "Rogue content in base of dataset: {}" . format ( d )
raise ( DiskStorageBrokerValidationWarning ( msg ) ) |
def printed_out ( self , name ) :
"""Create a string describing the APIObject and its children""" | out = ''
out += '|\n'
if self . _id_variable :
subs = '[{}]' . format ( self . _id_variable )
else :
subs = ''
out += '|---{}{}\n' . format ( name , subs )
if self . _description :
out += '| | {}\n' . format ( self . _description )
for name , action in self . _actions . items ( ) :
out += action . p... |
def push ( self , vs ) :
'Move given sheet ` vs ` to index 0 of list ` sheets ` .' | if vs :
vs . vd = self
if vs in self . sheets :
self . sheets . remove ( vs )
self . sheets . insert ( 0 , vs )
elif not vs . loaded :
self . sheets . insert ( 0 , vs )
vs . reload ( )
vs . recalc ( )
# set up Columns
else :
self . sheets . insert ... |
def find_geom ( geom , geoms ) :
"""Returns the index of a geometry in a list of geometries avoiding
expensive equality checks of ` in ` operator .""" | for i , g in enumerate ( geoms ) :
if g is geom :
return i |
def signalMinimum ( img , fitParams = None , n_std = 3 ) :
'''intersection between signal and background peak''' | if fitParams is None :
fitParams = FitHistogramPeaks ( img ) . fitParams
assert len ( fitParams ) > 1 , 'need 2 peaks so get minimum signal'
i = signalPeakIndex ( fitParams )
signal = fitParams [ i ]
bg = getBackgroundPeak ( fitParams )
smn = signal [ 1 ] - n_std * signal [ 2 ]
bmx = bg [ 1 ] + n_std * bg [ 2 ]
if ... |
def handle_single_request ( self , request_object ) :
"""Handles a single request object and returns the raw response
: param request _ object :""" | if not isinstance ( request_object , ( MethodCall , Notification ) ) :
raise TypeError ( "Invalid type for request_object" )
method_name = request_object . method_name
params = request_object . params
req_id = request_object . id
request_body = self . build_request_body ( method_name , params , id = req_id )
http_r... |
def indexByComponent ( self , component ) :
"""Returns a location for the given component , or None if
it is not in the model
: param component : Component to get index for
: type component : : class : ` AbstractStimulusComponent < sparkle . stim . abstract _ component . AbstractStimulusComponent > `
: retu... | for row , rowcontents in enumerate ( self . _segments ) :
if component in rowcontents :
column = rowcontents . index ( component )
return ( row , column ) |
def get_last_depth ( self , symbol , _type ) :
"""获取marketdepth
: param symbol
: param type : 可选值 : { percent10 , step0 , step1 , step2 , step3 , step4 , step5 }
: return :""" | params = { 'symbol' : symbol , 'type' : _type }
url = u . MARKET_URL + '/market/depth'
def _wrapper ( _func ) :
@ wraps ( _func )
def handle ( ) :
_func ( http_get_request ( url , params ) )
return handle
return _wrapper |
def parse_int_token ( token ) :
"""Parses a string to convert it to an integer based on the format used :
: param token :
The string to convert to an integer .
: type token :
` ` str ` `
: return :
` ` int ` ` or raises ` ` ValueError ` ` exception .
Usage : :
> > > parse _ int _ token ( " 0x40 " ) ... | if token . startswith ( "0x" ) or token . startswith ( "0X" ) :
return int ( token , 16 )
elif token . startswith ( "0" ) :
return int ( token , 8 )
else :
return int ( token ) |
def _dict_to_name_value ( data ) :
'''Convert a dictionary to a list of dictionaries to facilitate ordering''' | if isinstance ( data , dict ) :
sorted_data = sorted ( data . items ( ) , key = lambda s : s [ 0 ] )
result = [ ]
for name , value in sorted_data :
if isinstance ( value , dict ) :
result . append ( { name : _dict_to_name_value ( value ) } )
else :
result . append ( {... |
def camel_to_under ( name ) :
"""Converts camel - case string to lowercase string separated by underscores .
Written by epost ( http : / / stackoverflow . com / questions / 1175208 ) .
: param name : String to be converted
: return : new String with camel - case converted to lowercase , underscored""" | s1 = re . sub ( "(.)([A-Z][a-z]+)" , r"\1_\2" , name )
return re . sub ( "([a-z0-9])([A-Z])" , r"\1_\2" , s1 ) . lower ( ) |
def receive ( self , request : RequestType , user : UserType = None , sender_key_fetcher : Callable [ [ str ] , str ] = None , skip_author_verification : bool = False ) -> Tuple [ str , dict ] :
"""Receive a request .
For testing purposes , ` skip _ author _ verification ` can be passed . Authorship will not be v... | self . user = user
self . get_contact_key = sender_key_fetcher
self . payload = json . loads ( decode_if_bytes ( request . body ) )
self . request = request
self . extract_actor ( )
# Verify the message is from who it claims to be
if not skip_author_verification :
self . verify_signature ( )
return self . actor , s... |
def team ( page ) :
"""Return the team name""" | soup = BeautifulSoup ( page )
try :
return soup . find ( 'title' ) . text . split ( ' | ' ) [ 0 ] . split ( ' - ' ) [ 1 ]
except :
return None |
def get_coordinates_by_full_name ( self , name ) :
"""Retrieves a person ' s coordinates by full name""" | person = self . get_person_by_full_name ( name )
if not person :
return '' , ''
return person . latitude , person . longitude |
def parse_ggKbase_tables ( tables , id_type ) :
"""convert ggKbase genome info tables to dictionary""" | g2info = { }
for table in tables :
for line in open ( table ) :
line = line . strip ( ) . split ( '\t' )
if line [ 0 ] . startswith ( 'name' ) :
header = line
header [ 4 ] = 'genome size (bp)'
header [ 12 ] = '#SCGs'
header [ 13 ] = '#SCG duplicates'
... |
def invalid_multipoly_handler ( gdf , relation , way_ids ) :
"""Handles invalid multipolygon geometries when there exists e . g . a feature without
geometry ( geometry = = NaN )
Parameters
gdf : gpd . GeoDataFrame
GeoDataFrame with Polygon geometries that should be converted into a MultiPolygon object .
r... | try :
gdf_clean = gdf . dropna ( subset = [ 'geometry' ] )
multipoly = MultiPolygon ( list ( gdf_clean [ 'geometry' ] ) )
return multipoly
except Exception :
log ( "Invalid geometry at relation id %s.\nWay-ids of the invalid MultiPolygon:" % ( relation [ 'id' ] , str ( way_ids ) ) )
return None |
def parse ( theme_file ) :
"""Parse the theme file .""" | data = util . read_file_json ( theme_file )
if "wallpaper" not in data :
data [ "wallpaper" ] = "None"
if "alpha" not in data :
data [ "alpha" ] = util . Color . alpha_num
# Terminal . sexy format .
if "color" in data :
data = terminal_sexy_to_wal ( data )
return data |
def get_data_context ( context_type , options , * args , ** kwargs ) :
"""Return a data _ context object which exposes options to list datasets and get a dataset from
that context . This is a new API in Great Expectations 0.4 , and is subject to rapid change .
: param context _ type : ( string ) one of " SqlAlc... | if context_type == "SqlAlchemy" :
return SqlAlchemyDataContext ( options , * args , ** kwargs )
elif context_type == "PandasCSV" :
return PandasCSVDataContext ( options , * args , ** kwargs )
else :
raise ValueError ( "Unknown data context." ) |
def parse ( cls , stream ) :
"""Return an instance of | _ TiffParser | containing the properties parsed
from the TIFF image in * stream * .""" | stream_rdr = cls . _make_stream_reader ( stream )
ifd0_offset = stream_rdr . read_long ( 4 )
ifd_entries = _IfdEntries . from_stream ( stream_rdr , ifd0_offset )
return cls ( ifd_entries ) |
def compose ( * funcs ) :
"""Compose any number of unary functions into a single unary function .
> > > import textwrap
> > > from six import text _ type
> > > stripped = text _ type . strip ( textwrap . dedent ( compose . _ _ doc _ _ ) )
> > > compose ( text _ type . strip , textwrap . dedent ) ( compose .... | def compose_two ( f1 , f2 ) :
return lambda * args , ** kwargs : f1 ( f2 ( * args , ** kwargs ) )
return functools . reduce ( compose_two , funcs ) |
def _process_incoming_data ( self ) :
"""Retrieve and process any incoming data .
: return :""" | while self . _running . is_set ( ) :
if self . poller . is_ready :
self . data_in += self . _receive ( )
self . data_in = self . _on_read_impl ( self . data_in ) |
def endInstance ( self ) :
"""Finalise the instance definition started by startInstance ( ) .""" | if self . currentInstance is None :
return
allInstances = self . root . findall ( '.instances' ) [ 0 ] . append ( self . currentInstance )
self . currentInstance = None |
def print_app_tb_only ( self , file ) :
"NOT _ RPYTHON" | tb = self . _application_traceback
if tb :
import linecache
print >> file , "Traceback (application-level):"
while tb is not None :
co = tb . frame . pycode
lineno = tb . get_lineno ( )
fname = co . co_filename
if fname . startswith ( '<inline>\n' ) :
lines = fnam... |
def run_helper_process ( python_file , metadata_queue , quit_event , options ) :
""": param python _ file : The absolute path of a python file containing the helper process that should be run .
It must define a class which is a subclass of BotHelperProcess .
: param metadata _ queue : A queue from which the hel... | class_wrapper = import_class_with_base ( python_file , BotHelperProcess )
helper_class = class_wrapper . get_loaded_class ( )
helper = helper_class ( metadata_queue , quit_event , options )
helper . start ( ) |
def from_dict ( cls , d ) :
"""Reconstructs the WeightedNbSetChemenvStrategy object from a dict representation of the
WeightedNbSetChemenvStrategy object created using the as _ dict method .
: param d : dict representation of the WeightedNbSetChemenvStrategy object
: return : WeightedNbSetChemenvStrategy obje... | return cls ( additional_condition = d [ "additional_condition" ] , symmetry_measure_type = d [ "symmetry_measure_type" ] , nb_set_weights = d [ "nb_set_weights" ] , ce_estimator = d [ "ce_estimator" ] ) |
def recursively_register_child_states ( self , state ) :
"""A function tha registers recursively all child states of a state
: param state :
: return :""" | self . logger . info ( "Execution status observer add new state {}" . format ( state ) )
if isinstance ( state , ContainerState ) :
state . add_observer ( self , "add_state" , notify_after_function = self . on_add_state )
for state in list ( state . states . values ( ) ) :
self . recursively_register_ch... |
def find_faces ( self , image , draw_box = False ) :
"""Uses a haarcascade to detect faces inside an image .
Args :
image : The image .
draw _ box : If True , the image will be marked with a rectangle .
Return :
The faces as returned by OpenCV ' s detectMultiScale method for
cascades .""" | frame_gray = cv2 . cvtColor ( image , cv2 . COLOR_RGB2GRAY )
faces = self . cascade . detectMultiScale ( frame_gray , scaleFactor = 1.3 , minNeighbors = 5 , minSize = ( 50 , 50 ) , flags = 0 )
if draw_box :
for x , y , w , h in faces :
cv2 . rectangle ( image , ( x , y ) , ( x + w , y + h ) , ( 0 , 255 , 0 ... |
def message_iter ( evt ) :
"""provide a message iterator which checks for a response error prior to returning""" | for msg in evt :
if logger . isEnabledFor ( log . logging . DEBUG ) :
logger . debug ( msg . toString ( ) )
if msg . asElement ( ) . hasElement ( 'responseError' ) :
raise Exception ( msg . toString ( ) )
yield msg |
def get_infrared ( self , callb = None ) :
"""Convenience method to request the infrared brightness from the device
This method will check whether the value has already been retrieved from the device ,
if so , it will simply return it . If no , it will request the information from the device
and request that ... | response = self . req_with_resp ( LightGetInfrared , LightStateInfrared , callb = callb )
return self . infrared_brightness |
def get_unpatched_class ( cls ) :
"""Protect against re - patching the distutils if reloaded
Also ensures that no other distutils extension monkeypatched the distutils
first .""" | external_bases = ( cls for cls in _get_mro ( cls ) if not cls . __module__ . startswith ( 'setuptools' ) )
base = next ( external_bases )
if not base . __module__ . startswith ( 'distutils' ) :
msg = "distutils has already been patched by %r" % cls
raise AssertionError ( msg )
return base |
def san_managers ( self ) :
"""Gets the SanManagers API client .
Returns :
SanManagers :""" | if not self . __san_managers :
self . __san_managers = SanManagers ( self . __connection )
return self . __san_managers |
def get_form ( self ) :
"""Returns an instance of the form to be used in this view .""" | self . form = super ( SmartFormMixin , self ) . get_form ( )
fields = list ( self . derive_fields ( ) )
# apply our field filtering on our form class
exclude = self . derive_exclude ( )
exclude += self . derive_readonly ( )
# remove any excluded fields
for field in exclude :
if field in self . form . fields :
... |
def set_archive_layout ( self , archive_id , layout_type , stylesheet = None ) :
"""Use this method to change the layout of videos in an OpenTok archive
: param String archive _ id : The ID of the archive that will be updated
: param String layout _ type : The layout type for the archive . Valid values are :
... | payload = { 'type' : layout_type , }
if layout_type == 'custom' :
if stylesheet is not None :
payload [ 'stylesheet' ] = stylesheet
endpoint = self . endpoints . set_archive_layout_url ( archive_id )
response = requests . put ( endpoint , data = json . dumps ( payload ) , headers = self . json_headers ( ) ,... |
def populate ( self , obj = None , section = None , parse_types = True ) :
"""Set attributes in ` ` obj ` ` with ` ` setattr ` ` from the all values in
` ` section ` ` .""" | section = self . default_section if section is None else section
obj = Settings ( ) if obj is None else obj
is_dict = isinstance ( obj , dict )
for k , v in self . get_options ( section ) . items ( ) :
if parse_types :
if v == 'None' :
v = None
elif self . FLOAT_REGEXP . match ( v ) :
... |
async def send_audio ( self , chat_id : typing . Union [ base . Integer , base . String ] , audio : typing . Union [ base . InputFile , base . String ] , caption : typing . Union [ base . String , None ] = None , parse_mode : typing . Union [ base . String , None ] = None , duration : typing . Union [ base . Integer , ... | reply_markup = prepare_arg ( reply_markup )
payload = generate_payload ( ** locals ( ) , exclude = [ 'audio' ] )
if self . parse_mode :
payload . setdefault ( 'parse_mode' , self . parse_mode )
files = { }
prepare_file ( payload , files , 'audio' , audio )
result = await self . request ( api . Methods . SEND_AUDIO ... |
def _session ( ) :
'''Create a session to be used when connecting to Zenoss .''' | config = __salt__ [ 'config.option' ] ( 'zenoss' )
session = requests . session ( )
session . auth = ( config . get ( 'username' ) , config . get ( 'password' ) )
session . verify = False
session . headers . update ( { 'Content-type' : 'application/json; charset=utf-8' } )
return session |
def clean ( self : 'TSelf' , * , atol : float = 1e-9 ) -> 'TSelf' :
"""Remove terms with coefficients of absolute value atol or less .""" | negligible = [ v for v , c in self . _terms . items ( ) if abs ( c ) <= atol ]
for v in negligible :
del self . _terms [ v ]
return self |
def _check_child_limits ( self , child_pid ) :
"""Check that inserting a child is within the limits .""" | if self . max_children is not None and self . children . count ( ) >= self . max_children :
raise PIDRelationConsistencyError ( "Max number of children is set to {}." . format ( self . max_children ) )
if self . max_parents is not None and PIDRelation . query . filter_by ( child = child_pid , relation_type = self .... |
def next ( self ) :
"""Return the next window""" | next_index = ( self . index + 1 ) % len ( self . _browser . driver . window_handles )
next_handle = self . _browser . driver . window_handles [ next_index ]
return Window ( self . _browser , next_handle ) |
def _fix_bias_shape ( self , op_name , inputs , attrs ) :
"""A workaround to reshape bias term to ( 1 , num _ channel ) .""" | if ( op_name == 'Add' or op_name == 'Mul' ) and ( int ( len ( self . _params ) ) > 0 ) and ( 'broadcast' in attrs and attrs [ 'broadcast' ] == 1 ) :
assert len ( list ( inputs ) ) == 2
bias_name = self . _renames . get ( inputs [ 1 ] , inputs [ 1 ] )
bias = self . _params [ bias_name ]
assert len ( bias... |
def response_text ( self , status , text = None , content_type = 'text/plain' , encoding = 'utf-8' , headers = None ) :
"""Send a plain - text response""" | if text is None :
if isinstance ( status , str ) :
text = status
else :
text = status . phrase
return self . response ( status , content_type , [ text . encode ( encoding ) ] , headers = headers ) |
def bgc ( mag_file , dir_path = "." , input_dir_path = "" , meas_file = 'measurements.txt' , spec_file = 'specimens.txt' , samp_file = 'samples.txt' , site_file = 'sites.txt' , loc_file = 'locations.txt' , append = False , location = "unknown" , site = "" , samp_con = '1' , specnum = 0 , meth_code = "LP-NO" , volume = ... | version_num = pmag . get_version ( )
input_dir_path , output_dir_path = pmag . fix_directories ( input_dir_path , dir_path )
samp_con = str ( samp_con )
specnum = - int ( specnum )
volume *= 1e-6
# convert cc to m ^ 3
if "4" in samp_con :
if "-" not in samp_con :
print ( "option [4] must be in form 4-Z wher... |
def _get_kwsdag ( self , goids , go2obj , ** kws_all ) :
"""Get keyword args for a GoSubDag .""" | kws_dag = { }
# Term Counts for GO Term information score
tcntobj = self . _get_tcntobj ( goids , go2obj , ** kws_all )
# TermCounts or None
if tcntobj is not None :
kws_dag [ 'tcntobj' ] = tcntobj
# GO letters specified by the user
if 'go_aliases' in kws_all :
fin_go_aliases = kws_all [ 'go_aliases' ]
if o... |
def computeRatModuleParametersFromCellCount ( cellsPerAxis , baselineCellsPerAxis = 6 ) :
"""Compute ' cellsPerAxis ' , ' bumpSigma ' , and ' activeFiringRate ' parameters for
: class : ` ThresholdedGaussian2DLocationModule ` given the number of cells per
axis . See : func : ` createRatModuleFromCellCount `""" | bumpSigma = RAT_BUMP_SIGMA * ( baselineCellsPerAxis / float ( cellsPerAxis ) )
activeFiringRate = ThresholdedGaussian2DLocationModule . chooseReliableActiveFiringRate ( cellsPerAxis , bumpSigma )
return { "cellsPerAxis" : cellsPerAxis , "bumpSigma" : bumpSigma , "activeFiringRate" : activeFiringRate } |
def change_encryption ( self , current_password , cipher , new_password , new_password_id ) :
"""Starts encryption of this medium . This means that the stored data in the
medium is encrypted .
This medium will be placed to : py : attr : ` MediumState . locked _ write `
state .
Please note that the results c... | if not isinstance ( current_password , basestring ) :
raise TypeError ( "current_password can only be an instance of type basestring" )
if not isinstance ( cipher , basestring ) :
raise TypeError ( "cipher can only be an instance of type basestring" )
if not isinstance ( new_password , basestring ) :
raise ... |
def _getDiagnosticString ( ) :
"""Generate a diagnostic string , showing the module version , the platform , current directory etc .
Returns :
A descriptive string .""" | text = '\n## Diagnostic output from minimalmodbus ## \n\n'
text += 'Minimalmodbus version: ' + __version__ + '\n'
text += 'Minimalmodbus status: ' + __status__ + '\n'
text += 'File name (with relative path): ' + __file__ + '\n'
text += 'Full file path: ' + os . path . abspath ( __file__ ) + '\n\n'
text += 'pySerial ver... |
def _read_mode_rsralt ( self , size , kind ) :
"""Read Router Alert option .
Positional arguments :
size - int , length of option
kind - int , 148 ( RTRALT )
Returns :
* dict - - extracted Router Alert ( RTRALT ) option
Structure of Router Alert ( RTRALT ) option [ RFC 2113 ] :
| 10010100 | 00000100 |... | if size != 4 :
raise ProtocolError ( f'{self.alias}: [Optno {kind}] invalid format' )
_code = self . _read_unpack ( 2 )
data = dict ( kind = kind , type = self . _read_opt_type ( kind ) , length = size , alert = _ROUTER_ALERT . get ( _code , 'Reserved' ) , code = _code , )
return data |
def clean ( outputdir , drivers = None ) :
"""Remove driver executables from the specified outputdir .
drivers can be a list of drivers to filter which executables
to remove . Specify a version using an equal sign i . e . : ' chrome = 2.2'""" | if drivers : # Generate a list of tuples : [ ( driver _ name , requested _ version ) ]
# If driver string does not contain a version , the second element
# of the tuple is None .
# Example :
# [ ( ' driver _ a ' , ' 2.2 ' ) , ( ' driver _ b ' , None ) ]
drivers_split = [ helpers . split_driver_name_and_version ( x ... |
def get_relation ( self , relation ) :
"""Get the relation instance for the given relation name .
: rtype : orator . orm . relations . Relation""" | from . relations import Relation
with Relation . no_constraints ( True ) :
rel = getattr ( self . get_model ( ) , relation ) ( )
nested = self . _nested_relations ( relation )
if len ( nested ) > 0 :
rel . get_query ( ) . with_ ( nested )
return rel |
def scan ( self ) :
"""Trigger the wifi interface to scan .""" | self . _logger . info ( "iface '%s' scans" , self . name ( ) )
self . _wifi_ctrl . scan ( self . _raw_obj ) |
def present ( name , pipeline_objects = None , pipeline_objects_from_pillars = 'boto_datapipeline_pipeline_objects' , parameter_objects = None , parameter_objects_from_pillars = 'boto_datapipeline_parameter_objects' , parameter_values = None , parameter_values_from_pillars = 'boto_datapipeline_parameter_values' , regio... | ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } }
pipeline_objects = pipeline_objects or { }
parameter_objects = parameter_objects or { }
parameter_values = parameter_values or { }
present , old_pipeline_definition = _pipeline_present_with_definition ( name , _pipeline_objects ( pipeline_obje... |
def query ( self , sql , parameters = None ) :
"""A generator to issue a query on the server , mogrifying the
parameters against the sql statement . Results are returned as a
: py : class : ` queries . Results ` object which can act as an iterator and
has multiple ways to access the result data .
: param st... | try :
self . _cursor . execute ( sql , parameters )
except psycopg2 . Error as err :
self . _incr_exceptions ( )
raise err
finally :
self . _incr_executions ( )
return results . Results ( self . _cursor ) |
def from_array ( cls , arr ) :
"""Convert a structured NumPy array into a Table .""" | return cls ( ) . with_columns ( [ ( f , arr [ f ] ) for f in arr . dtype . names ] ) |
def stonith_present ( name , stonith_id , stonith_device_type , stonith_device_options = None , cibname = None ) :
'''Ensure that a fencing resource is created
Should be run on one cluster node only
( there may be races )
Can only be run on a node with a functional pacemaker / corosync
name
Irrelevant , n... | return _item_present ( name = name , item = 'stonith' , item_id = stonith_id , item_type = stonith_device_type , extra_args = stonith_device_options , cibname = cibname ) |
def shell_safe_json_parse ( json_or_dict_string , preserve_order = False ) :
"""Allows the passing of JSON or Python dictionary strings . This is needed because certain
JSON strings in CMD shell are not received in main ' s argv . This allows the user to specify
the alternative notation , which does not have th... | try :
if not preserve_order :
return json . loads ( json_or_dict_string )
from collections import OrderedDict
return json . loads ( json_or_dict_string , object_pairs_hook = OrderedDict )
except ValueError :
import ast
return ast . literal_eval ( json_or_dict_string ) |
def visualize_diagram ( bpmn_diagram ) :
"""Shows a simple visualization of diagram
: param bpmn _ diagram : an instance of BPMNDiagramGraph class .""" | g = bpmn_diagram . diagram_graph
pos = bpmn_diagram . get_nodes_positions ( )
nx . draw_networkx_nodes ( g , pos , node_shape = 's' , node_color = 'white' , nodelist = bpmn_diagram . get_nodes_id_list_by_type ( consts . Consts . task ) )
nx . draw_networkx_nodes ( g , pos , node_shape = 's' , node_color = 'white' , nod... |
def _writeResponse ( self , response , request , status = 200 ) :
"""request - - request message
response - - - response message
status - - HTTP Status""" | request . setResponseCode ( status )
if self . encoding is not None :
mimeType = 'text/xml; charset="%s"' % self . encoding
else :
mimeType = "text/xml"
request . setHeader ( "Content-Type" , mimeType )
request . setHeader ( "Content-Length" , str ( len ( response ) ) )
request . write ( response )
request . fi... |
def parameters_changed ( self ) :
"""Parameters have now changed""" | # np . set _ printoptions ( 16)
# print ( self . param _ array )
# Get the model matrices from the kernel
( F , L , Qc , H , P_inf , P0 , dFt , dQct , dP_inft , dP0t ) = self . kern . sde ( )
# necessary parameters
measurement_dim = self . output_dim
grad_params_no = dFt . shape [ 2 ] + 1
# we also add measurement nois... |
def checkout_moses_tokenizer ( workspace_dir : str ) :
"""Checkout Moses tokenizer ( sparse checkout of Moses ) .
: param workspace _ dir : Workspace directory .""" | # Prerequisites
check_git ( )
check_perl ( )
# Check cache
dest = os . path . join ( workspace_dir , DIR_THIRD_PARTY , MOSES_DEST )
if confirm_checkout ( dest , MOSES_COMMIT ) :
logging . info ( "Usable: %s" , dest )
return
# Need to ( re - ) checkout
if os . path . exists ( dest ) :
shutil . rmtree ( dest ... |
def get_velocity ( samplemat , Hz , blinks = None ) :
'''Compute velocity of eye - movements .
Samplemat must contain fields ' x ' and ' y ' , specifying the x , y coordinates
of gaze location . The function assumes that the values in x , y are sampled
continously at a rate specified by ' Hz ' .''' | Hz = float ( Hz )
distance = ( ( np . diff ( samplemat . x ) ** 2 ) + ( np . diff ( samplemat . y ) ** 2 ) ) ** .5
distance = np . hstack ( ( [ distance [ 0 ] ] , distance ) )
if blinks is not None :
distance [ blinks [ 1 : ] ] = np . nan
win = np . ones ( ( velocity_window_size ) ) / float ( velocity_window_size )... |
def cursor_query ( self , collection , query ) :
""": param str collection : The name of the collection for the request .
: param dict query : Dictionary of solr args .
Will page through the result set in increments using cursorMark until it has all items . Sort is required for cursorMark queries , if you don '... | cursor = '*'
if 'sort' not in query :
query [ 'sort' ] = 'id desc'
while True :
query [ 'cursorMark' ] = cursor
# Get data with starting cursorMark
results = self . query ( collection , query )
if results . get_results_count ( ) :
cursor = results . get_cursor ( )
yield results
e... |
def waitForDeferred ( d , result = None ) :
"""Block current greenlet for Deferred , waiting until result is not a Deferred or a failure is encountered""" | from twisted . internet import reactor
assert reactor . greenlet != getcurrent ( ) , "can't invoke this in the reactor greenlet"
if result is None :
result = AsyncResult ( )
def cb ( res ) :
if isinstance ( res , defer . Deferred ) :
waitForDeferred ( res , result )
else :
result . set ( res... |
def get_zoneID ( self , headers , zone ) :
"""Get the zone id for the zone .""" | zoneIDurl = self . BASE_URL + '?name=' + zone
zoneIDrequest = requests . get ( zoneIDurl , headers = headers )
zoneID = zoneIDrequest . json ( ) [ 'result' ] [ 0 ] [ 'id' ]
return zoneID |
def transform_search_hit ( self , pid , record_hit , links_factory = None , ** kwargs ) :
"""Transform search result hit into an intermediate representation .""" | context = kwargs . get ( 'marshmallow_context' , { } )
context . setdefault ( 'pid' , pid )
return self . dump ( self . preprocess_search_hit ( pid , record_hit , links_factory = links_factory , ** kwargs ) , context ) |
def is_entailed_by ( self , other ) :
"""Fewer members = more information ( exception is empty set , which means
all members of the domain )
(1 ) when self is empty and others is not ( equal to containing the
entire domain )
(2 ) when other contains more members than self""" | if not self . same_domain ( other ) :
return False
if not other . values :
if self . values : # None can never entail - None
return False
else : # None entails None
return True
return not self . values or self . values . issuperset ( other . values ) |
def read_bucket ( self , bucket_name ) :
'''a method to retrieve properties of a bucket in s3
: param bucket _ name : string with name of bucket
: return : dictionary with details of bucket''' | title = '%s.read_bucket' % self . __class__ . __name__
# validate inputs
input_fields = { 'bucket_name' : bucket_name }
for key , value in input_fields . items ( ) :
object_title = '%s(%s=%s)' % ( title , key , str ( value ) )
self . fields . validate ( value , '.%s' % key , object_title )
# validate existence ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.