signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def stack_get ( self , key ) :
"""Set a value in a task context stack""" | task = Task . current_task ( )
try :
context = task . _context_stack
except AttributeError :
return
if key in context :
return context [ key ] [ - 1 ] |
def receive ( self ) :
"""Read and return a message from the stream . If ` None ` is returned , then
the socket is considered closed / errored .""" | if self . _closed :
raise WebSocketError ( "Connection is already closed" )
try :
return self . read_message ( )
except UnicodeError as e :
logger . info ( 'websocket.receive: UnicodeError {}' . format ( e ) )
self . close ( 1007 )
except WebSocketError as e :
logger . info ( 'websocket.receive: Web... |
def infer_namespace ( ac ) :
"""Infer the single namespace of the given accession
This function is convenience wrapper around infer _ namespaces ( ) .
Returns :
* None if no namespaces are inferred
* The ( single ) namespace if only one namespace is inferred
* Raises an exception if more than one namespac... | namespaces = infer_namespaces ( ac )
if not namespaces :
return None
if len ( namespaces ) > 1 :
raise BioutilsError ( "Multiple namespaces possible for {}" . format ( ac ) )
return namespaces [ 0 ] |
def do_list ( self ) :
"""! @ brief Handle ' list ' subcommand .""" | # Default to listing probes .
if ( self . _args . probes , self . _args . targets , self . _args . boards ) == ( False , False , False ) :
self . _args . probes = True
# Create a session with no device so we load any config .
session = Session ( None , project_dir = self . _args . project_dir , config_file = self .... |
def plot_cumulative_gain ( y_true , y_probas , title = 'Cumulative Gains Curve' , ax = None , figsize = None , title_fontsize = "large" , text_fontsize = "medium" ) :
"""Generates the Cumulative Gains Plot from labels and scores / probabilities
The cumulative gains chart is used to determine the effectiveness of ... | y_true = np . array ( y_true )
y_probas = np . array ( y_probas )
classes = np . unique ( y_true )
if len ( classes ) != 2 :
raise ValueError ( 'Cannot calculate Cumulative Gains for data with ' '{} category/ies' . format ( len ( classes ) ) )
# Compute Cumulative Gain Curves
percentages , gains1 = cumulative_gain_... |
def main ( inputstructs , inputpdbids ) :
"""Main function . Calls functions for processing , report generation and visualization .""" | pdbid , pdbpath = None , None
# # @ todo For multiprocessing , implement better stacktracing for errors
# Print title and version
title = "* Protein-Ligand Interaction Profiler v%s *" % __version__
write_message ( '\n' + '*' * len ( title ) + '\n' )
write_message ( title )
write_message ( '\n' + '*' * len ( title ) + '... |
def import_keyset ( self , keyset ) :
"""Imports a RFC 7517 keyset using the standard JSON format .
: param keyset : The RFC 7517 representation of a JOSE Keyset .""" | try :
jwkset = json_decode ( keyset )
except Exception : # pylint : disable = broad - except
raise InvalidJWKValue ( )
if 'keys' not in jwkset :
raise InvalidJWKValue ( )
for k , v in iteritems ( jwkset ) :
if k == 'keys' :
for jwk in v :
self [ 'keys' ] . add ( JWK ( ** jwk ) )
... |
def max ( cls ) :
"""Get max record identifier .""" | max_recid = db . session . query ( func . max ( cls . recid ) ) . scalar ( )
return max_recid if max_recid else 0 |
def _router_added ( self , router_id , router ) :
"""Operations when a router is added .
Create a new RouterInfo object for this router and add it to the
service helpers router _ info dictionary . Then ` router _ added ( ) ` is
called on the device driver .
: param router _ id : id of the router
: param r... | ri = RouterInfo ( router_id , router )
driver = self . driver_manager . set_driver ( router )
if router [ ROUTER_ROLE_ATTR ] in [ c_constants . ROUTER_ROLE_GLOBAL , c_constants . ROUTER_ROLE_LOGICAL_GLOBAL ] : # No need to create a vrf for Global or logical global routers
LOG . debug ( "Skipping router_added device... |
def set_colors ( self , fg = None , bg = None ) :
"""Sets the colors to be used with the L { print _ str } and draw _ * methods .
Values of None will only leave the current values unchanged .
Args :
fg ( Optional [ Union [ Tuple [ int , int , int ] , int , Ellipsis ] ] )
bg ( Optional [ Union [ Tuple [ int ... | if fg is not None :
self . _fg = _format_color ( fg , self . _fg )
if bg is not None :
self . _bg = _format_color ( bg , self . _bg ) |
def get_worksheet ( self , index ) :
"""Returns a worksheet with specified ` index ` .
: param index : An index of a worksheet . Indexes start from zero .
: type index : int
: returns : an instance of : class : ` gsperad . models . Worksheet `
or ` None ` if the worksheet is not found .
Example . To get f... | sheet_data = self . fetch_sheet_metadata ( )
try :
properties = sheet_data [ 'sheets' ] [ index ] [ 'properties' ]
return Worksheet ( self , properties )
except ( KeyError , IndexError ) :
return None |
def extractSampleMicroData ( Economy , num_periods , AgentCount , ignore_periods ) :
'''Extracts sample micro data to be used in micro ( cross section ) regression .
Parameters
Economy : Economy
An economy ( with one AgentType ) for for which history has already been calculated .
num _ periods : int
Numbe... | # First pull out economy common data .
# Note indexing on Economy tracked vars is one ahead of agent .
agg_trans_shk_matrix = deepcopy ( Economy . TranShkAggNow_hist [ ignore_periods : ignore_periods + num_periods ] )
wRte_matrix = deepcopy ( Economy . wRteNow_hist [ ignore_periods : ignore_periods + num_periods ] )
# ... |
def getParameterByName ( self , name ) :
"""Searchs a parameter by name and returns it .""" | result = None
for parameter in self . getParameters ( ) :
nameParam = parameter . getName ( )
if nameParam == name :
result = parameter
break
return result |
def _connect ( ) :
'''Return server object used to interact with Jenkins .
: return : server object used to interact with Jenkins''' | jenkins_url = __salt__ [ 'config.get' ] ( 'jenkins.url' ) or __salt__ [ 'config.get' ] ( 'jenkins:url' ) or __salt__ [ 'pillar.get' ] ( 'jenkins.url' )
jenkins_user = __salt__ [ 'config.get' ] ( 'jenkins.user' ) or __salt__ [ 'config.get' ] ( 'jenkins:user' ) or __salt__ [ 'pillar.get' ] ( 'jenkins.user' )
jenkins_pass... |
def heartbeat_interval ( self , heartbeat_interval_ms ) :
"""heartbeat _ interval ( nsqd 0.2.19 + ) milliseconds between heartbeats .
Valid range : 1000 < = heartbeat _ interval < = configured _ max ( - 1 disables
heartbeats )
- - max - heartbeat - interval ( nsqd flag ) controls the max
Defaults to - - cli... | assert issubclass ( heartbeat_interval_ms . __class__ , int )
return self . __push ( 'heartbeat_interval' , heartbeat_interval_ms ) |
def get_recordInfo ( self , headers , zoneID , zone , records ) :
"""Get the information of the records .""" | if 'None' in records : # If [ ' None ' ] in record argument , query all .
recordQueryEnpoint = '/' + zoneID + '/dns_records&per_page=100'
recordUrl = self . BASE_URL + recordQueryEnpoint
recordRequest = requests . get ( recordUrl , headers = headers )
recordResponse = recordRequest . json ( ) [ 'result'... |
def explain_prediction_lightning ( estimator , doc , vec = None , top = None , target_names = None , targets = None , feature_names = None , vectorized = False , coef_scale = None ) :
"""Return an explanation of a lightning estimator predictions""" | return explain_weights_lightning_not_supported ( estimator , doc ) |
def generate_context ( self ) :
'''Setup context''' | self . permalink_output_path = os . path . join ( self . output_path , self . settings [ 'PERMALINK_PATH' ] )
self . permalink_id_metadata_key = ( self . settings [ 'PERMALINK_ID_METADATA_KEY' ] ) |
def InstallGRR ( self , path ) :
"""Installs GRR .""" | cmd64 = [ self . pip64 , "install" ]
cmd32 = [ self . pip32 , "install" ]
if args . wheel_dir :
cmd64 += [ "--no-index" , r"--find-links=file:///%s" % args . wheel_dir ]
cmd32 += [ "--no-index" , r"--find-links=file:///%s" % args . wheel_dir ]
cmd64 . append ( path )
cmd32 . append ( path )
subprocess . check_c... |
def reset ( self , ) :
"""Reset the state of all cells .
This is normally used between sequences while training . All internal states
are reset to 0.""" | self . activeState [ 't-1' ] . fill ( 0 )
self . activeState [ 't' ] . fill ( 0 )
self . predictedState [ 't-1' ] . fill ( 0 )
self . predictedState [ 't' ] . fill ( 0 )
self . learnState [ 't-1' ] . fill ( 0 )
self . learnState [ 't' ] . fill ( 0 )
self . confidence [ 't-1' ] . fill ( 0 )
self . confidence [ 't' ] . f... |
def confirm_forgot_password ( self , confirmation_code , password ) :
"""Allows a user to enter a code provided when they reset their password
to update their password .
: param confirmation _ code : The confirmation code sent by a user ' s request
to retrieve a forgotten password
: param password : New pas... | params = { 'ClientId' : self . client_id , 'Username' : self . username , 'ConfirmationCode' : confirmation_code , 'Password' : password }
self . _add_secret_hash ( params , 'SecretHash' )
response = self . client . confirm_forgot_password ( ** params )
self . _set_attributes ( response , { 'password' : password } ) |
def CalcDayOfWeek ( self ) :
"""Calculate the correct day of the week .""" | # rip apart the value
year , month , day , day_of_week = self . value
# assume the worst
day_of_week = 255
# check for special values
if year == 255 :
pass
elif month in _special_mon_inv :
pass
elif day in _special_day_inv :
pass
else :
try :
today = time . mktime ( ( year + 1900 , month , day ,... |
def check_signing_key ( self ) :
"""Check that repo signing key is trusted by gpg keychain""" | user_keys = self . gpg . list_keys ( )
if len ( user_keys ) > 0 :
trusted = False
for key in user_keys :
if key [ 'fingerprint' ] == self . key_info [ 'fingerprint' ] :
trusted = True
logger . debug ( ( "repo signing key trusted in user keyring, " "fingerprint {0}" . format ( key... |
def v1_subtopic_list ( request , response , kvlclient , fid , sfid ) :
'''Retrieves a list of items in a subfolder .
The route for this endpoint is :
` ` GET / dossier / v1 / folder / < fid > / subfolder / < sfid > ` ` .
( Temporarily , the " current user " can be set via the
` ` annotator _ id ` ` query pa... | path = urllib . unquote ( fid ) + '/' + urllib . unquote ( sfid )
try :
items = [ ]
for it in new_folders ( kvlclient , request ) . list ( path ) :
if '@' in it . name :
items . append ( it . name . split ( '@' ) )
else :
items . append ( ( it . name , None ) )
return... |
def put ( self , id , name , description , private , runs_executable_tasks , runs_docker_container_tasks , runs_singularity_container_tasks , active , whitelists , ) :
"""Updates a task queue on the saltant server .
Args :
id ( int ) : The ID of the task queue .
name ( str ) : The name of the task queue .
d... | # Update the object
request_url = self . _client . base_api_url + self . detail_url . format ( id = id )
data_to_put = { "name" : name , "description" : description , "private" : private , "runs_executable_tasks" : runs_executable_tasks , "runs_docker_container_tasks" : runs_docker_container_tasks , "runs_singularity_c... |
def history_file ( self , location = None ) :
"""Return history file location .""" | if location : # Hardcoded location passed from the config file .
if os . path . exists ( location ) :
return location
else :
logger . warn ( "The specified history file %s doesn't exist" , location )
filenames = [ ]
for base in [ 'CHANGES' , 'HISTORY' , 'CHANGELOG' ] :
filenames . append ( b... |
def clear_repository_helper ( reserve_fn , clear_fn , retry = 5 , reservation = None ) :
"""Helper function to start repository erasure and wait until finish .
This helper is used by clear _ sel and clear _ sdr _ repository .""" | if reservation is None :
reservation = reserve_fn ( )
# start erasure
reservation = _clear_repository ( reserve_fn , clear_fn , INITIATE_ERASE , retry , reservation )
# give some time to clear
time . sleep ( 0.5 )
# wait until finish
reservation = _clear_repository ( reserve_fn , clear_fn , GET_ERASE_STATUS , retry... |
def _imputeMissing ( X , center = True , unit = True , betaNotUnitVariance = False , betaA = 1.0 , betaB = 1.0 ) :
'''fill in missing values in the SNP matrix by the mean value
optionally center the data and unit - variance it
Args :
X : scipy . array of SNP values . If dtype = = ' int8 ' the missing values a... | typeX = X . dtype
if typeX != SP . int8 :
iNanX = X != X
else :
iNanX = X == - 9
if iNanX . any ( ) or betaNotUnitVariance :
if cparser :
print ( "using C-based imputer" )
if X . flags [ "C_CONTIGUOUS" ] or typeX != SP . float32 :
X = SP . array ( X , order = "F" , dtype = SP . f... |
def servicegroup_delete ( sg_name , ** connection_args ) :
'''Delete a new service group
CLI Example :
. . code - block : : bash
salt ' * ' netscaler . servicegroup _ delete ' serviceGroupName ' ''' | ret = True
sg = _servicegroup_get ( sg_name , ** connection_args )
if sg is None :
return False
nitro = _connect ( ** connection_args )
if nitro is None :
return False
try :
NSServiceGroup . delete ( nitro , sg )
except NSNitroError as error :
log . debug ( 'netscaler module error - NSServiceGroup.delet... |
def start ( self , * args , ** kwargs ) :
'''Launch IPython notebook server in background process .
Arguments and keyword arguments are passed on to ` Popen ` call .
By default , notebook server is launched using current working directory
as the notebook directory .''' | if 'stderr' in kwargs :
raise ValueError ( '`stderr` must not be specified, since it must be' ' monitored to determine which port the notebook ' 'server is running on.' )
args_ = ( '%s' % sys . executable , '-m' , 'IPython' , 'notebook' ) + self . args
args_ = args_ + tuple ( args )
self . process = Popen ( args_ ,... |
def postURL ( self , url , headers , body ) :
"""Implement post using a get call""" | new_url = url
if body is not None :
new_url = FileSea . convert_body ( url , body )
return self . getURL ( new_url , headers ) |
def ranked_in_list ( self , members , ** options ) :
'''Retrieve a page of leaders from the leaderboard for a given list of members .
@ param members [ Array ] Member names .
@ param options [ Hash ] Options to be used when retrieving the page from the leaderboard .
@ return a page of leaders from the leaderb... | return self . ranked_in_list_in ( self . leaderboard_name , members , ** options ) |
def receive_accepted ( self , msg ) :
'''Called when an Accepted message is received from an acceptor . Once the final value
is determined , the return value of this method will be a Resolution message containing
the consentual value . Subsequent calls after the resolution is chosen will continue to add
new A... | if self . final_value is not None :
if msg . proposal_id >= self . final_proposal_id and msg . proposal_value == self . final_value :
self . final_acceptors . add ( msg . from_uid )
return Resolution ( self . network_uid , self . final_value )
last_pn = self . acceptors . get ( msg . from_uid )
if last_... |
def evaluate ( self , frame_id , expression , global_context = False , disable_break = False ) :
"""Evaluates ' expression ' in the context of the frame identified by
' frame _ id ' or globally .
Breakpoints are disabled depending on ' disable _ break ' value .
Returns a tuple of value and type both as str . ... | if disable_break :
breakpoints_backup = IKBreakpoint . backup_breakpoints_state ( )
IKBreakpoint . disable_all_breakpoints ( )
if frame_id and not global_context :
eval_frame = ctypes . cast ( frame_id , ctypes . py_object ) . value
global_vars = eval_frame . f_globals
local_vars = eval_frame . f_lo... |
def _line_for_patches ( self , data , chart , renderer , series_name ) :
"""Add a line along the top edge of a Patch in a stacked Area Chart ; return
the new Glyph for addition to HoverTool .
: param data : original data for the graph
: type data : dict
: param chart : Chart to add the line to
: type char... | # @ TODO this method needs a major refactor
# get the original x and y values , and color
xvals = deepcopy ( renderer . data_source . data [ 'x_values' ] [ 0 ] )
yvals = deepcopy ( renderer . data_source . data [ 'y_values' ] [ 0 ] )
line_color = renderer . glyph . fill_color
# save original values for logging if neede... |
def slope_percentile ( self , date , mag ) :
"""Return 10 % and 90 % percentile of slope .
Parameters
date : array _ like
An array of phase - folded date . Sorted .
mag : array _ like
An array of phase - folded magnitudes . Sorted by date .
Returns
per _ 10 : float
10 % percentile values of slope . ... | date_diff = date [ 1 : ] - date [ : len ( date ) - 1 ]
mag_diff = mag [ 1 : ] - mag [ : len ( mag ) - 1 ]
# Remove zero mag _ diff .
index = np . where ( mag_diff != 0. )
date_diff = date_diff [ index ]
mag_diff = mag_diff [ index ]
# Derive slope .
slope = date_diff / mag_diff
percentile_10 = np . percentile ( slope ,... |
def get_bucket_for ( self , node ) :
"""Get the index of the bucket that the given node would fall into .""" | for index , bucket in enumerate ( self . buckets ) :
if node . long_id < bucket . range [ 1 ] :
return index
# we should never be here , but make linter happy
return None |
def db2server ( dbfile , block_size , dbuser , dbpassword ) :
"""Transfer data from local database to Catalysis Hub server""" | _db2server . main ( dbfile , write_reaction = True , write_ase = True , write_publication = True , write_reaction_system = True , block_size = block_size , start_block = 0 , user = dbuser , password = dbpassword ) |
def fcontext_add_policy ( name , filetype = None , sel_type = None , sel_user = None , sel_level = None ) :
'''. . versionadded : : 2019.2.0
Adds the SELinux policy for a given filespec and other optional parameters .
Returns the result of the call to semanage .
Note that you don ' t have to remove an entry b... | return _fcontext_add_or_delete_policy ( 'add' , name , filetype , sel_type , sel_user , sel_level ) |
def service ( self ) :
"""Returns a Splunk service object for this script invocation .
The service object is created from the Splunkd URI and session key
passed to the command invocation on the modular input stream . It is
available as soon as the : code : ` Script . stream _ events ` method is
called .
:... | if self . _service is not None :
return self . _service
if self . _input_definition is None :
return None
splunkd_uri = self . _input_definition . metadata [ "server_uri" ]
session_key = self . _input_definition . metadata [ "session_key" ]
splunkd = urlsplit ( splunkd_uri , allow_fragments = False )
self . _se... |
def cull_to_timestep ( self , timestep = 1 ) :
"""Get a collection with only datetimes that fit a timestep .""" | valid_s = self . header . analysis_period . VALIDTIMESTEPS . keys ( )
assert timestep in valid_s , 'timestep {} is not valid. Choose from: {}' . format ( timestep , valid_s )
new_ap , new_values , new_datetimes = self . _timestep_cull ( timestep )
new_header = self . header . duplicate ( )
new_header . _analysis_period... |
def _ParseDateTimeValue ( self , byte_stream , file_offset ) :
"""Parses a CUPS IPP RFC2579 date - time value from a byte stream .
Args :
byte _ stream ( bytes ) : byte stream .
file _ offset ( int ) : offset of the attribute data relative to the start of
the file - like object .
Returns :
dfdatetime . ... | datetime_value_map = self . _GetDataTypeMap ( 'cups_ipp_datetime_value' )
try :
value = self . _ReadStructureFromByteStream ( byte_stream , file_offset , datetime_value_map )
except ( ValueError , errors . ParseError ) as exception :
raise errors . ParseError ( 'Unable to parse datetime value with error: {0!s}'... |
async def send_telegram ( self , * , client_key , telegram_id , telegram_key , recepient ) :
"""A basic interface to the Telegrams API .
Parameters
client _ key : str
Telegrams API Client Key .
telegram _ id : int or str
Telegram id .
telegram _ key : str
Telegram key .
recepient : str
Name of the... | params = { 'a' : 'sendTG' , 'client' : client_key , 'tgid' : str ( telegram_id ) , 'key' : telegram_key , 'to' : recepient }
return await self . _call_api ( params ) |
def compute_area_features ( features , max_area_width , max_area_height = 1 , height = 1 , epsilon = 1e-6 ) :
"""Computes features for each area .
Args :
features : a Tensor in a shape of [ batch _ size , height * width , depth ] .
max _ area _ width : the max width allowed for an area .
max _ area _ height... | with tf . name_scope ( "compute_area_features" ) :
tf . logging . info ( "area_attention compute_area_features: %d x %d" , max_area_height , max_area_width )
area_sum , area_heights , area_widths = _compute_sum_image ( features , max_area_width = max_area_width , max_area_height = max_area_height , height = hei... |
def get_hardware_source_by_id ( self , hardware_source_id : str , version : str ) :
"""Return the hardware source API matching the hardware _ source _ id and version .
. . versionadded : : 1.0
Scriptable : Yes""" | actual_version = "1.0.0"
if Utility . compare_versions ( version , actual_version ) > 0 :
raise NotImplementedError ( "Hardware API requested version %s is greater than %s." % ( version , actual_version ) )
hardware_source = HardwareSourceModule . HardwareSourceManager ( ) . get_hardware_source_for_hardware_source_... |
def content_disposition_header ( disptype : str , quote_fields : bool = True , ** params : str ) -> str :
"""Sets ` ` Content - Disposition ` ` header .
disptype is a disposition type : inline , attachment , form - data .
Should be valid extension token ( see RFC 2183)
params is a dict with disposition params... | if not disptype or not ( TOKEN > set ( disptype ) ) :
raise ValueError ( 'bad content disposition type {!r}' '' . format ( disptype ) )
value = disptype
if params :
lparams = [ ]
for key , val in params . items ( ) :
if not key or not ( TOKEN > set ( key ) ) :
raise ValueError ( 'bad con... |
def hashing_function_from_properties ( fhp # type : FieldHashingProperties
) : # type : ( . . . ) - > Callable [ [ Iterable [ str ] , Sequence [ bytes ] , Sequence [ int ] , int , str ] , bitarray ]
"""Get the hashing function for this field
: param fhp : hashing properties for this field
: return : the hashing... | if fhp . hash_type == 'doubleHash' :
if fhp . prevent_singularity :
return double_hash_encode_ngrams_non_singular
else :
return double_hash_encode_ngrams
elif fhp . hash_type == 'blakeHash' :
return blake_encode_ngrams
else :
msg = "Unsupported hash type '{}'" . format ( fhp . hash_type ... |
def EL_Si_module ( ) :
'''returns angular dependent EL emissivity of a PV module
calculated of nanmedian ( persp - corrected EL module / reference module )
published in K . Bedrich : Quantitative Electroluminescence Measurement on PV devices
PhD Thesis , 2017''' | arr = np . array ( [ [ 2.5 , 1.00281 ] , [ 7.5 , 1.00238 ] , [ 12.5 , 1.00174 ] , [ 17.5 , 1.00204 ] , [ 22.5 , 1.00054 ] , [ 27.5 , 0.998255 ] , [ 32.5 , 0.995351 ] , [ 37.5 , 0.991246 ] , [ 42.5 , 0.985304 ] , [ 47.5 , 0.975338 ] , [ 52.5 , 0.960455 ] , [ 57.5 , 0.937544 ] , [ 62.5 , 0.900607 ] , [ 67.5 , 0.844636 ] ... |
def knot_removal_alpha_i ( u , degree , knotvector , num , idx ) :
"""Computes : math : ` \\ alpha _ { i } ` coefficient for knot removal algorithm .
Please refer to Eq . 5.29 of The NURBS Book by Piegl & Tiller , 2nd Edition , p . 184 for details .
: param u : knot
: type u : float
: param degree : degree ... | return ( u - knotvector [ idx ] ) / ( knotvector [ idx + degree + 1 + num ] - knotvector [ idx ] ) |
def get_rubric_id ( self ) :
"""Gets the ` ` Id ` ` of the rubric .
return : ( osid . id . Id ) - an assessment taken ` ` Id ` `
raise : IllegalState - ` ` has _ rubric ( ) ` ` is ` ` false ` `
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . Resource . get _ avatar _ id _ template
if not bool ( self . _my_map [ 'rubricId' ] ) :
raise errors . IllegalState ( 'this AssessmentTaken has no rubric' )
else :
return Id ( self . _my_map [ 'rubricId' ] ) |
def get_json_body ( self , required = None , validators = None ) :
"""Get JSON from the request body
: param required : optionally provide a list of keys that should be
in the JSON body ( raises a 400 HTTPError if any are missing )
: param validator : optionally provide a dictionary of items that should
be ... | content_type = self . request . headers . get ( 'Content-Type' , 'application/json' )
if 'application/json' not in content_type . split ( ';' ) :
raise HTTPError ( 415 , 'Content-Type should be application/json' )
if not self . request . body :
error = 'Request body is empty'
logging . warning ( error )
... |
def get_filename ( self , variable ) :
"""Return the auxiliary file name the given variable is allocated
to or | None | if the given variable is not allocated to any
auxiliary file name .
> > > from hydpy import dummies
> > > eqb = dummies . v2af . eqb [ 0]
> > > dummies . v2af . get _ filename ( eqb )
... | fn2var = self . _type2filename2variable . get ( type ( variable ) , { } )
for ( fn_ , var ) in fn2var . items ( ) :
if var == variable :
return fn_
return None |
def merge ( dst , src ) :
"""put key / value pairs that exist in src but not in dst into dst""" | for key in src . keys ( ) :
if key not in dst :
dst [ key ] = src [ key ] |
def po_to_unicode ( po_obj ) :
"""Turns a polib : class : ` polib . PoFile ` or a : class : ` polib . PoEntry `
into a : class : ` unicode ` string .
: param po _ obj : Either a : class : ` polib . PoFile ` or : class : ` polib . PoEntry ` .
: rtype : : class : ` unicode ` string .""" | po_text = po_obj . __str__ ( )
if type ( po_text ) != types . UnicodeType :
po_text = po_text . decode ( 'utf-8' )
return po_text |
def _parse_fields_whois ( self , * args , ** kwargs ) :
"""Deprecated . This will be removed in a future release .""" | from warnings import warn
warn ( 'IPASN._parse_fields_whois() has been deprecated and will be ' 'removed. You should now use IPASN.parse_fields_whois().' )
return self . parse_fields_whois ( * args , ** kwargs ) |
def plat ( inc ) :
"""calculate paleolatitude from inclination using dipole formula : tan ( I ) = 2tan ( lat )
Parameters
_ _ _ _ _
inc : either a single value or an array of inclinations
Returns
array of latitudes""" | tani = np . tan ( np . radians ( inc ) )
lat = np . arctan ( tani / 2. )
return np . degrees ( lat ) |
def tvdb_refresh_token ( token ) :
"""Refreshes JWT token
Online docs : api . thetvdb . com / swagger # ! / Authentication / get _ refresh _ token =""" | url = "https://api.thetvdb.com/refresh_token"
headers = { "Authorization" : "Bearer %s" % token }
status , content = _request_json ( url , headers = headers , cache = False )
if status == 401 :
raise MapiProviderException ( "invalid token" )
elif status != 200 or not content . get ( "token" ) :
raise MapiNetwor... |
def fasta_cmd_get_seqs ( acc_list , blast_db = None , is_protein = None , out_filename = None , params = { } , WorkingDir = tempfile . gettempdir ( ) , SuppressStderr = None , SuppressStdout = None ) :
"""Retrieve sequences for list of accessions""" | if is_protein is None :
params [ "-p" ] = 'G'
elif is_protein :
params [ "-p" ] = 'T'
else :
params [ "-p" ] = 'F'
if blast_db :
params [ "-d" ] = blast_db
if out_filename :
params [ "-o" ] = out_filename
# turn off duplicate accessions
params [ "-a" ] = "F"
# create Psi - BLAST
fasta_cmd = FastaCmd... |
def info ( request ) :
"""display some user info to show we have authenticated successfully""" | if check_key ( request ) :
api = get_api ( request )
user = api . users ( id = 'self' )
print dir ( user )
return render_to_response ( 'djfoursquare/info.html' , { 'user' : user } )
else :
return HttpResponseRedirect ( reverse ( 'main' ) ) |
def button_pressed ( self , key_code , prefix = None ) :
"""Called from the controller classes to update the state of this button manager when a button is pressed .
: internal :
: param key _ code :
The code specified when populating Button instances
: param prefix :
Applied to key code if present""" | if prefix is not None :
state = self . buttons_by_code . get ( prefix + str ( key_code ) )
else :
state = self . buttons_by_code . get ( key_code )
if state is not None :
for handler in state . button_handlers :
handler ( state . button )
state . is_pressed = True
state . last_pressed = time... |
def project ( self ) :
"""str : Default project to use for queries performed through IPython
magics
Note :
The project does not need to be explicitly defined if you have an
environment default project set . If you do not have a default
project set in your environment , manually assign the project as
dem... | if self . _project is None :
_ , self . _project = google . auth . default ( )
return self . _project |
def read ( cls , source , * args , ** kwargs ) :
"""Read data from a source into a ` gwpy . timeseries ` object .
This method is just the internal worker for ` TimeSeries . read ` , and
` TimeSeriesDict . read ` , and isn ' t meant to be called directly .""" | # if reading a cache , read it now and sieve
if io_cache . is_cache ( source ) :
from . cache import preformat_cache
source = preformat_cache ( source , * args [ 1 : ] , start = kwargs . get ( 'start' ) , end = kwargs . get ( 'end' ) )
# get join arguments
pad = kwargs . pop ( 'pad' , None )
gap = kwargs . pop ... |
def standardize_table ( cls , table ) :
'''Extract objects from a Gaia DR2 table .''' | # tidy up quantities , setting motions to 0 if poorly defined
for key in [ 'pmra' , 'pmdec' , 'parallax' , 'radial_velocity' ] :
bad = table [ key ] . mask
table [ key ] [ bad ] = 0.0
bad = table [ 'parallax' ] / table [ 'parallax_error' ] < 1
bad += table [ 'parallax' ] . mask
table [ 'parallax' ] [ bad ] = np... |
def valid_config_param ( self , param_name , cleanup = False ) :
"""Check if a given section name is a valid parameter for i3status .""" | if cleanup :
valid_config_params = [ _ for _ in self . i3status_module_names if _ not in [ "cpu_usage" , "ddate" , "ipv6" , "load" , "time" ] ]
else :
valid_config_params = self . i3status_module_names + [ "general" , "order" ]
return param_name . split ( " " ) [ 0 ] in valid_config_params |
def assertCategoricalLevelIn ( self , level , levels , msg = None ) :
'''Fail if ` ` level ` ` is not in ` ` levels ` ` .
This is equivalent to ` ` self . assertIn ( level , levels ) ` ` .
Parameters
level
levels : iterable
msg : str
If not provided , the : mod : ` marbles . mixins ` or
: mod : ` unit... | if not isinstance ( levels , collections . Iterable ) :
raise TypeError ( 'Second argument is not iterable' )
self . assertIn ( level , levels , msg = msg ) |
def extract_columns ( data , * cols ) :
"""Extract columns specified in the argument list .
> > > chart _ data . extract _ columns ( [ [ 10,20 ] , [ 30,40 ] , [ 50,60 ] ] , 0)
[ [ 10 ] , [ 30 ] , [ 50 ] ]""" | out = [ ]
try : # for python 2.2:
# return [ [ r [ c ] for c in cols ] for r in data ]
for r in data :
col = [ ]
for c in cols :
col . append ( r [ c ] )
out . append ( col )
except IndexError :
raise IndexError ( "data=%s col=%s" % ( data , col ) )
return out |
def truncate ( s , max_len = 20 , ellipsis = '...' ) :
r"""Return string at most ` max _ len ` characters or sequence elments appended with the ` ellipsis ` characters
> > > truncate ( OrderedDict ( zip ( list ( ' ABCDEFGH ' ) , range ( 8 ) ) ) , 1)
" { ' A ' : 0 . . . "
> > > truncate ( list ( range ( 5 ) ) ... | if s is None :
return None
elif isinstance ( s , basestring ) :
return s [ : min ( len ( s ) , max_len ) ] + ellipsis if len ( s ) > max_len else ''
elif isinstance ( s , Mapping ) :
truncated_str = str ( dict ( islice ( viewitems ( s ) , max_len ) ) )
else :
truncated_str = str ( list ( islice ( s , ma... |
def receive ( self , x , mesh_axis , source_pcoord ) :
"""Collective receive in groups .
Each group contains the processors that differ only in mesh _ axis .
` ` ` python
group _ size = self . shape [ mesh _ axis ] . size
Args :
x : a LaidOutTensor
mesh _ axis : an integer
source _ pcoord : a list of ... | x = x . to_laid_out_tensor ( )
t = x . one_slice
source_target_pairs = [ ]
for pnum in xrange ( self . size ) :
coord = mtf . pnum_to_processor_coordinates ( self . shape , pnum )
k = coord [ mesh_axis ]
if source_pcoord [ k ] is not None :
coord [ mesh_axis ] = source_pcoord [ k ]
target_pn... |
def delete ( self , creative_id , nick = None ) :
'''xxxxx . xxxxx . creative . delete
删除一个创意''' | request = TOPRequest ( 'xxxxx.xxxxx.creative.delete' )
request [ 'creative_id' ] = creative_id
if nick != None :
request [ 'nick' ] = nick
self . create ( self . execute ( request ) , fields = [ 'success' , 'result' , 'success' , 'result_code' , 'result_message' ] , models = { 'result' : Creative } )
return self . ... |
def get_netid_subscriptions ( netid , subscription_codes ) :
"""Returns a list of uwnetid . subscription objects
corresponding to the netid and subscription code or list provided""" | url = _netid_subscription_url ( netid , subscription_codes )
response = get_resource ( url )
return _json_to_subscriptions ( response ) |
def matrixidx2sheet ( self , row , col ) :
"""Return ( x , y ) where x and y are the floating point coordinates
of the * center * of the given matrix cell ( row , col ) . If the
matrix cell represents a 0.2 by 0.2 region , then the center
location returned would be 0.1,0.1.
NOTE : This is NOT the strict mat... | x , y = self . matrix2sheet ( ( row + 0.5 ) , ( col + 0.5 ) )
# Rounding allows easier comparison with user specified values
if not isinstance ( x , datetime_types ) :
x = np . around ( x , 10 )
if not isinstance ( y , datetime_types ) :
y = np . around ( y , 10 )
return x , y |
def generate ( job , build_path : str , from_image : str , build_steps : Optional [ List [ str ] ] = None , env_vars : Optional [ List [ Tuple [ str , str ] ] ] = None , nvidia_bin : str = None , set_lang_env : bool = True , uid : int = None , gid : int = None ) -> bool :
"""Build necessary code for a job to run""" | rendered_dockerfile = dockerizer_generate ( repo_path = build_path , from_image = from_image , build_steps = build_steps , env_vars = env_vars , nvidia_bin = nvidia_bin , set_lang_env = set_lang_env , uid = uid , gid = gid )
if rendered_dockerfile :
job . log_dockerfile ( dockerfile = rendered_dockerfile )
return T... |
def expireat ( self , key , timestamp ) :
"""Set expire timestamp on a key .
if timeout is float it will be multiplied by 1000
coerced to int and passed to ` pexpireat ` method .
Otherwise raises TypeError if timestamp argument is not int .""" | if isinstance ( timestamp , float ) :
return self . pexpireat ( key , int ( timestamp * 1000 ) )
if not isinstance ( timestamp , int ) :
raise TypeError ( "timestamp argument must be int, not {!r}" . format ( timestamp ) )
fut = self . execute ( b'EXPIREAT' , key , timestamp )
return wait_convert ( fut , bool ) |
def main ( ) :
'''Sample program to test GLWindow .''' | print ( 'GLWindow:' , GLWindow . __version__ )
print ( 'Python:' , sys . version )
print ( 'Platform:' , sys . platform )
wnd = GLWindow . create_window ( ( 480 , 480 ) , title = 'GLWindow Sample' )
wnd . vsync = False
ctx = ModernGL . create_context ( )
prog = ctx . program ( [ ctx . vertex_shader ( '''
#v... |
def throughput_data ( self , cycle_data , frequency = '1D' , pointscolumn = None ) :
"""Return a data frame with columns ` completed _ timestamp ` of the
given frequency , either
` count ` , where count is the number of items
' sum ' , where sum is the sum of value specified by pointscolumn . Expected to be '... | if len ( cycle_data ) < 1 :
return None
# Note completed items yet , return None
if pointscolumn :
return cycle_data [ [ 'completed_timestamp' , pointscolumn ] ] . rename ( columns = { pointscolumn : 'sum' } ) . groupby ( 'completed_timestamp' ) . sum ( ) . resample ( frequency ) . sum ( ) . fillna ( 0 )
else :... |
def alternates ( page ) :
"""Return iterable containing players on bench who are available to play ,
where each player is a dict containing :
- name
- details
- opponent""" | soup = BeautifulSoup ( page )
try :
bench = soup . find_all ( 'tr' , class_ = 'bench' )
bench_bios = [ p . find ( 'div' , class_ = 'ysf-player-name' ) for p in bench ]
names = [ p . find ( 'a' ) . text for p in bench_bios ]
details = [ p . find ( 'span' ) . text for p in bench_bios ]
opponents = [ p... |
def ticket_field_show ( self , id , ** kwargs ) :
"https : / / developer . zendesk . com / rest _ api / docs / core / ticket _ fields # show - ticket - field" | api_path = "/api/v2/ticket_fields/{id}.json"
api_path = api_path . format ( id = id )
return self . call ( api_path , ** kwargs ) |
def add_index_alias ( es , index_name , alias_name ) :
"""Add index alias to index _ name""" | es . indices . put_alias ( index = index_name , name = terms_alias ) |
def determine_file_type ( self , z ) :
"""Determine file type .""" | mimetype = z . read ( 'mimetype' ) . decode ( 'utf-8' ) . strip ( )
self . type = MIMEMAP [ mimetype ] |
def store_tmp ( self , tmp , content , reg_deps = None , tmp_deps = None , deps = None ) :
"""Stores a Claripy expression in a VEX temp value .
If in symbolic mode , this involves adding a constraint for the tmp ' s symbolic variable .
: param tmp : the number of the tmp
: param content : a Claripy expression... | self . state . _inspect ( 'tmp_write' , BP_BEFORE , tmp_write_num = tmp , tmp_write_expr = content )
tmp = self . state . _inspect_getattr ( 'tmp_write_num' , tmp )
content = self . state . _inspect_getattr ( 'tmp_write_expr' , content )
if o . SYMBOLIC_TEMPS not in self . state . options : # Non - symbolic
self . ... |
def ssn ( self , dob = None , gender = None ) :
"""Returns 11 character Norwegian personal identity code ( Fødselsnummer ) .
A Norwegian personal identity code consists of 11 digits , without any
whitespace or other delimiters . The form is DDMMYYIIICC , where III is
a serial number separating persons born oh... | if dob :
birthday = datetime . datetime . strptime ( dob , '%Y%m%d' )
else :
age = datetime . timedelta ( days = self . generator . random . randrange ( 18 * 365 , 90 * 365 ) )
birthday = datetime . datetime . now ( ) - age
if not gender :
gender = self . generator . random . choice ( ( 'F' , 'M' ) )
el... |
def find_object ( self , pattern , hosts , services ) :
"""Find object from pattern
: param pattern : text to search ( host1 , service1)
: type pattern : str
: param hosts : hosts list , used to find a specific host
: type hosts : alignak . objects . host . Host
: param services : services list , used to ... | obj = None
error = None
is_service = False
# h _ name , service _ desc are , separated
elts = pattern . split ( ',' )
host_name = elts [ 0 ] . strip ( )
# If host _ name is empty , use the host _ name the business rule is bound to
if not host_name :
host_name = self . bound_item . host_name
# Look if we have a serv... |
def section_term_lengths ( neurites , neurite_type = NeuriteType . all ) :
'''Termination section lengths in a collection of neurites''' | return map_sections ( _section_length , neurites , neurite_type = neurite_type , iterator_type = Tree . ileaf ) |
def set_tile ( self , codepoint : int , tile : np . array ) -> None :
"""Upload a tile into this array .
The tile can be in 32 - bit color ( height , width , rgba ) , or grey - scale
( height , width ) . The tile should have a dtype of ` ` np . uint8 ` ` .
This data may need to be sent to graphics card memory... | tile = np . ascontiguousarray ( tile , dtype = np . uint8 )
if tile . shape == self . tile_shape :
full_tile = np . empty ( self . tile_shape + ( 4 , ) , dtype = np . uint8 )
full_tile [ : , : , : 3 ] = 255
full_tile [ : , : , 3 ] = tile
return self . set_tile ( codepoint , full_tile )
required = self .... |
def process_summary ( article ) :
"""Ensures summaries are not cut off . Also inserts
mathjax script so that math will be rendered""" | summary = article . summary
summary_parsed = BeautifulSoup ( summary , 'html.parser' )
math = summary_parsed . find_all ( class_ = 'math' )
if len ( math ) > 0 :
last_math_text = math [ - 1 ] . get_text ( )
if len ( last_math_text ) > 3 and last_math_text [ - 3 : ] == '...' :
content_parsed = BeautifulS... |
def calc_distance_to_border ( polygons , template_raster , dst_raster , overwrite = False , keep_interim_files = False ) :
"""Calculate the distance of each raster cell ( in and outside the polygons ) to the next polygon border .
Arguments :
polygons { str } - - Filename to a geopandas - readable file with poly... | if Path ( dst_raster ) . exists ( ) and not overwrite :
print ( f"Returning 0 - File exists: {dst_raster}" )
return 0
with rasterio . open ( template_raster ) as tmp :
crs = tmp . crs
dst_raster = Path ( dst_raster )
dst_raster . parent . mkdir ( exist_ok = True , parents = True )
tempdir = Path ( tempfile ... |
def n1ql_index_build_deferred ( self , other_buckets = False ) :
"""Instruct the server to begin building any previously deferred index
definitions .
This method will gather a list of all pending indexes in the cluster
( including those created using the ` defer ` option with
: meth : ` create _ index ` ) a... | info = N1qlIndex ( )
if not other_buckets :
info . keyspace = self . _cb . bucket
return IxmgmtRequest ( self . _cb , 'build' , info ) . execute ( ) |
def get_last ( self ) :
"""Get to know how long you have kept signing in .""" | response = self . session . get ( self . mission_url , verify = False )
soup = BeautifulSoup ( response . text , 'html.parser' )
last = soup . select ( '#Main div' ) [ - 1 ] . text
return last |
def download ( self , image , url_field = 'url' , suffix = None ) :
"""Download the binary data of an image attachment .
: param image : an image attachment
: type image : : class : ` ~ groupy . api . attachments . Image `
: param str url _ field : the field of the image with the right URL
: param str suffi... | url = getattr ( image , url_field )
if suffix is not None :
url = '.' . join ( url , suffix )
response = self . session . get ( url )
return response . content |
def set_xlim ( self , xlims , dx , xscale , reverse = False ) :
"""Set x limits for plot .
This will set the limits for the x axis
for the specific plot .
Args :
xlims ( len - 2 list of floats ) : The limits for the axis .
dx ( float ) : Amount to increment by between the limits .
xscale ( str ) : Scale... | self . _set_axis_limits ( 'x' , xlims , dx , xscale , reverse )
return |
def agent ( ) :
"""Run the agent , connecting to a ( remote ) host started independently .""" | agent_module , agent_name = FLAGS . agent . rsplit ( "." , 1 )
agent_cls = getattr ( importlib . import_module ( agent_module ) , agent_name )
logging . info ( "Starting agent:" )
with remote_sc2_env . RemoteSC2Env ( map_name = FLAGS . map , host = FLAGS . host , host_port = FLAGS . host_port , lan_port = FLAGS . lan_p... |
def import_emails ( self , archives_path , all , exclude_lists = None ) :
"""Get emails from the filesystem from the ` archives _ path `
and store them into the database . If ` all ` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previous... | count = 0
email_generator = self . get_emails ( archives_path , all , exclude_lists )
for mailinglist_name , msg , index in email_generator :
try :
self . save_email ( mailinglist_name , msg , index )
except : # This anti - pattern is needed to avoid the transations to
# get stuck in case of errors ... |
def _remove_deactivated ( contexts ) :
"""Remove deactivated handlers from the chain""" | # Clean ctx handlers
stack_contexts = tuple ( [ h for h in contexts [ 0 ] if h . active ] )
# Find new head
head = contexts [ 1 ]
while head is not None and not head . active :
head = head . old_contexts [ 1 ]
# Process chain
ctx = head
while ctx is not None :
parent = ctx . old_contexts [ 1 ]
while parent ... |
def _preprocess_journal_query_value ( third_journal_field , old_publication_info_values ) :
"""Transforms the given journal query value ( old publication info ) to the new one .
Args :
third _ journal _ field ( six . text _ type ) : The final field to be used for populating the old publication info .
old _ pu... | # Prepare old publication info for : meth : ` inspire _ schemas . utils . convert _ old _ publication _ info _ to _ new ` .
publication_info_keys = [ ElasticSearchVisitor . JOURNAL_TITLE , ElasticSearchVisitor . JOURNAL_VOLUME , third_journal_field , ]
values_list = [ value . strip ( ) for value in old_publication_info... |
def get_all_notificants ( self , ** kwargs ) : # noqa : E501
"""Get all notification targets for a customer # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . get _ all _ notificants... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . get_all_notificants_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . get_all_notificants_with_http_info ( ** kwargs )
# noqa : E501
return data |
def name ( self , value ) :
"""Set a new name to controller .""" | data = { '_set_controller_name' : 'Set Name' , 'controller_name' : value , }
self . post ( data , url = SETUP_ENDPOINT , referer = SETUP_ENDPOINT ) |
def get_user ( self , request ) :
"""return active user or ` ` None ` `""" | try :
return User . objects . get ( username = request . data . get ( 'username' ) , is_active = True )
except User . DoesNotExist :
return None |
def require_http_methods ( request_methods ) :
"""Decorator to make a function view only accept particular request methods .
Usage : :
@ require _ http _ methods ( [ " GET " , " POST " ] )
def function _ view ( request ) :
# HTTP methods ! = GET or POST results in 405 error code response""" | if not isinstance ( request_methods , ( list , tuple ) ) :
raise ImproperlyConfigured ( "require_http_methods decorator must be called " "with a list or tuple of strings. For example:\n\n" " @require_http_methods(['GET', 'POST'])\n" " def function_view(request):\n" " ...\n" )
request_methods = list ( m... |
def get_app_list ( site , request ) :
"""Returns a sorted list of all the installed apps that have been
registered in this site .""" | app_dict = _build_app_dict ( site , request )
# Sort the apps alphabetically .
app_list = sorted ( app_dict . values ( ) , key = lambda x : x [ 'name' ] . lower ( ) )
# Sort the models alphabetically within each app .
for app in app_list :
app [ 'models' ] . sort ( key = lambda x : x [ 'name' ] )
return app_list |
def __set_tab_title ( self , index ) :
"""Sets the name and toolTip of the * * Script _ Editor _ tabWidget * * Widget tab with given index .
: param index : Index of the tab containing the Model editor .
: type index : int""" | editor = self . get_widget ( index )
if not editor :
return
title , tool_tip = foundations . strings . to_string ( editor . title ) , foundations . strings . to_string ( editor . file )
LOGGER . debug ( "> Setting '{0}' window title and '{1}' toolTip to tab with '{2}' index." . format ( title , tool_tip , index ) )... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.