signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def del_pipe ( self , pipe , forced = False ) :
"""Deletes a pipe ( A , . . . , N ) which is an N - ` ` tuple ` ` of ` ` Piper ` `
instances . Deleting a pipe means to delete all the connections between
` ` Pipers ` ` and to delete all the ` ` Pipers ` ` . If " forced " is ` ` False ` `
only ` ` Pipers ` ` wh... | self . log . debug ( '%s removes pipe%s forced: %s' % ( repr ( self ) , repr ( pipe ) , forced ) )
pipe = list ( reversed ( pipe ) )
for i in xrange ( len ( pipe ) - 1 ) :
edge = ( self . resolve ( pipe [ i ] ) , self . resolve ( pipe [ i + 1 ] ) )
self . del_edge ( edge )
self . log . debug ( '%s removed t... |
def create_choice_attribute ( creator_type , value , choice_entry ) :
"""Create an instance of a subclass of ChoiceAttributeMixin for the given value .
Parameters
creator _ type : type
` ` ChoiceAttributeMixin ` ` or a subclass , from which we ' ll call the ` ` get _ class _ for _ value ` `
class - method .... | klass = creator_type . get_class_for_value ( value )
return klass ( value , choice_entry ) |
def handle_error ( self , callback ) :
"""Called when an error occurs in an event loop callback .
By default , sets the error view .""" | self . loop . log_error ( callback )
msg = "\n" . join ( [ "Exception in callback %r" % callback , traceback . format_exc ( ) ] )
self . show_error ( msg . encode ( 'utf-8' ) ) |
def format_datetime ( dt , usegmt = False ) :
"""Turn a datetime into a date string as specified in RFC 2822.
If usegmt is True , dt must be an aware datetime with an offset of zero . In
this case ' GMT ' will be rendered instead of the normal + 0000 required by
RFC2822 . This is to support HTTP headers invol... | now = dt . timetuple ( )
if usegmt :
if dt . tzinfo is None or dt . tzinfo != datetime . timezone . utc :
raise ValueError ( "usegmt option requires a UTC datetime" )
zone = 'GMT'
elif dt . tzinfo is None :
zone = '-0000'
else :
zone = dt . strftime ( "%z" )
return _format_timetuple_and_zone ( n... |
def takeScreenshotAndShowItOnWindow ( self ) :
'''Takes the current screenshot and shows it on the main window .
It also :
- sizes the window
- create the canvas
- set the focus
- enable the events
- create widgets
- finds the targets ( as explained in L { findTargets } )
- hides the vignette ( that... | if PROFILE :
print >> sys . stderr , "PROFILING: takeScreenshotAndShowItOnWindow()"
profileStart ( )
if DEBUG :
print >> sys . stderr , "takeScreenshotAndShowItOnWindow()"
if self . vc and self . vc . uiAutomatorHelper :
received = self . vc . uiAutomatorHelper . takeScreenshot ( )
stream = StringIO... |
def is_iterable ( val ) :
"""Check if val is not a list , but is a collections . Iterable type . This is used to determine
when list ( ) should be called on val
> > > l = [ 1 , 2]
> > > is _ iterable ( l )
False
> > > is _ iterable ( iter ( l ) )
True
: param val : value to check
: return : True if ... | if isinstance ( val , list ) :
return False
return isinstance ( val , collections . Iterable ) |
def run ( self , ** client_params ) :
"""Actually creates the async job on the CARTO server
: param client _ params : To be send to the CARTO API . See CARTO ' s
documentation depending on the subclass
you are using
: type client _ params : kwargs
: return :
: raise : CartoException""" | try :
self . send ( self . get_collection_endpoint ( ) , http_method = "POST" , ** client_params )
except Exception as e :
raise CartoException ( e ) |
def make_model ( self ) :
"""Assemble text from the set of collected INDRA Statements .
Returns
stmt _ strs : str
Return the assembled text as unicode string . By default , the text
is a single string consisting of one or more sentences with
periods at the end .""" | stmt_strs = [ ]
for stmt in self . statements :
if isinstance ( stmt , ist . Modification ) :
stmt_strs . append ( _assemble_modification ( stmt ) )
elif isinstance ( stmt , ist . Autophosphorylation ) :
stmt_strs . append ( _assemble_autophosphorylation ( stmt ) )
elif isinstance ( stmt , i... |
def _decode_surrogatepass ( data , codec ) :
"""Like data . decode ( codec , ' surrogatepass ' ) but makes utf - 16 - le / be work
on Python < 3.4 + Windows
https : / / bugs . python . org / issue27971
Raises UnicodeDecodeError , LookupError""" | try :
return data . decode ( codec , _surrogatepass )
except UnicodeDecodeError :
if not _codec_can_decode_with_surrogatepass ( codec ) :
if _normalize_codec ( codec ) == "utf-16-be" :
data = _swap_bytes ( data )
codec = "utf-16-le"
if _normalize_codec ( codec ) == "utf-1... |
def erase_all ( self ) :
"""@ brief Erase all the flash .
@ exception FlashEraseFailure""" | assert self . _active_operation == self . Operation . ERASE
assert self . is_erase_all_supported
# update core register to execute the erase _ all subroutine
result = self . _call_function_and_wait ( self . flash_algo [ 'pc_eraseAll' ] )
# check the return code
if result != 0 :
raise FlashEraseFailure ( 'erase_all ... |
def module_can_run_parallel ( test_module : unittest . TestSuite ) -> bool :
"""Checks if a given module of tests can be run in parallel or not
: param test _ module : the module to run
: return : True if the module can be run on parallel , False otherwise""" | for test_class in test_module : # if the test is already failed , we just don ' t filter it
# and let the test runner deal with it later .
if hasattr ( unittest . loader , '_FailedTest' ) : # import failure in python 3.4.5 +
# noinspection PyProtectedMember
if isinstance ( test_class , unittest . loader... |
def stoptimes ( self , start_date , end_date ) :
"""Return all stop times in the date range
: param start _ date :
The starting date for the query .
: param end _ date :
The end date for the query .
> > > import datetime
> > > today = datetime . date . today ( )
> > > trans . stoptimes ( today - datet... | params = { 'start' : self . format_date ( start_date ) , 'end' : self . format_date ( end_date ) }
response = self . _request ( ENDPOINTS [ 'STOPTIMES' ] , params )
return response |
def _get_hash ( self , name , operation , create = False ) :
"""Get ( and maybe create ) a hash by name .""" | return self . _get_by_type ( name , operation , create , b'hash' , { } ) |
def calculate_start_time ( df ) :
"""Calculate the star _ time per read .
Time data is either
a " time " ( in seconds , derived from summary files ) or
a " timestamp " ( in UTC , derived from fastq _ rich format )
and has to be converted appropriately in a datetime format time _ arr
For both the time _ ze... | if "time" in df :
df [ "time_arr" ] = pd . Series ( df [ "time" ] , dtype = 'datetime64[s]' )
elif "timestamp" in df :
df [ "time_arr" ] = pd . Series ( df [ "timestamp" ] , dtype = "datetime64[ns]" )
else :
return df
if "dataset" in df :
for dset in df [ "dataset" ] . unique ( ) :
time_zero = d... |
def vrfs_get ( self , subcommand = 'routes' , route_dist = None , route_family = 'all' , format = 'json' ) :
"""This method returns the existing vrfs .
` ` subcommand ` ` specifies one of the following .
- ' routes ' : shows routes present for vrf
- ' summary ' : shows configuration and summary of vrf
` ` r... | show = { 'format' : format , }
if route_family in SUPPORTED_VRF_RF :
assert route_dist is not None
show [ 'params' ] = [ 'vrf' , subcommand , route_dist , route_family ]
else :
show [ 'params' ] = [ 'vrf' , subcommand , 'all' ]
return call ( 'operator.show' , ** show ) |
def get_initial ( self , form , name ) :
"""Get the initial data that got passed into the superform for this
composite field . It should return ` ` None ` ` if no initial values where
given .""" | if hasattr ( form , 'initial' ) :
return form . initial . get ( name , None )
return None |
def get_history_by_flight_number ( self , flight_number , page = 1 , limit = 100 ) :
"""Fetch the history of a flight by its number .
This method can be used to get the history of a flight route by the number .
It checks the user authentication and returns the data accordingly .
Args :
flight _ number ( str... | url = FLT_BASE . format ( flight_number , str ( self . AUTH_TOKEN ) , page , limit )
return self . _fr24 . get_data ( url ) |
def do_dump ( self , arg ) :
'''Output all bytes waiting in output queue .''' | if not self . arm . is_connected ( ) :
print ( self . style . error ( 'Error: ' , 'Arm is not connected.' ) )
return
print ( self . arm . dump ( ) ) |
def final ( ) :
"""In case the program is cancelled or quit , we need to clean up the PulseIn
helper process and also the message queue , this is called at exit to do so""" | if DEBUG :
print ( "Cleaning up message queues" , queues )
print ( "Cleaning up processes" , procs )
for q in queues :
q . remove ( )
for proc in procs :
proc . terminate ( ) |
def get_context ( self , arr , expr , context ) :
"""Returns a context dictionary for use in evaluating the expression .
: param arr : The input array .
: param expr : The input expression .
: param context : Evaluation context .""" | expression_names = [ x for x in self . get_expression_names ( expr ) if x not in set ( context . keys ( ) ) . union ( [ 'i' ] ) ]
if len ( expression_names ) != 1 :
raise ValueError ( 'The expression must have exactly one variable.' )
return { expression_names [ 0 ] : arr } |
def _get_conversion_outfile ( self , convert_to = None ) :
'''a helper function to return a conversion temporary output file
based on kind of conversion
Parameters
convert _ to : a string either docker or singularity , if a different''' | conversion = self . _get_conversion_type ( convert_to )
prefix = "Singularity"
if conversion == "docker" :
prefix = "Dockerfile"
suffix = next ( tempfile . _get_candidate_names ( ) )
return "%s.%s" % ( prefix , suffix ) |
def get_skyline ( lrh ) :
"""Wortst Time Complexity : O ( NlogN )
: type buildings : List [ List [ int ] ]
: rtype : List [ List [ int ] ]""" | skyline , live = [ ] , [ ]
i , n = 0 , len ( lrh )
while i < n or live :
if not live or i < n and lrh [ i ] [ 0 ] <= - live [ 0 ] [ 1 ] :
x = lrh [ i ] [ 0 ]
while i < n and lrh [ i ] [ 0 ] == x :
heapq . heappush ( live , ( - lrh [ i ] [ 2 ] , - lrh [ i ] [ 1 ] ) )
i += 1
... |
def submit_all ( self , poll = True , errors = True , process_files = True , halt_on_error = True ) :
"""Submit Batch request to ThreatConnect API .
By default this method will submit the job request and data and if the size of the data
is below the value * * synchronousBatchSaveLimit * * set in System Setting ... | batch_data_array = [ ]
while True :
batch_data = { }
batch_id = None
if self . action . lower ( ) == 'delete' : # while waiting of FR for delete support in createAndUpload submit delete request
# the old way ( submit job + submit data ) , still using V2.
if len ( self ) > 0 : # pylint : disable ... |
def page ( self , status = values . unset , date_created_after = values . unset , date_created_before = values . unset , room_sid = values . unset , page_token = values . unset , page_number = values . unset , page_size = values . unset ) :
"""Retrieve a single page of CompositionInstance records from the API .
R... | params = values . of ( { 'Status' : status , 'DateCreatedAfter' : serialize . iso8601_datetime ( date_created_after ) , 'DateCreatedBefore' : serialize . iso8601_datetime ( date_created_before ) , 'RoomSid' : room_sid , 'PageToken' : page_token , 'Page' : page_number , 'PageSize' : page_size , } )
response = self . _ve... |
def set ( self , time , value , compact = False ) :
"""Set the value for the time series . If compact is True , only set the
value if it ' s different from what it would be anyway .""" | if ( len ( self ) == 0 ) or ( not compact ) or ( compact and self . get ( time ) != value ) :
self . _d [ time ] = value |
async def open_session ( self , request : BaseRequestWebsocket ) -> Session :
"""Open and return a Session using the request .""" | return await ensure_coroutine ( self . session_interface . open_session ) ( self , request ) |
def tmpfile ( prefix , direc ) :
"""Returns the path to a newly created temporary file .""" | return tempfile . mktemp ( prefix = prefix , suffix = '.pdb' , dir = direc ) |
def query_pa_no_flush ( session , permission , role , obj ) :
"""Query for a : class : ` PermissionAssignment ` using ` session ` without any
` flush ( ) ` .
It works by looking in session ` new ` , ` dirty ` and ` deleted ` , and issuing a
query with no autoflush .
. . note : :
This function is used by `... | to_visit = [ session . deleted , session . dirty , session . new ]
with session . no_autoflush : # no _ autoflush is required to visit PERMISSIONS _ ATTR without emitting a
# flush ( )
if obj :
to_visit . append ( getattr ( obj , PERMISSIONS_ATTR ) )
permissions = ( p for p in chain ( * to_visit ) if is... |
async def toggle ( self ) :
"""Toggles between pause and resume command""" | self . logger . debug ( "toggle command" )
if not self . state == 'ready' :
return
if self . streamer is None :
return
try :
if self . streamer . is_playing ( ) :
await self . pause ( )
else :
await self . resume ( )
except Exception as e :
logger . error ( e )
pass |
def get_row_generator ( self , ref , cache = None ) :
"""Return a row generator for a reference""" | from inspect import isgenerator
from rowgenerators import get_generator
g = get_generator ( ref )
if not g :
raise GenerateError ( "Cant figure out how to generate rows from {} ref: {}" . format ( type ( ref ) , ref ) )
else :
return g |
def urlsplit ( url ) :
"""Split an arbitrary url into protocol , host , rest
The standard urlsplit does not want to provide ' netloc ' for arbitrary
protocols , this works around that .
: param url : The url to split into component parts""" | proto , rest = url . split ( ':' , 1 )
host = ''
if rest [ : 2 ] == '//' :
host , rest = rest [ 2 : ] . split ( '/' , 1 )
rest = '/' + rest
return proto , host , rest |
def _compute_inflation ( value , reference_value ) :
"""Helper function to compute the inflation / deflation based on a value and
a reference value""" | res = value / float ( reference_value )
return InflationResult ( factor = res , value = res - 1 ) |
def dropout_mask ( x : Tensor , sz : Collection [ int ] , p : float ) :
"Return a dropout mask of the same type as ` x ` , size ` sz ` , with probability ` p ` to cancel an element ." | return x . new ( * sz ) . bernoulli_ ( 1 - p ) . div_ ( 1 - p ) |
def _discover_meta_cols ( self , ** kwargs ) :
"""Return the subset of ` kwargs ` values ( not keys ! ) matching
a ` meta ` column name""" | cols = set ( [ 'exclude' ] )
for arg , value in kwargs . items ( ) :
if isstr ( value ) and value in self . meta . columns :
cols . add ( value )
return list ( cols ) |
def prepare_function_symbol ( self , symbol_name , basic_addr = None ) :
"""Prepare the address space with the data necessary to perform relocations pointing to the given symbol
Returns a 2 - tuple . The first item is the address of the function code , the second is the address of the
relocation target .""" | if basic_addr is None :
basic_addr = self . project . loader . extern_object . get_pseudo_addr ( symbol_name )
return basic_addr , basic_addr |
def normalize_keys ( self , value ) :
"""Normalize the keys of a dictionary using : func : ` normalize _ name ( ) ` .
: param value : The dictionary to normalize .
: returns : A dictionary with normalized keys .""" | return dict ( ( self . normalize_name ( k ) , v ) for k , v in value . items ( ) ) |
def list_all_promotions ( cls , ** kwargs ) :
"""List Promotions
Return a list of Promotions
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . list _ all _ promotions ( async = True )
> > > result = thread . get (... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _list_all_promotions_with_http_info ( ** kwargs )
else :
( data ) = cls . _list_all_promotions_with_http_info ( ** kwargs )
return data |
def tx_tn_days_above ( tasmin , tasmax , thresh_tasmin = '22 degC' , thresh_tasmax = '30 degC' , freq = 'YS' ) :
r"""Number of days with both hot maximum and minimum daily temperatures .
The number of days per period with tasmin above a threshold and tasmax above another threshold .
Parameters
tasmin : xarray... | thresh_tasmax = utils . convert_units_to ( thresh_tasmax , tasmax )
thresh_tasmin = utils . convert_units_to ( thresh_tasmin , tasmin )
events = ( ( tasmin > ( thresh_tasmin ) ) & ( tasmax > ( thresh_tasmax ) ) ) * 1
return events . resample ( time = freq ) . sum ( dim = 'time' ) |
def GetCollectionNode ( self , partition_key ) :
"""Gets the SelfLink / ID based link of the collection node that maps to the partition key
based on the hashing algorithm used for finding the node in the ring .
: param str partition _ key :
The partition key to be used for finding the node in the ring .
: r... | if partition_key is None :
raise ValueError ( "partition_key is None or empty." )
partition_number = self . _FindPartition ( self . _GetBytes ( partition_key ) )
return self . partitions [ partition_number ] . GetNode ( ) |
def mk_dict ( results , description ) :
"""Given a result list and descrition sequence , return a list
of dictionaries""" | rows = [ ]
for row in results :
row_dict = { }
for idx in range ( len ( row ) ) :
col = description [ idx ] [ 0 ]
row_dict [ col ] = row [ idx ]
rows . append ( row_dict )
return rows |
def get_shard_id2num_examples ( num_shards , total_num_examples ) :
"""Return the mapping shard _ id = > num _ examples , assuming round - robin .""" | # TODO ( b / 130353071 ) : This has the strong assumption that the shards have
# been written in a round - robin fashion . This assumption does not hold , for
# instance , with Beam generation . The mapping shard _ id = > num _ examples
# should be computed during generation .
# Minimum number of example per shards
num... |
def segment_length ( curve , start , end , start_point , end_point , error = LENGTH_ERROR , min_depth = LENGTH_MIN_DEPTH , depth = 0 ) :
"""Recursively approximates the length by straight lines""" | mid = ( start + end ) / 2
mid_point = curve . point ( mid )
length = abs ( end_point - start_point )
first_half = abs ( mid_point - start_point )
second_half = abs ( end_point - mid_point )
length2 = first_half + second_half
if ( length2 - length > error ) or ( depth < min_depth ) : # Calculate the length of each segme... |
def filter_input ( keys , raw ) :
"""Adds fancy mouse wheel functionality and VI navigation to ListBox""" | if len ( keys ) == 1 :
if keys [ 0 ] in UI . keys [ 'up' ] :
keys [ 0 ] = 'up'
elif keys [ 0 ] in UI . keys [ 'down' ] :
keys [ 0 ] = 'down'
elif len ( keys [ 0 ] ) == 4 and keys [ 0 ] [ 0 ] == 'mouse press' :
if keys [ 0 ] [ 1 ] == 4 :
keys [ 0 ] = 'up'
elif keys... |
def histogram_summary ( tag , values , bins ) :
"""Outputs a ` Summary ` protocol buffer with a histogram .
Adding a histogram summary makes it possible to visualize the data ' s distribution in
TensorBoard . See detailed explanation of the TensorBoard histogram dashboard at
https : / / www . tensorflow . org... | tag = _clean_tag ( tag )
values = _make_numpy_array ( values )
hist = _make_histogram ( values . astype ( float ) , bins )
return Summary ( value = [ Summary . Value ( tag = tag , histo = hist ) ] ) |
def add_federation ( self , provider , federated_id ) :
"""Add federated login to the current user
: param provider :
: param federated _ id :
: return :""" | models . AuthUserFederation . new ( user = self , provider = provider , federated_id = federated_id ) |
def _read_dataframes_100k ( path ) :
"""reads in the movielens 100k dataset""" | import pandas
ratings = pandas . read_table ( os . path . join ( path , "u.data" ) , names = [ 'userId' , 'movieId' , 'rating' , 'timestamp' ] )
movies = pandas . read_csv ( os . path . join ( path , "u.item" ) , names = [ 'movieId' , 'title' ] , usecols = [ 0 , 1 ] , delimiter = '|' , encoding = 'ISO-8859-1' )
return ... |
def load_model ( self , tid , custom_objects = None ) :
"""Load saved keras model of the trial .
If tid = None , get the best model
Not applicable for trials ran in cross validion ( i . e . not applicable
for ` CompileFN . cv _ n _ folds is None `""" | if tid is None :
tid = self . best_trial_tid ( )
model_path = self . get_trial ( tid ) [ "result" ] [ "path" ] [ "model" ]
return load_model ( model_path , custom_objects = custom_objects ) |
def subroutine ( self , iterator , asyncStart = True , name = None , daemon = False ) :
"""Start extra routines in this container .
: param iterator : A coroutine object i . e the return value of an async method ` my _ routine ( ) `
: param asyncStart : if False , start the routine in foreground . By default , ... | r = Routine ( iterator , self . scheduler , asyncStart , self , True , daemon )
if name is not None :
setattr ( self , name , r )
# Call subroutine may change the currentroutine , we should restore it
currentroutine = getattr ( self , 'currentroutine' , None )
try :
next ( r )
except StopIteration :
pass
se... |
def tune ( self , divergence_threshold = 1e10 , verbose = 0 ) :
"""Tunes the scaling parameter for the proposal distribution
according to the acceptance rate of the last k proposals :
Rate Variance adaptation
< 0.001 x 0.1
< 0.05 x 0.5
< 0.2 x 0.9
> 0.5 x 1.1
> 0.75 x 2
> 0.95 x 10
This method is ... | if self . verbose > - 1 :
verbose = self . verbose
# Verbose feedback
if verbose > 0 :
print_ ( '\t%s tuning:' % self . _id )
# Flag for tuning state
tuning = True
# Calculate recent acceptance rate
if not ( self . accepted + self . rejected ) :
return tuning
acc_rate = self . accepted / ( self . accepted +... |
def fits_region_objects_to_table ( regions ) :
"""Converts list of regions to FITS region table .
Parameters
regions : list
List of ` regions . Region ` objects
Returns
region _ string : ` ~ astropy . table . Table `
FITS region table
Examples
> > > from regions import CirclePixelRegion , PixCoord
... | for reg in regions :
if isinstance ( reg , SkyRegion ) :
raise TypeError ( 'Every region must be a pixel region' . format ( reg ) )
shape_list = to_shape_list ( regions , coordinate_system = 'image' )
return shape_list . to_fits ( ) |
def _onPaint ( self , evt ) :
"""Called when wxPaintEvt is generated""" | DEBUG_MSG ( "_onPaint()" , 1 , self )
drawDC = wx . PaintDC ( self )
if not self . _isDrawn :
self . draw ( drawDC = drawDC )
else :
self . gui_repaint ( drawDC = drawDC )
evt . Skip ( ) |
def get_representations_of_kind ( kind , start = None , end = None ) :
"""Return all representations of properties of kind in the specified range .
NOTE : This function does not return unindexed properties .
Args :
kind : name of kind whose properties you want .
start : only return properties > = start if s... | q = Property . query ( ancestor = Property . key_for_kind ( kind ) )
if start is not None and start != '' :
q = q . filter ( Property . key >= Property . key_for_property ( kind , start ) )
if end is not None :
if end == '' :
return { }
q = q . filter ( Property . key < Property . key_for_property (... |
def plot_predict ( self , h = 5 , past_values = 20 , intervals = True , oos_data = None , ** kwargs ) :
"""Makes forecast with the estimated model
Parameters
h : int ( default : 5)
How many steps ahead would you like to forecast ?
past _ values : int ( default : 20)
How many past observations to show on t... | import matplotlib . pyplot as plt
import seaborn as sns
figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) )
nsims = kwargs . get ( 'nsims' , 200 )
if self . latent_variables . estimated is False :
raise Exception ( "No latent variables estimated!" )
else :
_ , X_oos = dmatrices ( self . formula , oos_data )
X... |
def reloadFileAtIndex ( self , itemIndex , rtiClass = None ) :
"""Reloads the item at the index by removing the repo tree item and inserting a new one .
The new item will have by of type rtiClass . If rtiClass is None ( the default ) , the
new rtiClass will be the same as the old one .""" | fileRtiParentIndex = itemIndex . parent ( )
fileRti = self . getItem ( itemIndex )
position = fileRti . childNumber ( )
fileName = fileRti . fileName
if rtiClass is None :
rtiClass = type ( fileRti )
# Delete old RTI and Insert a new one instead .
self . deleteItemAtIndex ( itemIndex )
# this will close the items r... |
def send_result ( self , additional_dict ) :
'''Send a result to the RPC client
: param additional _ dict : the dictionary with the response''' | self . send_response ( 200 )
self . send_header ( "Content-type" , "application/json" )
response = { 'jsonrpc' : self . req_rpc_version , 'id' : self . req_id , }
response . update ( additional_dict )
jresponse = json . dumps ( response )
self . send_header ( "Content-length" , len ( jresponse ) )
self . end_headers ( ... |
def replace_cancel_operation_by_id ( cls , cancel_operation_id , cancel_operation , ** kwargs ) :
"""Replace CancelOperation
Replace all attributes of CancelOperation
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _replace_cancel_operation_by_id_with_http_info ( cancel_operation_id , cancel_operation , ** kwargs )
else :
( data ) = cls . _replace_cancel_operation_by_id_with_http_info ( cancel_operation_id , cancel_operation , ** kwargs ... |
def select_option_by_text ( self , dropdown_selector , option , dropdown_by = By . CSS_SELECTOR , timeout = settings . SMALL_TIMEOUT ) :
"""Selects an HTML < select > option by option text .
@ Params
dropdown _ selector - the < select > selector
option - the text of the option""" | if self . timeout_multiplier and timeout == settings . SMALL_TIMEOUT :
timeout = self . __get_new_timeout ( timeout )
self . __select_option ( dropdown_selector , option , dropdown_by = dropdown_by , option_by = "text" , timeout = timeout ) |
def get ( self , sid ) :
"""Constructs a FunctionContext
: param sid : The sid
: returns : twilio . rest . serverless . v1 . service . function . FunctionContext
: rtype : twilio . rest . serverless . v1 . service . function . FunctionContext""" | return FunctionContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , sid = sid , ) |
def concordance_index_ipcw ( survival_train , survival_test , estimate , tau = None , tied_tol = 1e-8 ) :
"""Concordance index for right - censored data based on inverse probability of censoring weights .
This is an alternative to the estimator in : func : ` concordance _ index _ censored `
that does not depend... | test_event , test_time = check_y_survival ( survival_test )
if tau is not None :
survival_test = survival_test [ test_time < tau ]
estimate = check_array ( estimate , ensure_2d = False )
check_consistent_length ( test_event , test_time , estimate )
cens = CensoringDistributionEstimator ( )
cens . fit ( survival_tra... |
def validate_query_params ( self , request ) :
"""Validate that query params are in the list of valid query keywords in
: py : attr : ` query _ regex `
: raises ValidationError : if not .""" | # TODO : For jsonapi error object conformance , must set jsonapi errors " parameter " for
# the ValidationError . This requires extending DRF / DJA Exceptions .
for qp in request . query_params . keys ( ) :
if not self . query_regex . match ( qp ) :
raise ValidationError ( 'invalid query parameter: {}' . fo... |
def set_integer_value ( self , value = None ) :
"""stub""" | if value is None :
raise NullArgument ( )
if self . get_integer_value_metadata ( ) . is_read_only ( ) :
raise NoAccess ( )
if not self . my_osid_object_form . _is_valid_integer ( value , self . get_integer_value_metadata ( ) ) :
raise InvalidArgument ( )
self . my_osid_object_form . _my_map [ 'integerValue'... |
def add ( self , key , val ) :
"""Adds a ( name , value ) pair , doesn ' t overwrite the value if it already
exists .
> > > headers = HTTPHeaderDict ( foo = ' bar ' )
> > > headers . add ( ' Foo ' , ' baz ' )
> > > headers [ ' foo ' ]
' bar , baz '""" | key_lower = key . lower ( )
new_vals = key , val
# Keep the common case aka no item present as fast as possible
vals = _dict_setdefault ( self , key_lower , new_vals )
if new_vals is not vals : # new _ vals was not inserted , as there was a previous one
if isinstance ( vals , list ) : # If already several items got... |
def connect_cloudwatch ( aws_access_key_id = None , aws_secret_access_key = None , ** kwargs ) :
""": type aws _ access _ key _ id : string
: param aws _ access _ key _ id : Your AWS Access Key ID
: type aws _ secret _ access _ key : string
: param aws _ secret _ access _ key : Your AWS Secret Access Key
: ... | from boto . ec2 . cloudwatch import CloudWatchConnection
return CloudWatchConnection ( aws_access_key_id , aws_secret_access_key , ** kwargs ) |
async def edit_message ( self , entity , message = None , text = None , * , parse_mode = ( ) , link_preview = True , file = None , buttons = None ) :
"""Edits the given message ID ( to change its contents or disable preview ) .
Args :
entity ( ` entity ` | ` Message < telethon . tl . custom . message . Message ... | if isinstance ( entity , types . InputBotInlineMessageID ) :
text = message
message = entity
elif isinstance ( entity , types . Message ) :
text = message
# Shift the parameters to the right
message = entity
entity = entity . to_id
text , msg_entities = await self . _parse_message_text ( text , ... |
def poll ( self ) :
"""Update internal state from polling strava . com .
: raise stravalib . exc . ActivityUploadFailed : If the poll returns an error .""" | response = self . client . protocol . get ( '/uploads/{upload_id}' , upload_id = self . upload_id , check_for_errors = False )
self . update_from_response ( response ) |
def delete ( self ) :
"""delete the object from the db if pk is set""" | ret = False
q = self . query
pk = self . pk
if pk :
pk_name = self . schema . pk . name
self . query . is_field ( pk_name , pk ) . delete ( )
setattr ( self , pk_name , None )
# mark all the fields that still exist as modified
self . reset_modified ( )
for field_name in self . schema . fields :
... |
def createEditor ( self , parent , column , operator , value ) :
"""Creates a new editor for the system .""" | editor = super ( EnumPlugin , self ) . createEditor ( parent , column , operator , value )
editor . setEnum ( column . enum ( ) )
if operator in ( 'contains' , 'does not contain' ) :
editor . setCheckable ( True )
editor . setCurrentValue ( value )
return editor |
def _read_mol ( self ) :
"""- V3000""" | self . system = dict ( )
if self . file_content [ 2 ] != '\n' :
self . system [ 'remarks' ] = self . file_content [ 2 ]
file_body = [ i . split ( ) for i in self . file_content ]
elements = [ ]
coordinates = [ ]
atom_data = False
for line in file_body :
if len ( line ) > 2 :
if line [ 2 ] == 'END' and l... |
def _geometric_intersect ( nodes1 , degree1 , nodes2 , degree2 , verify ) :
r"""Find all intersections among edges of two surfaces .
. . note : :
There is also a Fortran implementation of this function , which
will be used if it can be built .
Uses : func : ` generic _ intersect ` with the
: attr : ` ~ . ... | all_intersections = _geometric_intersection . all_intersections
return generic_intersect ( nodes1 , degree1 , nodes2 , degree2 , verify , all_intersections ) |
def from_dict ( d ) :
"""Recreate a KrausModel from the dictionary representation .
: param dict d : The dictionary representing the KrausModel . See ` to _ dict ` for an
example .
: return : The deserialized KrausModel .
: rtype : KrausModel""" | kraus_ops = [ KrausModel . unpack_kraus_matrix ( k ) for k in d [ 'kraus_ops' ] ]
return KrausModel ( d [ 'gate' ] , d [ 'params' ] , d [ 'targets' ] , kraus_ops , d [ 'fidelity' ] ) |
def clean_tenant_url ( url_string ) :
"""Removes the TENANT _ TOKEN from a particular string""" | if hasattr ( settings , 'PUBLIC_SCHEMA_URLCONF' ) :
if ( settings . PUBLIC_SCHEMA_URLCONF and url_string . startswith ( settings . PUBLIC_SCHEMA_URLCONF ) ) :
url_string = url_string [ len ( settings . PUBLIC_SCHEMA_URLCONF ) : ]
return url_string |
def find ( cls , paths ) :
"""Given a list of files or directories , try to detect python interpreters amongst them .
Returns a list of PythonInterpreter objects .""" | pythons = [ ]
for path in paths :
for fn in cls . expand_path ( path ) :
basefile = os . path . basename ( fn )
if cls . _matches_binary_name ( basefile ) :
try :
pythons . append ( cls . from_binary ( fn ) )
except Exception as e :
TRACER . lo... |
def _auto_wait_for_status ( self , message = None , exclude_services = None , include_only = None , timeout = None ) :
"""Wait for all units to have a specific extended status , except
for any defined as excluded . Unless specified via message , any
status containing any case of ' ready ' will be considered a m... | if not timeout :
timeout = int ( os . environ . get ( 'AMULET_SETUP_TIMEOUT' , 1800 ) )
self . log . info ( 'Waiting for extended status on units for {}s...' '' . format ( timeout ) )
all_services = self . d . services . keys ( )
if exclude_services and include_only :
raise ValueError ( 'exclude_services can no... |
def abup_se_plot ( mod , species ) :
"""plot species from one ABUPP file and the se file .
You must use this function in the directory where the ABP files
are and an ABUP file for model mod must exist .
Parameters
mod : integer
Model to plot , you need to have an ABUPP file for that
model .
species : ... | # Marco , you have already implemented finding headers and columns in
# ABUP files . You may want to transplant that into here ?
species = 'C-12'
filename = 'ABUPP%07d0000.DAT' % mod
print ( filename )
mass , c12 = np . loadtxt ( filename , skiprows = 4 , usecols = [ 1 , 18 ] , unpack = True )
c12_se = self . se . get ... |
def threshold_brier_score ( observations , forecasts , threshold , issorted = False , axis = - 1 ) :
"""Calculate the Brier scores of an ensemble for exceeding given thresholds .
According to the threshold decomposition of CRPS , the resulting Brier
scores can thus be summed along the last axis to calculate CRP... | observations = np . asarray ( observations )
threshold = np . asarray ( threshold )
forecasts = np . asarray ( forecasts )
if axis != - 1 :
forecasts = move_axis_to_end ( forecasts , axis )
if forecasts . shape == observations . shape :
forecasts = forecasts [ ... , np . newaxis ]
if observations . shape != for... |
def submit_async_work_chain ( self , work_chain , workunit_parent , done_hook = None ) :
"""Submit work to be executed in the background .
- work _ chain : An iterable of Work instances . Will be invoked serially . Each instance may
have a different cardinality . There is no output - input chaining : the argume... | def done ( ) :
if done_hook :
done_hook ( )
with self . _pending_workchains_cond :
self . _pending_workchains -= 1
self . _pending_workchains_cond . notify ( )
def error ( e ) :
done ( )
self . _run_tracker . log ( Report . ERROR , '{}' . format ( e ) )
# We filter out Nones defe... |
def crop_at_zero_crossing ( gen , seconds = 5 , error = 0.1 ) :
'''Crop the generator , ending at a zero - crossing
Crop the generator to produce approximately seconds seconds
( default 5s ) of audio at the provided FRAME _ RATE , attempting
to end the clip at a zero crossing point to avoid clicking .''' | source = iter ( gen )
buffer_length = int ( 2 * error * sampler . FRAME_RATE )
# split the source into two iterators :
# - start , which contains the bulk of the sound clip
# - and end , which contains the final 100ms , plus 100ms past
# the desired clip length . We may cut the clip anywhere
# within this + / - 100ms e... |
def main ( ) :
"""Sample usage for this python module
This main method simply illustrates sample usage for this python
module .
: return : None""" | log = logging . getLogger ( Logify . get_name ( ) + '.logify.main' )
log . info ( 'logger name is: %s' , Logify . get_name ( ) )
log . debug ( 'This is DEBUG' )
log . info ( 'This is INFO' )
log . warning ( 'This is a WARNING' )
log . error ( 'This is an ERROR' ) |
def confirm_tell ( self , data , success ) :
"""Confirm that you ' ve done as you were told . Call this from your control callback to confirm action .
Used when you are advertising a control and you want to tell the remote requestor that you have
done what they asked you to .
` Example : ` this is a minimal e... | logger . info ( "confirm_tell(success=%s) [lid=\"%s\",pid=\"%s\"]" , success , data [ P_ENTITY_LID ] , data [ P_LID ] )
evt = self . _request_point_confirm_tell ( R_CONTROL , data [ P_ENTITY_LID ] , data [ P_LID ] , success , data [ 'requestId' ] )
self . _wait_and_except_if_failed ( evt ) |
def xstep ( self ) :
r"""Minimise Augmented Lagrangian with respect to block vector
: math : ` \ mathbf { x } = \ left ( \ begin { array } { ccc } \ mathbf { x } _ 0 ^ T &
\ mathbf { x } _ 1 ^ T & \ ldots \ end { array } \ right ) ^ T \ ; ` .""" | # This test reflects empirical evidence that two slightly
# different implementations are faster for single or
# multi - channel data . This kludge is intended to be temporary .
if self . cri . Cd > 1 :
for i in range ( self . Nb ) :
self . xistep ( i )
else :
self . YU [ : ] = self . Y [ ... , np . new... |
def infer_schema ( self , stream , namespace = None ) :
"""Queries the Kronos server and fetches the inferred schema for the
requested stream .""" | return self . _make_request ( self . _infer_schema_url , data = { 'stream' : stream , 'namespace' : namespace or self . namespace } ) |
def _collectOffAxisPoints ( self ) :
"""Return a dictionary with all off - axis locations .""" | offAxis = { }
for l , ( value , deltaName ) in self . items ( ) :
location = Location ( l )
name = location . isOnAxis ( )
if name is None or name is False :
offAxis [ l ] = 1
return list ( offAxis . keys ( ) ) |
def find_collisions ( Signal , tolerance = 50 ) :
"""Finds collision events in the signal from the shift in phase of the signal .
Parameters
Signal : array _ like
Array containing the values of the signal of interest containing a single frequency .
tolerance : float
Percentage tolerance , if the value of ... | fmd = fm_discriminator ( Signal )
mean_fmd = _np . mean ( fmd )
Collisions = [ _is_this_a_collision ( [ value , mean_fmd , tolerance ] ) for value in fmd ]
return Collisions |
def parse ( self , filename_or_file , initialize = True ) :
"""Load manifest from file or file object""" | if isinstance ( filename_or_file , ( str , unicode ) ) :
filename = filename_or_file
else :
filename = filename_or_file . name
try :
domtree = minidom . parse ( filename_or_file )
except xml . parsers . expat . ExpatError , e :
args = [ e . args [ 0 ] ]
if isinstance ( filename , unicode ) :
... |
def _populate_domain ( self ) :
'''Populate TrustDomain ' s domain attribute .
This entails an inspection of each device ' s certificate - authority
devices in its trust domain and recording them . After which , we
get a dictionary of who trusts who in the domain .''' | self . domain = { }
for device in self . devices :
device_name = get_device_info ( device ) . name
ca_devices = device . tm . cm . trust_domains . trust_domain . load ( name = 'Root' ) . caDevices
self . domain [ device_name ] = [ d . replace ( '/%s/' % self . partition , '' ) for d in ca_devices ] |
def _iter_straight_packed ( self , byte_blocks ) :
"""Iterator that undoes the effect of filtering ;
yields each row as a sequence of packed bytes .
Assumes input is straightlaced .
` byte _ blocks ` should be an iterable that yields the raw bytes
in blocks of arbitrary size .""" | # length of row , in bytes
rb = self . row_bytes
a = bytearray ( )
# The previous ( reconstructed ) scanline .
# None indicates first line of image .
recon = None
for some_bytes in byte_blocks :
a . extend ( some_bytes )
while len ( a ) >= rb + 1 :
filter_type = a [ 0 ]
scanline = a [ 1 : rb + 1... |
def _tr_above ( self ) :
"""The tr element prior in sequence to the tr this cell appears in .
Raises | ValueError | if called on a cell in the top - most row .""" | tr_lst = self . _tbl . tr_lst
tr_idx = tr_lst . index ( self . _tr )
if tr_idx == 0 :
raise ValueError ( 'no tr above topmost tr' )
return tr_lst [ tr_idx - 1 ] |
def get_worker_node_ips ( config_file , override_cluster_name ) :
"""Returns worker node IPs for given configuration file .""" | config = yaml . load ( open ( config_file ) . read ( ) )
if override_cluster_name is not None :
config [ "cluster_name" ] = override_cluster_name
provider = get_node_provider ( config [ "provider" ] , config [ "cluster_name" ] )
try :
nodes = provider . non_terminated_nodes ( { TAG_RAY_NODE_TYPE : "worker" } )
... |
def parse_set ( string ) :
"""Parse set from comma separated string .""" | string = string . strip ( )
if string :
return set ( string . split ( "," ) )
else :
return set ( ) |
def _load_info ( self ) :
"""This functions stores the id and the username of the bot .
Called by ` . username ` and ` . id ` properties .
: return :""" | myself = self . get_me ( )
if self . return_python_objects :
self . _id = myself . id
self . _username = myself . username
else :
self . _id = myself [ "result" ] [ "id" ]
self . _username = myself [ "result" ] [ "username" ] |
def is_volatile ( self ) :
"""True if combination of field access properties result in a field that
should be interpreted as volatile .
( Any hardware - writable field is inherently volatile )""" | hw = self . get_property ( 'hw' )
return ( ( hw in ( rdltypes . AccessType . rw , rdltypes . AccessType . rw1 , rdltypes . AccessType . w , rdltypes . AccessType . w1 ) ) or self . get_property ( 'counter' ) or ( self . get_property ( 'next' ) is not None ) or self . get_property ( 'hwset' ) or self . get_property ( 'h... |
def process_filter_args ( cls , kwargs ) :
"""loop through properties in filter parameters check they match class definition
deflate them and convert into something easy to generate cypher from""" | output = { }
for key , value in kwargs . items ( ) :
if '__' in key :
prop , operator = key . rsplit ( '__' )
operator = OPERATOR_TABLE [ operator ]
else :
prop = key
operator = '='
if prop not in cls . defined_properties ( rels = False ) :
raise ValueError ( "No such... |
def take_off ( self , height = DEFAULT , velocity = DEFAULT ) :
"""Takes off , that is starts the motors , goes straight up and hovers .
Do not call this function if you use the with keyword . Take off is
done automatically when the context is created .
: param height : the height ( meters ) to hover at . Non... | if self . _is_flying :
raise Exception ( 'Already flying' )
if not self . _cf . is_connected ( ) :
raise Exception ( 'Crazyflie is not connected' )
self . _is_flying = True
self . _reset_position_estimator ( )
self . _activate_controller ( )
self . _activate_high_level_commander ( )
self . _hl_commander = self ... |
async def start_worker ( self , cmd : List [ str ] , input_source : str , output : Optional [ str ] = None , extra_cmd : Optional [ str ] = None , pattern : Optional [ str ] = None , reading : str = FFMPEG_STDERR , ) -> None :
"""Start ffmpeg do process data from output .""" | if self . is_running :
_LOGGER . warning ( "Can't start worker. It is allready running!" )
return
if reading == FFMPEG_STDERR :
stdout = False
stderr = True
else :
stdout = True
stderr = False
# start ffmpeg and reading to queue
await self . open ( cmd = cmd , input_source = input_source , outpu... |
def spawn ( cls , options = None , dir_base = None ) :
"""Alternative constructor . Creates a mutator and returns section object .
: param dict options :
: param str | unicode dir _ base :
: rtype : SectionMutator""" | from uwsgiconf . utils import ConfModule
options = options or { 'compile' : True , }
dir_base = os . path . abspath ( dir_base or find_project_dir ( ) )
name_module = ConfModule . default_name
name_project = get_project_name ( dir_base )
path_conf = os . path . join ( dir_base , name_module )
if os . path . exists ( pa... |
def digest ( algorithm = DEFAULT_HASH_ALGORITHM , hash_library = DEFAULT_HASH_LIBRARY ) :
"""< Purpose >
Provide the caller with the ability to create digest objects without having
to worry about crypto library availability or which library to use . The
caller also has the option of specifying which hash algo... | # Are the arguments properly formatted ? If not , raise
# ' securesystemslib . exceptions . FormatError ' .
securesystemslib . formats . NAME_SCHEMA . check_match ( algorithm )
securesystemslib . formats . NAME_SCHEMA . check_match ( hash_library )
# Was a hashlib digest object requested and is it supported ?
# If so ,... |
def parser ( self ) :
"""Creates a parser for the method based on the documentation .
: return < OptionParser >""" | usage = self . usage ( )
if self . __doc__ :
usage += '\n' + nstr ( self . __doc__ )
parse = PARSER_CLASS ( usage = usage )
shorts = { v : k for k , v in self . short_keys . items ( ) }
for key , default in self . cmd_opts . items ( ) : # default key , cannot be duplicated
if key == 'help' :
continue
... |
def finish ( self , key1set , key2set , mask = True ) :
"""Returns ( weights , means , variances ) , where :
weights
ndarray of number of samples per key ; shape ( n1 , n2 ) , where n1 is the
size of key1set and n2 is the size of key2set .
means
computed mean value for each key
variances
computed vari... | n1_us = len ( self . _key1map )
n2_us = len ( self . _key2map )
wt_us = self . _m0 [ : n1_us , : n2_us ]
badwt = ( wt_us == 0 ) | ~ np . isfinite ( wt_us )
wt_us [ badwt ] = 1
mean_us = self . _m1 [ : n1_us , : n2_us ] / wt_us
var_us = self . _m2 [ : n1_us , : n2_us ] / wt_us - mean_us ** 2
wt_us [ badwt ] = 0
mean_us ... |
def activated ( self , value ) :
"""Setter for * * self . _ _ activated * * 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 ( "activated" , value )
self . component_activated . emit ( ) if value else self . component_deactivated . emit ( )
self . __activated = value |
def add_weight ( self , weight ) :
"""stub""" | if weight is None :
raise NullArgument ( 'weight cannot be None' )
if not self . my_osid_object_form . _is_valid_decimal ( weight , self . get_weight_metadata ( ) ) :
raise InvalidArgument ( 'weight' )
self . my_osid_object_form . _my_map [ 'weight' ] = weight |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.