signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _calculate_session_expiry ( self , request , user_info ) :
"""Returns the number of seconds after which the Django session should expire .""" | access_token_expiry_timestamp = self . _get_access_token_expiry ( request )
id_token_expiry_timestamp = self . _get_id_token_expiry ( user_info )
now_in_seconds = int ( time . time ( ) )
# The session length is set to match whichever token expiration time is closer .
earliest_expiration_timestamp = min ( access_token_e... |
def send_messages ( self , request , queryset , bulk = False ) :
"""Provides error handling for DeviceAdmin send _ message and send _ bulk _ message methods .""" | ret = [ ]
errors = [ ]
r = ""
for device in queryset :
try :
if bulk :
r = queryset . send_message ( "Test bulk notification" )
else :
r = device . send_message ( "Test single notification" )
if r :
ret . append ( r )
except GCMError as e :
err... |
def get_signature_challenge ( self ) :
"""Returns new signature challenge""" | devices = [ DeviceRegistration . wrap ( device ) for device in self . __get_u2f_devices ( ) ]
if devices == [ ] :
return { 'status' : 'failed' , 'error' : 'No devices been associated with the account!' }
challenge = start_authenticate ( devices )
challenge [ 'status' ] = 'ok'
session [ '_u2f_challenge_' ] = challen... |
def new ( self , items : Iterator , processor : PreProcessors = None , ** kwargs ) -> 'ItemList' :
"Create a new ` ItemList ` from ` items ` , keeping the same attributes ." | processor = ifnone ( processor , self . processor )
copy_d = { o : getattr ( self , o ) for o in self . copy_new }
kwargs = { ** copy_d , ** kwargs }
return self . __class__ ( items = items , processor = processor , ** kwargs ) |
def handle_response ( response ) :
"""Given a requests . Response object , throw the appropriate exception , if applicable .""" | # ignore valid responses
if response . status_code < 400 :
return
cls = _status_to_exception_type . get ( response . status_code , HttpError )
kwargs = { 'code' : response . status_code , 'method' : response . request . method , 'url' : response . request . url , 'details' : response . text , }
if response . header... |
def find_by_workspace ( self , workspace , params = { } , ** options ) :
"""Returns the compact tag records for all tags in the workspace .
Parameters
workspace : { Id } The workspace or organization to find tags in .
[ params ] : { Object } Parameters for the request""" | path = "/workspaces/%s/tags" % ( workspace )
return self . client . get_collection ( path , params , ** options ) |
async def get_devices ( self ) :
"""Get the local installed version .""" | data = await self . api ( "devices" )
if self . connected and self . authenticated :
self . _devices = data
else :
self . _devices = self . _devices
_LOGGER . debug ( self . _devices ) |
def _filter_keywords ( function , kwargs_dict , is_class = False , warn_print = True ) :
"""Brief
Function for filtering kwargs , ensuring that invalid keywords are not passed as arguments .
Description
Many Python functions included in the major packages , include in their definition some
keyword arguments... | # % % % % % List of keywords of our input function % % % % %
if is_class is False :
list_of_keywords = list ( signature ( function ) . parameters . keys ( ) )
else :
list_of_keywords = list ( function . __dict__ . keys ( ) )
# % % List of keywords passed in * * kwargs that match the valid keywords of the input ... |
def sample ( self , nsims = 1000 ) :
"""Samples from the posterior predictive distribution
Parameters
nsims : int ( default : 1000)
How many draws from the posterior predictive distribution
Returns
- np . ndarray of draws from the data""" | if self . latent_variables . estimation_method not in [ 'BBVI' , 'M-H' ] :
raise Exception ( "No latent variables estimated!" )
else :
lv_draws = self . draw_latent_variables ( nsims = nsims )
mus = [ ]
for i in range ( nsims ) :
mu , V = self . smoothed_state ( self . data , lv_draws [ : , i ] ... |
def p_pointer ( self , p ) :
'pointer : identifier LBRACKET expression RBRACKET' | p [ 0 ] = Pointer ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 1 ) )
p . set_lineno ( 0 , p . lineno ( 1 ) ) |
def obj_update_or_create ( model , defaults = None , update_fields = UNSET , ** kwargs ) :
"""Mimic queryset . update _ or _ create but using obj _ update .""" | obj , created = model . objects . get_or_create ( defaults = defaults , ** kwargs )
if created :
logger . debug ( 'CREATED %s %s' , model . _meta . object_name , obj . pk , extra = { 'pk' : obj . pk } )
else :
obj_update ( obj , defaults , update_fields = update_fields )
return obj , created |
def help_center_user_articles ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / help _ center / articles # list - articles" | api_path = "/api/v2/help_center/users/{id}/articles.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def ped_parser ( self , family_info ) :
"""Parse . ped formatted family info .
Add all family info to the parser object
Arguments :
family _ info ( iterator ) : An iterator with family info""" | for line in family_info : # Check if commented line or empty line :
if not line . startswith ( '#' ) and not all ( c in whitespace for c in line . rstrip ( ) ) :
splitted_line = line . rstrip ( ) . split ( '\t' )
if len ( splitted_line ) != 6 : # Try to split the line on another symbol :
... |
def slug ( s , remove_whitespace = True , lowercase = True ) :
"""Condensed version of s , containing only lowercase alphanumeric characters .""" | res = '' . join ( c for c in unicodedata . normalize ( 'NFD' , s ) if unicodedata . category ( c ) != 'Mn' )
if lowercase :
res = res . lower ( )
for c in string . punctuation :
res = res . replace ( c , '' )
res = re . sub ( '\s+' , '' if remove_whitespace else ' ' , res )
res = res . encode ( 'ascii' , 'ignor... |
def visit_num ( self , node , parent ) :
"""visit a Num node by returning a fresh instance of Const""" | return nodes . Const ( node . n , getattr ( node , "lineno" , None ) , getattr ( node , "col_offset" , None ) , parent , ) |
def get_inputmode_fragments ( python_input ) :
"""Return current input mode as a list of ( token , text ) tuples for use in a
toolbar .""" | app = get_app ( )
@ if_mousedown
def toggle_vi_mode ( mouse_event ) :
python_input . vi_mode = not python_input . vi_mode
token = 'class:status-toolbar'
input_mode_t = 'class:status-toolbar.input-mode'
mode = app . vi_state . input_mode
result = [ ]
append = result . append
append ( ( input_mode_t , '[F4] ' , toggl... |
def sg_squeeze ( tensor , opt ) :
r"""Removes axis of size 1 from the shape of a tensor .
See ` tf . squeeze ( ) ` in tensorflow .
Args :
tensor : A ` Tensor ` ( automatically given by chain ) .
opt :
axis : A tuple / list of integers or an integer .
axis to remove . Default is - 1.
name : If provided... | opt += tf . sg_opt ( axis = [ - 1 ] )
opt . axis = opt . axis if isinstance ( opt . axis , ( tuple , list ) ) else [ opt . axis ]
return tf . squeeze ( tensor , opt . axis , name = opt . name ) |
def ContainsAll ( self , * values ) :
"""Sets the type of the WHERE clause as " contains all " .
Args :
* values : The values to be used in the WHERE condition .
Returns :
The query builder that this WHERE builder links to .""" | self . _awql = self . _CreateMultipleValuesCondition ( values , 'CONTAINS_ALL' )
return self . _query_builder |
def process_default ( self , event ) :
"""Fallback .""" | if self . job . LOG . isEnabledFor ( logging . DEBUG ) : # On debug level , we subscribe to ALL events , so they ' re expected in that case ; )
if self . job . config . trace_inotify :
self . job . LOG . debug ( "Ignored inotify event:\n %r" % event )
else :
self . job . LOG . warning ( "Unexpected i... |
def chain_tasks ( tasks ) :
"""Chain given tasks . Set each task to run after its previous task .
: param tasks : Tasks list .
: return : Given tasks list .""" | # If given tasks list is not empty
if tasks : # Previous task
previous_task = None
# For given tasks list ' s each task
for task in tasks : # If the task is not None .
# Task can be None to allow code like ` ` task if _ PY2 else None ` ` .
if task is not None : # If previous task is not None
... |
def render ( self , name , value , attrs = None ) :
if value is None :
value = ''
value = smart_unicode ( value )
final_attrs = self . build_attrs ( attrs )
final_attrs [ 'name' ] = name
assert 'id' in final_attrs , "TinyMCE widget attributes must contain 'id'"
mce_config = cms . plugins... | json = simplejson . dumps ( mce_config )
html = [ u'<textarea%s>%s</textarea>' % ( flatatt ( final_attrs ) , escape ( value ) ) ]
if tinymce . settings . USE_COMPRESSOR :
compressor_config = { 'plugins' : mce_config . get ( 'plugins' , '' ) , 'themes' : mce_config . get ( 'theme' , 'advanced' ) , 'languages' : mce_... |
def build_from_queue ( cls , input_queue , replay_size , batch_size ) :
"""Builds a ` ReplayableQueue ` that draws from a regular ` input _ queue ` .
Args :
input _ queue : The queue to draw from .
replay _ size : The size of the replay buffer .
batch _ size : The size of each batch .
Returns :
A Replay... | return cls ( lambda : input_queue . dequeue_many ( batch_size ) , replay_size , batch_size = batch_size ) |
def format ( collection , ** params ) :
"""Truns a python object into a ZIP file .""" | binary = io . BytesIO ( )
with zipfile . ZipFile ( binary , 'w' ) as zip_ :
now = datetime . datetime . utcnow ( ) . timetuple ( )
for filename , content in collection :
content_type , encoding = mimetypes . guess_type ( filename )
content = content_types . get ( content_type ) . parse ( content... |
def sg_rnn ( tensor , opt ) :
r"""Applies a simple rnn .
Args :
tensor : A 3 - D ` Tensor ` ( automatically passed by decorator ) .
opt :
in _ dim : A positive ` integer ` . The size of input dimension .
dim : A positive ` integer ` . The size of output dimension .
bias : Boolean . If True , biases are ... | # layer normalization
# noinspection PyPep8
ln = lambda v : _ln_rnn ( v , gamma , beta ) if opt . ln else v
# step function
def step ( hh , x ) : # simple rnn
y = ln ( tf . matmul ( x , w ) + tf . matmul ( hh , u ) + ( b if opt . bias else 0 ) )
return y
# parameter initialize
w = tf . sg_initializer . orthogon... |
def data ( self ) -> Tensor :
"Return the points associated to this object ." | flow = self . flow
# This updates flow before we test if some transforms happened
if self . transformed :
if 'remove_out' not in self . sample_kwargs or self . sample_kwargs [ 'remove_out' ] :
flow = _remove_points_out ( flow )
self . transformed = False
return flow . flow . flip ( 1 ) |
def remove_sid2sub ( self , sid , sub ) :
"""Remove the connection between a session ID and a Subject
: param sid : Session ID
: param sub : Subject identifier""" | self . remove ( 'sub2sid' , sub , sid )
self . remove ( 'sid2sub' , sid , sub ) |
def clock_in ( request ) :
"""For clocking the user into a project .""" | user = request . user
# Lock the active entry for the duration of this transaction , to prevent
# creating multiple active entries .
active_entry = utils . get_active_entry ( user , select_for_update = True )
initial = dict ( [ ( k , v ) for k , v in request . GET . items ( ) ] )
data = request . POST or None
form = Cl... |
def construct_kde ( samples_array , use_kombine = False ) :
"""Constructs a KDE from the given samples .""" | if use_kombine :
try :
import kombine
except ImportError :
raise ImportError ( "kombine is not installed." )
# construct the kde
if use_kombine :
kde = kombine . clustered_kde . KDE ( samples_array )
else :
kde = scipy . stats . gaussian_kde ( samples_array . T )
return kde |
def split_docstring ( self , block ) :
"""Split a code block into a docstring and a body .""" | try :
first_line , rest_of_lines = block . split ( "\n" , 1 )
except ValueError :
pass
else :
raw_first_line = split_leading_trailing_indent ( rem_comment ( first_line ) ) [ 1 ]
if match_in ( self . just_a_string , raw_first_line ) :
return first_line , rest_of_lines
return None , block |
def create_cluster ( self , project_id , region , cluster , request_id = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Creates a cluster in a project .
Example :
> > > from google . cloud import dataproc _ v1... | # Wrap the transport method to add retry and timeout logic .
if "create_cluster" not in self . _inner_api_calls :
self . _inner_api_calls [ "create_cluster" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . create_cluster , default_retry = self . _method_configs [ "CreateCluster" ] . retr... |
def resetAndRejoin ( self , timeout ) :
"""reset and join back Thread Network with a given timeout delay
Args :
timeout : a timeout interval before rejoin Thread Network
Returns :
True : successful to reset and rejoin Thread Network
False : fail to reset and rejoin the Thread Network""" | print '%s call resetAndRejoin' % self . port
print timeout
try :
if self . __sendCommand ( WPANCTL_CMD + 'setprop Daemon:AutoAssociateAfterReset false' ) [ 0 ] != 'Fail' :
time . sleep ( 0.5 )
if self . __sendCommand ( WPANCTL_CMD + 'reset' ) [ 0 ] != 'Fail' :
self . isPowerDown = True
... |
def reorder_release_entries ( releases ) :
"""Mutate ` ` releases ` ` so the entrylist in each is ordered by feature / bug / etc .""" | order = { 'feature' : 0 , 'bug' : 1 , 'support' : 2 }
for release in releases :
entries = release [ 'entries' ] [ : ]
release [ 'entries' ] = sorted ( entries , key = lambda x : order [ x . type ] ) |
def already_resolved ( self , pattern : QueryTriple ) -> bool :
"""Determine whether pattern has already been loaded into the cache .
The " wild card " - ` ( None , None , None ) ` - always counts as resolved .
: param pattern : pattern to check
: return : True it is a subset of elements already loaded""" | if self . sparql_locked or pattern == ( None , None , None ) :
return True
for resolved_node in self . resolved_nodes :
if resolved_node != ( None , None , None ) and ( pattern [ 0 ] == resolved_node [ 0 ] or resolved_node [ 0 ] is None ) and ( pattern [ 1 ] == resolved_node [ 1 ] or resolved_node [ 1 ] is None... |
def sma ( arg , n ) :
"""If n is 0 then return the ltd mean ; else return the n day mean""" | if n == 0 :
return pd . expanding_mean ( arg )
else :
return pd . rolling_mean ( arg , n , min_periods = n ) |
def update_device_info ( self , device_id , display_name ) :
"""Update the display name of a device .
Args :
device _ id ( str ) : The device ID of the device to update .
display _ name ( str ) : New display name for the device .""" | content = { "display_name" : display_name }
return self . _send ( "PUT" , "/devices/%s" % device_id , content = content ) |
def thermodynamic_integration_log_evidence ( betas , logls ) :
"""Thermodynamic integration estimate of the evidence .
: param betas : The inverse temperatures to use for the quadrature .
: param logls : The mean log - likelihoods corresponding to ` ` betas ` ` to use for
computing the thermodynamic evidence ... | if len ( betas ) != len ( logls ) :
raise ValueError ( 'Need the same number of log(L) values as temperatures.' )
order = np . argsort ( betas ) [ : : - 1 ]
betas = betas [ order ]
logls = logls [ order ]
betas0 = np . copy ( betas )
if betas [ - 1 ] != 0 :
betas = np . concatenate ( ( betas0 , [ 0 ] ) )
be... |
def __search_document ( self , document , pattern , settings ) :
"""Searches for given pattern occurrences in given document using given settings .
: param document : Document .
: type document : QTextDocument
: param pattern : Pattern .
: type pattern : unicode
: param settings : Search settings .
: ty... | pattern = settings . regular_expressions and QRegExp ( pattern ) or pattern
flags = QTextDocument . FindFlags ( )
if settings . case_sensitive :
flags = flags | QTextDocument . FindCaseSensitively
if settings . whole_word :
flags = flags | QTextDocument . FindWholeWords
occurrences = [ ]
block = document . find... |
def register_token_network ( self , token_registry_abi : Dict , token_registry_address : str , token_address : str , channel_participant_deposit_limit : Optional [ int ] , token_network_deposit_limit : Optional [ int ] , ) :
"""Register token with a TokenNetworkRegistry contract .""" | with_limits = contracts_version_expects_deposit_limits ( self . contracts_version )
if with_limits :
return self . _register_token_network_with_limits ( token_registry_abi , token_registry_address , token_address , channel_participant_deposit_limit , token_network_deposit_limit , )
else :
return self . _registe... |
def fit ( self , X , y , sample_weight = None , eval_set = None , eval_metric = None , early_stopping_rounds = None , verbose = True , xgb_model = None , sample_weight_eval_set = None , callbacks = None ) : # pylint : disable = missing - docstring , invalid - name , attribute - defined - outside - init
"""Fit the g... | if sample_weight is not None :
trainDmatrix = DMatrix ( X , label = y , weight = sample_weight , missing = self . missing , nthread = self . n_jobs )
else :
trainDmatrix = DMatrix ( X , label = y , missing = self . missing , nthread = self . n_jobs )
evals_result = { }
if eval_set is not None :
if sample_we... |
def _levenshtein_distance ( s1 , s2 ) :
""": param s1 : A list or string
: param s2 : Another list or string
: returns : The levenshtein distance between the two""" | if len ( s1 ) > len ( s2 ) :
s1 , s2 = s2 , s1
distances = range ( len ( s1 ) + 1 )
for index2 , num2 in enumerate ( s2 ) :
new_distances = [ index2 + 1 ]
for index1 , num1 in enumerate ( s1 ) :
if num1 == num2 :
new_distances . append ( distances [ index1 ] )
else :
... |
def call_func ( self , * args , ** kwargs ) :
"""Called . Take care of exceptions using gather""" | asyncio . gather ( self . cron ( * args , ** kwargs ) , loop = self . loop , return_exceptions = True ) . add_done_callback ( self . set_result ) |
def iso_write ( self , dev_handle , ep , intf , data , timeout ) :
r"""Perform an isochronous write .
dev _ handle is the value returned by the open _ device ( ) method .
The ep parameter is the bEndpointAddress field whose endpoint
the data will be sent to . intf is the bInterfaceNumber field
of the interf... | _not_implemented ( self . iso_write ) |
def single_val ( self ) :
"""return relative error of worst point that might make the data none
symmetric .""" | sv_t = self . _sv ( self . _tdsphere )
sv_p = self . _sv ( self . _tdsphere )
return ( sv_t , sv_p ) |
def selections ( self ) :
"Yields ( column , lookup , value ) tuples" | for key , value in self . pairs :
if '__' in key :
column , lookup = key . rsplit ( '__' , 1 )
else :
column = key
lookup = 'exact'
yield column , lookup , value |
def _set_cspf_group_node ( self , v , load = False ) :
"""Setter method for cspf _ group _ node , mapped from YANG variable / mpls _ config / router / mpls / mpls _ cmds _ holder / cspf _ group / cspf _ group _ node ( list )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = YANGListType ( "cspf_group_node_ip" , cspf_group_node . cspf_group_node , yang_name = "cspf-group-node" , rest_name = "node" , parent = self , is_container = 'list' , user_ordered = False , path_helper = self . _path_helper ,... |
def iterpaths ( self ) :
"""Yield all WinFile ' s absolute path .""" | try :
for path in self . order :
yield path
except :
for path in self . files :
yield path |
def boolean ( _object ) :
"""Validates a given input is of type boolean .
Example usage : :
data = { ' a ' : True }
schema = ( ' a ' , boolean )
You can also use this as a decorator , as a way to check for the
input before it even hits a validator you may be writing .
. . note : :
If the argument is a... | if is_callable ( _object ) :
_validator = _object
@ wraps ( _validator )
def decorated ( value ) :
ensure ( isinstance ( value , bool ) , "not of type boolean" )
return _validator ( value )
return decorated
ensure ( isinstance ( _object , bool ) , "not of type boolean" ) |
def openid_associate ( self , request ) :
"""Handle and respond to C { associate } requests .
@ returntype : L { OpenIDResponse }""" | # XXX : TESTME
assoc_type = request . assoc_type
session_type = request . session . session_type
if self . negotiator . isAllowed ( assoc_type , session_type ) :
assoc = self . signatory . createAssociation ( dumb = False , assoc_type = assoc_type )
return request . answer ( assoc )
else :
message = ( 'Asso... |
def _get_image_tensors ( self ) -> ( [ Tensor ] , [ Tensor ] , [ Tensor ] ) :
"Gets list of image tensors from lists of Image objects , as a tuple of original , generated and real ( target ) images ." | orig_images , gen_images , real_images = [ ] , [ ] , [ ]
for image_set in self . image_sets :
orig_images . append ( image_set . orig . px )
gen_images . append ( image_set . gen . px )
real_images . append ( image_set . real . px )
return orig_images , gen_images , real_images |
def arccalibration ( wv_master , xpos_arc , naxis1_arc , crpix1 , wv_ini_search , wv_end_search , wvmin_useful , wvmax_useful , error_xpos_arc , times_sigma_r , frac_triplets_for_sum , times_sigma_theil_sen , poly_degree_wfit , times_sigma_polfilt , times_sigma_cook , times_sigma_inclusion , geometry = None , debugplot... | ntriplets_master , ratios_master_sorted , triplets_master_sorted_list = gen_triplets_master ( wv_master = wv_master , geometry = geometry , debugplot = debugplot )
list_of_wvfeatures = arccalibration_direct ( wv_master = wv_master , ntriplets_master = ntriplets_master , ratios_master_sorted = ratios_master_sorted , tri... |
def ip_monitor ( self , query , days_back = 0 , page = 1 , ** kwargs ) :
"""Pass in the IP Address you wish to query ( i . e . 199.30.228.112 ) .""" | return self . _results ( 'ip-monitor' , '/v1/ip-monitor' , query = query , days_back = days_back , page = page , items_path = ( 'alerts' , ) , ** kwargs ) |
def stop_supporting_containers ( get_container_name , extra_containers ) :
"""Stop postgres and solr containers , along with any specified extra containers""" | docker . remove_container ( get_container_name ( 'postgres' ) )
docker . remove_container ( get_container_name ( 'solr' ) )
for container in extra_containers :
docker . remove_container ( get_container_name ( container ) ) |
def download ( self , paths , tool , language ) :
"""Download subtitles via a number of tools .""" | if tool not in self . available :
fatal ( '{!r} is not installed' . format ( tool ) )
try :
from . import plugins
downloader = plugins . __getattribute__ ( tool )
except AttributeError :
fatal ( '{!r} is not a supported download tool' . format ( tool ) )
try :
if downloader . __code__ . co_argcount ... |
def crop_square ( im , r , c , sz ) :
'''crop image into a square of size sz ,''' | return im [ r : r + sz , c : c + sz ] |
def turn_left ( ) :
"""turns RedBot to the Left""" | motors . left_motor ( 150 )
# spin CCW
motors . right_motor ( 150 )
# spin CCW
board . sleep ( 0.5 )
motors . brake ( ) ;
board . sleep ( 0.1 ) |
def GetServiceObj ( self , servicename ) :
"""Given a service name string , returns
the object that corresponds to the service""" | for sobj in self . services :
if sobj . GetName ( ) . lower ( ) == servicename . lower ( ) :
return sobj
return None |
def update ( self , id , ** kwargs ) :
"""Updates an existing License
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the response .
> > > def callback _ function ( response ) :
> > > pprint... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . update_with_http_info ( id , ** kwargs )
else :
( data ) = self . update_with_http_info ( id , ** kwargs )
return data |
def fnr ( y , z ) :
"""False negative rate ` fn / ( fn + tp ) `""" | tp , tn , fp , fn = contingency_table ( y , z )
return fn / ( fn + tp ) |
def get_tasks ( self ) :
"""Return tasks as list of ( name , function ) tuples .""" | def predicate ( item ) :
return ( inspect . isfunction ( item ) and item . __name__ not in self . _helper_names )
return inspect . getmembers ( self . _tasks , predicate ) |
def is_cookie_in_driver ( self , cookie ) :
"""We check that the cookie is correctly added to the driver
We only compare name , value and domain , as the rest can produce false negatives .
We are a bit lenient when comparing domains .""" | for driver_cookie in self . get_cookies ( ) :
if ( cookie [ 'name' ] == driver_cookie [ 'name' ] and cookie [ 'value' ] == driver_cookie [ 'value' ] and ( cookie [ 'domain' ] == driver_cookie [ 'domain' ] or '.' + cookie [ 'domain' ] == driver_cookie [ 'domain' ] ) ) :
return True
return False |
def xpending_range ( self , name , groupname , min , max , count , consumername = None ) :
"""Returns information about pending messages , in a range .
name : name of the stream .
groupname : name of the consumer group .
min : minimum stream ID .
max : maximum stream ID .
count : number of messages to ret... | pieces = [ name , groupname ]
if min is not None or max is not None or count is not None :
if min is None or max is None or count is None :
raise DataError ( "XPENDING must be provided with min, max " "and count parameters, or none of them. " )
if not isinstance ( count , ( int , long ) ) or count < - 1... |
def non_empty_lines ( path ) :
"""Yield non - empty lines from file at path""" | with open ( path ) as f :
for line in f :
line = line . strip ( )
if line :
yield line |
def save ( self , output_file , overwrite = False ) :
"""Save the model to disk""" | if os . path . exists ( output_file ) and overwrite is False :
raise ModelFileExists ( "The file %s exists already. If you want to overwrite it, use the 'overwrite=True' " "options as 'model.save(\"%s\", overwrite=True)'. " % ( output_file , output_file ) )
else :
data = self . to_dict_with_types ( )
# Writ... |
def calc_DUP_parameter ( self , modeln , label , fig = 10 , color = 'r' , marker_type = '*' , h_core_mass = False ) :
"""Method to calculate the DUP parameter evolution for different
TPs specified specified by their model number .
Parameters
fig : integer
Figure number to plot .
modeln : list
Array cont... | number_DUP = ( old_div ( len ( modeln ) , 2 ) - 1 )
# START WITH SECOND
try :
h1_bnd_m = self . get ( 'h1_boundary_mass' )
except :
try :
h1_bnd_m = self . get ( 'he_core_mass' )
except :
pass
star_mass = self . get ( 'star_mass' )
age = self . get ( "star_age" )
firstTP = h1_bnd_m [ modeln ... |
def firmware_download_output_fwdl_cmd_status ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
firmware_download = ET . Element ( "firmware_download" )
config = firmware_download
output = ET . SubElement ( firmware_download , "output" )
fwdl_cmd_status = ET . SubElement ( output , "fwdl-cmd-status" )
fwdl_cmd_status . text = kwargs . pop ( 'fwdl_cmd_status' )
callback = kwargs ... |
def main ( ctx , root_project_dir , verbose ) :
"""stack - docs is a CLI for building LSST Stack documentation , such as
pipelines . lsst . io .
This command should be run on the " main " documentation repository , namely
https : / / github . com / lsst / pipelines _ lsst _ io .
The stack - docs command rep... | root_project_dir = discover_conf_py_directory ( root_project_dir )
# Subcommands should use the click . pass _ obj decorator to get this
# ctx . obj object as the first argument .
ctx . obj = { 'root_project_dir' : root_project_dir , 'verbose' : verbose }
# Set up application logging . This ensures that only documentee... |
def setup_args ( self , parser ) :
"""Set up an argparse . ArgumentParser object by adding all the
arguments taken by the function .""" | # Add all the arguments to the argument parser
for args , kwargs in self . _arguments :
parser . add_argument ( * args , ** kwargs ) |
def thaw ( o ) :
"""Recursively convert pyrsistent containers into simple Python containers .
- pvector is converted to list , recursively
- pmap is converted to dict , recursively on values ( but not keys )
- pset is converted to set , but not recursively
- tuple is converted to tuple , recursively .
> >... | if isinstance ( o , PVector ) :
return list ( map ( thaw , o ) )
if isinstance ( o , PMap ) :
return dict ( ( k , thaw ( v ) ) for k , v in o . iteritems ( ) )
if isinstance ( o , PSet ) :
return set ( o )
if type ( o ) is tuple :
return tuple ( map ( thaw , o ) )
return o |
def handle_report_metric_data ( self , data ) :
"""data : a dict received from nni _ manager , which contains :
- ' parameter _ id ' : id of the trial
- ' value ' : metric value reported by nni . report _ final _ result ( )
- ' type ' : report type , support { ' FINAL ' , ' PERIODICAL ' }""" | if data [ 'type' ] == 'FINAL' :
self . _handle_final_metric_data ( data )
elif data [ 'type' ] == 'PERIODICAL' :
if self . assessor is not None :
self . _handle_intermediate_metric_data ( data )
else :
pass
else :
raise ValueError ( 'Data type not supported: {}' . format ( data [ 'type' ... |
def pipe_urlbuilder ( context = None , _INPUT = None , conf = None , ** kwargs ) :
"""A url module that builds a url . Loopable .
Parameters
context : pipe2py . Context object
_ INPUT : pipeforever pipe or an iterable of items or fields
conf : {
' PARAM ' : [
{ ' key ' : { ' value ' : < ' order ' > } , ... | pkwargs = cdicts ( opts , kwargs )
get_params = get_funcs ( conf . get ( 'PARAM' , [ ] ) , ** kwargs ) [ 0 ]
get_paths = get_funcs ( conf . get ( 'PATH' , [ ] ) , ** pkwargs ) [ 0 ]
get_base = get_funcs ( conf [ 'BASE' ] , listize = False , ** pkwargs ) [ 0 ]
parse_params = utils . parse_params
splits = get_splits ( _I... |
def genty ( target_cls ) :
"""This decorator takes the information provided by @ genty _ dataset ,
@ genty _ dataprovider , and @ genty _ repeat and generates the corresponding
test methods .
: param target _ cls :
Test class whose test methods have been decorated .
: type target _ cls :
` class `""" | tests = _expand_tests ( target_cls )
tests_with_datasets = _expand_datasets ( tests )
tests_with_datasets_and_repeats = _expand_repeats ( tests_with_datasets )
_add_new_test_methods ( target_cls , tests_with_datasets_and_repeats )
return target_cls |
def find_duplicate_schedule_items ( all_items ) :
"""Find talks / pages assigned to mulitple schedule items""" | duplicates = [ ]
seen_talks = { }
for item in all_items :
if item . talk and item . talk in seen_talks :
duplicates . append ( item )
if seen_talks [ item . talk ] not in duplicates :
duplicates . append ( seen_talks [ item . talk ] )
else :
seen_talks [ item . talk ] = item
... |
def verify ( self , message , signature , do_hash = True ) :
"""Verifies that message was appropriately signed .
Args :
message ( bytes ) : The message to be verified .
signature ( Signature ) : A signature object .
do _ hash ( bool ) : True if the message should be hashed prior
to signing , False if not ... | msg = get_bytes ( message )
return bitcoin_curve . verify ( msg , signature , self . point , do_hash ) |
def create_recomended_articles ( main_article , article_list ) :
'''Creates recommended article objects from article _ list
and _ prepends _ to existing recommended articles .''' | # store existing recommended articles
existing_recommended_articles = [ ra . recommended_article . specific for ra in main_article . recommended_articles . all ( ) ]
# delete existing recommended articles
ArticlePageRecommendedSections . objects . filter ( page = main_article ) . delete ( )
for hyperlinked_article in a... |
def write_uwsgi_ini_cfg ( fp : t . IO , cfg : dict ) :
"""Writes into IO stream the uwsgi . ini file content ( actually it does smth strange , just look below ) .
uWSGI configs are likely to break INI ( YAML , etc ) specification ( double key definition )
so it writes ` cfg ` object ( dict ) in " uWSGI Style " ... | fp . write ( f'[uwsgi]\n' )
for key , val in cfg . items ( ) :
if isinstance ( val , bool ) :
val = str ( val ) . lower ( )
if isinstance ( val , list ) :
for v in val :
fp . write ( f'{key} = {v}\n' )
continue
fp . write ( f'{key} = {val}\n' ) |
async def is_object_synced_to_cn ( self , client , pid ) :
"""Check if object with { pid } has successfully synced to the CN .
CNRead . describe ( ) is used as it ' s a light - weight HTTP HEAD request .
This assumes that the call is being made over a connection that has
been authenticated and has read or bet... | status = await client . describe ( pid )
if status == 200 :
self . progress_logger . event ( "SciObj already synced on CN" )
return True
elif status == 404 :
self . progress_logger . event ( "SciObj has not synced to CN" )
return False
self . progress_logger . event ( "CNRead.describe() returned unexpec... |
def _timesheets_callback ( self , callback ) :
"""Call a method on all the timesheets , aggregate the return values in a
list and return it .""" | def call ( * args , ** kwargs ) :
return_values = [ ]
for timesheet in self :
attr = getattr ( timesheet , callback )
if callable ( attr ) :
result = attr ( * args , ** kwargs )
else :
result = attr
return_values . append ( result )
return return_value... |
def _calc_sfnr ( volume , mask , ) :
"""Calculate the the SFNR of a volume
Calculates the Signal to Fluctuation Noise Ratio , the mean divided
by the detrended standard deviation of each brain voxel . Based on
Friedman and Glover , 2006
Parameters
volume : 4d array , float
Take a volume time series
ma... | # Make a matrix of brain voxels by time
brain_voxels = volume [ mask > 0 ]
# Take the means of each voxel over time
mean_voxels = np . nanmean ( brain_voxels , 1 )
# Detrend ( second order polynomial ) the voxels over time and then
# calculate the standard deviation .
order = 2
seq = np . linspace ( 1 , brain_voxels . ... |
def put ( self , key , value ) :
'''Stores the object ` value ` named by ` key ` in ` service ` .
Args :
key : Key naming ` value ` .
value : the object to store .''' | key = self . _service_key ( key )
self . _service_ops [ 'put' ] ( key , value ) |
def sqliteRowsToDicts ( sqliteRows ) :
"""Unpacks sqlite rows as returned by fetchall
into an array of simple dicts .
: param sqliteRows : array of rows returned from fetchall DB call
: return : array of dicts , keyed by the column names .""" | return map ( lambda r : dict ( zip ( r . keys ( ) , r ) ) , sqliteRows ) |
def list_datastore_clusters ( kwargs = None , call = None ) :
'''List all the datastore clusters for this VMware environment
CLI Example :
. . code - block : : bash
salt - cloud - f list _ datastore _ clusters my - vmware - config''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The list_datastore_clusters function must be called with ' '-f or --function.' )
return { 'Datastore Clusters' : salt . utils . vmware . list_datastore_clusters ( _get_si ( ) ) } |
def objective ( self , params ) :
"""Compute the negative penalized log - likelihood .""" | val = self . _penalty * np . sum ( params ** 2 )
for winner , losers in self . _data :
idx = np . append ( winner , losers )
val += logsumexp ( params . take ( idx ) - params [ winner ] )
return val |
def diagonal_path ( size ) :
"""Creates a set of diagonal paths moving from the top left to the bottom right of the image .
Successive rows start at the bottom - left corner and move up until the top - right corner .
: param size : The dimensions of the image ( width , height )
: return : A generator that yie... | width , height = size
return ( ( ( x , x + offset ) for x in range ( max ( 0 , - offset ) , min ( width , height - offset ) ) ) for offset in range ( height - 1 , - width , - 1 ) ) |
def ext_from_filename ( filename ) :
"""Scan a filename for it ' s extension .
: param filename : string of the filename
: return : the extension off the end ( empty string if it can ' t find one )""" | try :
base , ext = filename . lower ( ) . rsplit ( "." , 1 )
except ValueError :
return ''
ext = ".{0}" . format ( ext )
all_exts = [ x . extension for x in chain ( magic_header_array , magic_footer_array ) ]
if base [ - 4 : ] . startswith ( "." ) : # For double extensions like like . tar . gz
long_ext = ba... |
def parse_cell ( self , cell , coords , cell_mode = CellMode . cooked ) :
"""Parses a cell according to its cell . value _ type .""" | # pylint : disable = too - many - return - statements
if cell_mode == CellMode . cooked :
if cell . covered or cell . value_type is None or cell . value is None :
return None
vtype = cell . value_type
if vtype == 'string' :
return cell . value
if vtype == 'float' or vtype == 'percentage'... |
def _proxy ( self ) :
"""Generate an instance context for the instance , the context is capable of
performing various actions . All instance actions are proxied to the context
: returns : AssignedAddOnExtensionContext for this AssignedAddOnExtensionInstance
: rtype : twilio . rest . api . v2010 . account . in... | if self . _context is None :
self . _context = AssignedAddOnExtensionContext ( self . _version , account_sid = self . _solution [ 'account_sid' ] , resource_sid = self . _solution [ 'resource_sid' ] , assigned_add_on_sid = self . _solution [ 'assigned_add_on_sid' ] , sid = self . _solution [ 'sid' ] , )
return self... |
def iter_funders ( self ) :
"""Get a converted list of Funders as JSON dict .""" | root = self . doc_root
funders = root . findall ( './skos:Concept' , namespaces = self . namespaces )
for funder in funders :
funder_json = self . fundrefxml2json ( funder )
yield funder_json |
def get_reference_types ( self ) :
"""Return the reference types .
Zotero . item _ types ( ) caches data after the first API call .""" | item_types = self . _zotero_lib . item_types ( )
return sorted ( [ x [ "itemType" ] for x in item_types ] ) |
def index ( config ) : # pragma : no cover
"""Display group info in raw format .""" | client = Client ( )
client . prepare_connection ( )
group_api = API ( client )
print ( group_api . index ( ) ) |
def convert ( dbus_obj ) :
"""Converts dbus _ obj from dbus type to python type .
: param dbus _ obj : dbus object .
: returns : dbus _ obj in python type .""" | _isinstance = partial ( isinstance , dbus_obj )
ConvertType = namedtuple ( 'ConvertType' , 'pytype dbustypes' )
pyint = ConvertType ( int , ( dbus . Byte , dbus . Int16 , dbus . Int32 , dbus . Int64 , dbus . UInt16 , dbus . UInt32 , dbus . UInt64 ) )
pybool = ConvertType ( bool , ( dbus . Boolean , ) )
pyfloat = Conver... |
def create_developer_certificate ( self , authorization , body , ** kwargs ) : # noqa : E501
"""Create a new developer certificate to connect to the bootstrap server . # noqa : E501
This REST API is intended to be used by customers to get a developer certificate ( a certificate that can be flashed into multiple d... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'asynchronous' ) :
return self . create_developer_certificate_with_http_info ( authorization , body , ** kwargs )
# noqa : E501
else :
( data ) = self . create_developer_certificate_with_http_info ( authorization , body , ** kwargs )
# noqa : ... |
def _max_weight_operator ( ops : Iterable [ PauliTerm ] ) -> Union [ None , PauliTerm ] :
"""Construct a PauliTerm operator by taking the non - identity single - qubit operator at each
qubit position .
This function will return ` ` None ` ` if the input operators do not share a natural tensor
product basis . ... | mapping = dict ( )
# type : Dict [ int , str ]
for op in ops :
for idx , op_str in op :
if idx in mapping :
if mapping [ idx ] != op_str :
return None
else :
mapping [ idx ] = op_str
op = functools . reduce ( mul , ( PauliTerm ( op , q ) for q , op in mapping ... |
def run ( ) :
"""Initialize and start objects . This is called automatically when importing the package .
: return none :""" | # GLOBALS
global cwd , files , logger_start , logger_benchmark , settings , _timeseries_data
_timeseries_data = { }
# files = { " . lpd " : [ { " full _ path " , " filename _ ext " , " filename _ no _ ext " , " dir " } ] , " . xls " : [ . . . ] , " . txt " : [ . . . ] }
settings = { "note_update" : True , "note_validat... |
def hilbertscan ( size , distance ) :
"""Scan pixels in a Hilbert curve pattern in the first quadrant . Modified
algorithm from https : / / en . wikipedia . org / wiki / Hilbert _ curve .
: param size : Size of enclosing square
: type size : int
: param distance : Distance along curve ( Must be smaller than... | size = 2 * ( 1 << ( size - 1 ) . bit_length ( ) ) ;
if ( distance > size ** 2 - 1 ) :
raise StopIteration ( "Invalid distance!" )
for d in range ( distance ) :
t = d
x = 0
y = 0
s = 1
while ( s < size ) :
rx = 1 & ( t / 2 )
ry = 1 & ( t ^ rx )
x , y = hilbertrot ( s , x ,... |
def _generateAlias ( self ) :
"""Return an unused auth level alias""" | for i in range ( 1000 ) :
alias = 'cust%d' % ( i , )
if alias not in self . auth_level_aliases :
return alias
raise RuntimeError ( 'Could not find an unused alias (tried 1000!)' ) |
def unsign_url_safe ( token , secret_key , salt = None , ** kw ) :
"""To sign url safe data .
If expires _ in is provided it will Time the signature
: param token :
: param secret _ key :
: param salt : ( string ) a namespace key
: param kw :
: return :""" | if len ( token . split ( "." ) ) == 3 :
s = URLSafeTimedSerializer2 ( secret_key = secret_key , salt = salt , ** kw )
value , timestamp = s . loads ( token , max_age = None , return_timestamp = True )
now = datetime . datetime . utcnow ( )
if timestamp > now :
return value
else :
rai... |
def read_hashes ( self ) :
"""Read Hash values from the stream .
Returns :
list : a list of hash values . Each value is of the bytearray type .""" | var_len = self . read_var_int ( )
items = [ ]
for _ in range ( 0 , var_len ) :
ba = bytearray ( self . read_bytes ( 32 ) )
ba . reverse ( )
items . append ( ba . hex ( ) )
return items |
def _file_and_exists ( val , input_files ) :
"""Check if an input is a file and exists .
Checks both locally ( staged ) and from input files ( re - passed but never localized ) .""" | return ( ( os . path . exists ( val ) and os . path . isfile ( val ) ) or val in input_files ) |
def _get_template ( path , option_key ) :
'''Get the contents of a template file and provide it as a module type
: param path : path to the template . yml file
: type path : ` ` str ` `
: param option _ key : The unique key of this template
: type option _ key : ` ` str ` `
: returns : Details about the t... | with salt . utils . files . fopen ( path , 'r' ) as template_f :
template = deserialize ( template_f )
info = ( option_key , template . get ( 'description' , '' ) , template )
return info |
def delete_role_config_group ( resource_root , service_name , name , cluster_name = "default" ) :
"""Delete a role config group by name .
@ param resource _ root : The root Resource object .
@ param service _ name : Service name .
@ param name : Role config group name .
@ param cluster _ name : Cluster name... | return call ( resource_root . delete , _get_role_config_group_path ( cluster_name , service_name , name ) , ApiRoleConfigGroup , api_version = 3 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.