signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def getLocalityGroups ( self , login , tableName ) :
"""Parameters :
- login
- tableName""" | self . send_getLocalityGroups ( login , tableName )
return self . recv_getLocalityGroups ( ) |
def per_callback_query_chat_id ( types = 'all' ) :
""": param types :
` ` all ` ` or a list of chat types ( ` ` private ` ` , ` ` group ` ` , ` ` channel ` ` )
: return :
a seeder function that returns a callback query ' s originating chat id
if the chat type is in ` ` types ` ` .""" | def f ( msg ) :
if ( flavor ( msg ) == 'callback_query' and 'message' in msg and ( types == 'all' or msg [ 'message' ] [ 'chat' ] [ 'type' ] in types ) ) :
return msg [ 'message' ] [ 'chat' ] [ 'id' ]
else :
return None
return f |
def _update_plugin ( package_name ) :
'''Update plugin ( no user interface ) .
. . versionadded : : 0.19
Parameters
package _ name : str , optional
Conda MicroDrop plugin package name , e . g . , ` microdrop . mr - box - plugin ` .
Returns
dict
If plugin was updated successfully , output will * at lea... | try :
update_json_log = plugin_install ( package_name )
except RuntimeError , exception :
if 'CondaHTTPError' in str ( exception ) :
raise IOError ( 'Error accessing update server.' )
else :
raise
if update_json_log . get ( 'success' ) :
if 'actions' in update_json_log : # Plugin was upd... |
def from_string ( type_string ) :
'''Returns the correct constant for a given string .
@ raises InvalidCompositeTypeError''' | if type_string == NONE :
return NONE
elif type_string == PERIODIC_EC_SHARED :
return PERIODC_EC_SHARED
elif type_string == PERIODIC_STATE_SHARED :
return PERIODIC_STATE_SHARED
elif type_string == GROUPING :
return GROUPING
elif type_string == FSM_EC_SHARED :
return FSM_EC_SHARED
elif type_string == ... |
def safe_call ( self , kwargs , args = None ) :
"""Call the underlying function safely , given a set of keyword
arguments . If successful , the function return value ( likely
None ) will be returned . If the underlying function raises an
exception , the return value will be the exception message ,
unless an... | # Now let ' s call the function
try :
return self . _func ( ** kwargs )
except Exception as exc :
if args and getattr ( args , 'debug' , False ) :
raise
return str ( exc ) |
def set_indent ( indent = 2 , logger = "TaskLogger" ) :
"""Set the indent function
Convenience function to set the indent size
Parameters
indent : int , optional ( default : 2)
number of spaces by which to indent based on the
number of tasks currently running `
Returns
logger : TaskLogger""" | tasklogger = get_tasklogger ( logger )
tasklogger . set_indent ( indent )
return tasklogger |
def savetostr ( self , sortkey = True ) :
"""Save configurations to a single string""" | return '' . join ( k + '=' + repr ( v ) + '\n' for k , v in self . config_items ( sortkey ) ) |
def get_multizone_status ( host , services = None , zconf = None ) :
""": param host : Hostname or ip to fetch status from
: type host : str
: return : The multizone status as a named tuple .
: rtype : pychromecast . dial . MultizoneStatus or None""" | try :
status = status = _get_status ( host , services , zconf , "/setup/eureka_info?params=multizone" )
dynamic_groups = [ ]
if 'multizone' in status and 'dynamic_groups' in status [ 'multizone' ] :
for group in status [ 'multizone' ] [ 'dynamic_groups' ] :
name = group . get ( 'name' , ... |
def GetCpuShares ( self ) :
'''Retrieves the number of CPU shares allocated to the virtual machine . For
information about how an ESX server uses CPU shares to manage virtual
machine priority , see the vSphere Resource Management Guide .''' | counter = c_uint ( )
ret = vmGuestLib . VMGuestLib_GetCpuShares ( self . handle . value , byref ( counter ) )
if ret != VMGUESTLIB_ERROR_SUCCESS :
raise VMGuestLibException ( ret )
return counter . value |
def trim_ordered_range_list ( ranges , start , finish ) :
"""A function to help with slicing a mapping
Start with a list of ranges and get another list of ranges constrained by start ( 0 - indexed ) and finish ( 1 - indexed )
: param ranges : ordered non - overlapping ranges on the same chromosome
: param sta... | z = 0
keep_ranges = [ ]
for inrng in self . ranges :
z += 1
original_rng = inrng
rng = inrng . copy ( )
# we will be passing it along and possibly be cutting it
done = False ;
# print ' exon length ' + str ( rng . length ( ) )
if start >= index and start < index + original_rng . length ( ) :... |
def run_as ( self , identifiers ) :
""": type identifiers : subject _ abcs . IdentifierCollection""" | if ( not self . has_identifiers ) :
msg = ( "This subject does not yet have an identity. Assuming the " "identity of another Subject is only allowed for Subjects " "with an existing identity. Try logging this subject in " "first, or using the DelegatingSubject.Builder " "to build ad hoc Subject instances with ide... |
def get_chain ( self , name , table = "filter" ) :
"""Get the list of rules for a particular chain . Chain order is kept intact .
Args :
name ( str ) : chain name , e . g . ` `
table ( str ) : table name , defaults to ` ` filter ` `
Returns :
list : rules""" | return [ r for r in self . rules if r [ "table" ] == table and r [ "chain" ] == name ] |
def build_signature_template ( key_id , algorithm , headers ) :
"""Build the Signature template for use with the Authorization header .
key _ id is the mandatory label indicating to the server which secret to use
algorithm is one of the supported algorithms
headers is a list of http headers to be included in ... | param_map = { 'keyId' : key_id , 'algorithm' : algorithm , 'signature' : '%s' }
if headers :
headers = [ h . lower ( ) for h in headers ]
param_map [ 'headers' ] = ' ' . join ( headers )
kv = map ( '{0[0]}="{0[1]}"' . format , param_map . items ( ) )
kv_string = ',' . join ( kv )
sig_string = 'Signature {0}' . ... |
def default_help_formatter ( quick_helps ) :
"""Apply default formatting for help messages
: param quick _ helps : list of tuples containing help info""" | ret = ''
for line in quick_helps :
cmd_path , param_hlp , cmd_hlp = line
ret += ' ' . join ( cmd_path ) + ' '
if param_hlp :
ret += param_hlp + ' '
ret += '- ' + cmd_hlp + '\n'
return ret |
def _match_exec ( self , i ) :
"""Looks at line ' i ' for a subroutine or function definition .""" | self . col_match = self . RE_EXEC . match ( self . _source [ i ] )
if self . col_match is not None :
if self . col_match . group ( "codetype" ) == "function" :
self . el_type = Function
else :
self . el_type = Subroutine
self . el_name = self . col_match . group ( "name" )
return True
el... |
def selections ( self ) :
r"""The tuple of current ` Selection ` \ s .""" | for sel in self . _selections :
if sel . annotation . axes is None :
raise RuntimeError ( "Annotation unexpectedly removed; " "use 'cursor.remove_selection' instead" )
return tuple ( self . _selections ) |
def clean ( self , * args , ** kwargs ) :
"""Check if comments can be inserted for parent node or parent layer""" | # check done only for new nodes !
if not self . pk :
node = self . node
# ensure comments for this node are allowed
if node . participation_settings . comments_allowed is False :
raise ValidationError ( "Comments not allowed for this node" )
# ensure comments for this layer are allowed
if 'n... |
def includes_missingalt ( data ) :
"""As of GATK 4.1.0.0 , variants with missing alts are generated
( see https : / / github . com / broadinstitute / gatk / issues / 5650)""" | MISSINGALT_VERSION = LooseVersion ( "4.1.0.0" )
version = LooseVersion ( broad . get_gatk_version ( config = dd . get_config ( data ) ) )
return version >= MISSINGALT_VERSION |
def help ( i ) :
"""Input : {
Output : {
return - return code = 0 , if successful
> 0 , if error
( error ) - error text if return > 0
help - help text""" | o = i . get ( 'out' , '' )
m = i . get ( 'module_uoa' , '' )
if m == '' :
m = '<module_uoa>'
h = 'Usage: ' + cfg [ 'cmd' ] . replace ( '$#module_uoa#$' , m ) + '\n'
h += '\n'
h += ' Common actions:\n'
for q in sorted ( cfg [ 'common_actions' ] ) :
s = q
desc = cfg [ 'actions' ] [ q ] . get ( 'desc' , '' )
... |
def wait ( self ) :
'''Wait for the subprocess to finish .
Returns the exit code .''' | status = self . proc . wait ( )
if status >= 0 :
self . exitstatus = status
self . signalstatus = None
else :
self . exitstatus = None
self . signalstatus = - status
self . terminated = True
return status |
def breaks_from_binwidth ( x_range , binwidth = None , center = None , boundary = None ) :
"""Calculate breaks given binwidth
Parameters
x _ range : array _ like
Range over with to calculate the breaks . Must be
of size 2.
binwidth : float
Separation between the breaks
center : float
The center of o... | if binwidth <= 0 :
raise PlotnineError ( "The 'binwidth' must be positive." )
if boundary is not None and center is not None :
raise PlotnineError ( "Only one of 'boundary' and 'center' " "may be specified." )
elif boundary is None :
if center is None : # This puts min and max of data in outer half
# of... |
def join_list ( values , delimiter = ', ' , transform = None ) :
"""Concatenates the upper - cased values using the given delimiter if
the given values variable is a list . Otherwise it is just returned .
: param values : List of strings or string .
: param delimiter : The delimiter used to join the values . ... | # type : ( Union [ List [ str ] , str ] , str ) - > str
if transform is None :
transform = _identity
if values is not None and not isinstance ( values , ( str , bytes ) ) :
values = delimiter . join ( transform ( x ) for x in values )
return values |
def parse_labels ( result ) :
'''fix up the labels , meaning parse to json if needed , and return
original updated object
Parameters
result : the json object to parse from inspect''' | if "data" in result :
labels = result [ 'data' ] [ 'attributes' ] . get ( 'labels' ) or { }
elif 'attributes' in result :
labels = result [ 'attributes' ] . get ( 'labels' ) or { }
# If labels included , try parsing to json
try :
labels = jsonp . loads ( labels )
except :
pass
if "data" in result :
... |
def filter_queryset ( self , request , queryset , view ) :
"""Filter out any artifacts which the requesting user does not have permission to view .""" | if request . user . is_superuser :
return queryset
return queryset . filter ( status__user = request . user ) |
def filter_bboxes ( bboxes , rows , cols , min_area = 0. , min_visibility = 0. ) :
"""Remove bounding boxes that either lie outside of the visible area by more then min _ visibility
or whose area in pixels is under the threshold set by ` min _ area ` . Also it crops boxes to final image size .
Args :
bboxes (... | resulting_boxes = [ ]
for bbox in bboxes :
transformed_box_area = calculate_bbox_area ( bbox , rows , cols )
bbox [ : 4 ] = np . clip ( bbox [ : 4 ] , 0 , 1. )
clipped_box_area = calculate_bbox_area ( bbox , rows , cols )
if not transformed_box_area or clipped_box_area / transformed_box_area <= min_visi... |
def set_prior_probs ( self , statements ) :
"""Sets the prior belief probabilities for a list of INDRA Statements .
The Statements are assumed to be de - duplicated . In other words ,
each Statement in the list passed to this function is assumed to have
a list of Evidence objects that support it . The prior p... | self . scorer . check_prior_probs ( statements )
for st in statements :
st . belief = self . scorer . score_statement ( st ) |
def store ( self ) :
"""Store and return packages for upgrading""" | data = repo_data ( self . PACKAGES_TXT , "slack" , self . flag )
black = BlackList ( ) . packages ( pkgs = data [ 0 ] , repo = "slack" )
for name , loc , comp , uncomp in zip ( data [ 0 ] , data [ 1 ] , data [ 2 ] , data [ 3 ] ) :
status ( 0.0003 )
repo_pkg_name = split_package ( name ) [ 0 ]
if ( not os . ... |
def _http_call ( self , url , method , ** kwargs ) :
"""Makes a http call . Logs response information .""" | logging . debug ( "Request[{0}]: {1}" . format ( method , url ) )
start_time = datetime . datetime . now ( )
logging . debug ( "Header: {0}" . format ( kwargs [ 'headers' ] ) )
logging . debug ( "Params: {0}" . format ( kwargs [ 'data' ] ) )
response = requests . request ( method , url , verify = False , ** kwargs )
du... |
def do ( self , arg ) :
". example - This is an example plugin for the command line debugger" | print "This is an example command."
print "%s.do(%r, %r):" % ( __name__ , self , arg )
print " last event" , self . lastEvent
print " prefix" , self . cmdprefix
print " arguments" , self . split_tokens ( arg ) |
def get_requested_form ( self , request ) :
"""Returns an instance of a form requested .""" | flow_name = self . get_flow_name ( )
flow_key = '%s_flow' % self . flow_type
flow_enabled = self . enabled
form_data = None
if ( flow_enabled and request . method == 'POST' and request . POST . get ( flow_key , False ) and request . POST [ flow_key ] == flow_name ) :
form_data = request . POST
form = self . init_fo... |
def log_rule_info ( self ) :
"""Collects rule information and send to logit function to log to syslog""" | for c in sorted ( self . broker . get_by_type ( rule ) , key = dr . get_name ) :
v = self . broker [ c ]
_type = v . get ( "type" )
if _type :
if _type != "skip" :
msg = "Running {0} " . format ( dr . get_name ( c ) )
self . logit ( msg , self . pid , self . user , "insights-... |
def get_object_stats ( self , obj_name ) :
""": param obj _ name : requested object name
: returns : all statistics values for the requested object .""" | return dict ( zip ( self . captions , self . statistics [ obj_name ] ) ) |
def add_custom_frame ( frame , name , thread_id ) :
'''It ' s possible to show paused frames by adding a custom frame through this API ( it ' s
intended to be used for coroutines , but could potentially be used for generators too ) .
: param frame :
The topmost frame to be shown paused when a thread with thre... | with CustomFramesContainer . custom_frames_lock :
curr_thread_id = get_current_thread_id ( threading . currentThread ( ) )
next_id = CustomFramesContainer . _next_frame_id = CustomFramesContainer . _next_frame_id + 1
# Note : the frame id kept contains an id and thread information on the thread where the fr... |
def process ( meta ) :
"""Saves metadata fields in global variables and returns a few
computed fields .""" | # pylint : disable = global - statement
global capitalize
global use_cleveref_default
global plusname
global starname
global numbersections
# Read in the metadata fields and do some checking
for name in [ 'eqnos-cleveref' , 'xnos-cleveref' , 'cleveref' ] : # ' xnos - cleveref ' enables cleveref in all 3 of fignos / eqn... |
def parse_schedule ( schedule , action ) :
"""parses the given schedule and validates at""" | error = None
scheduled_at = None
try :
scheduled_at = dateutil . parser . parse ( schedule )
if scheduled_at . tzinfo is None :
error = 'Timezone information is mandatory for the scheduled {0}' . format ( action )
status_code = 400
elif scheduled_at < datetime . datetime . now ( tzutc ) :
... |
def _refresh_state ( self ) :
"""Refresh the job info .""" | # DataFlow ' s DataflowPipelineResult does not refresh state , so we have to do it ourselves
# as a workaround .
self . _runner_results . _job = ( self . _runner_results . _runner . dataflow_client . get_job ( self . _runner_results . job_id ( ) ) )
self . _is_complete = self . _runner_results . state in [ 'STOPPED' , ... |
def _prepare_cookies ( self , command , url ) :
"""Extract cookies from the requests session and add them to the command""" | req = requests . models . Request ( )
req . method = 'GET'
req . url = url
cookie_values = requests . cookies . get_cookie_header ( self . session . cookies , req )
if cookie_values :
self . _add_cookies ( command , cookie_values ) |
def get_address ( self , address ) :
"""Retrieve an address from the wallet .
: param str address : address in the wallet to look up
: return : an instance of : class : ` Address ` class""" | params = self . build_basic_request ( )
params [ 'address' ] = address
response = util . call_api ( "merchant/{0}/address_balance" . format ( self . identifier ) , params , base_url = self . service_url )
json_response = json . loads ( response )
self . parse_error ( json_response )
return Address ( json_response [ 'ba... |
def load_files ( self ) -> selectiontools . Selections :
"""Read all network files of the current working directory , structure
their contents in a | selectiontools . Selections | object , and return it .""" | devicetools . Node . clear_all ( )
devicetools . Element . clear_all ( )
selections = selectiontools . Selections ( )
for ( filename , path ) in zip ( self . filenames , self . filepaths ) : # Ensure both ` Node ` and ` Element ` start with a ` fresh ` memory .
devicetools . Node . extract_new ( )
devicetools .... |
def validate ( self , data ) :
"""We need to set some timestamps according to the accounting packet type
* update _ time : set everytime a Interim - Update / Stop packet is received
* stop _ time : set everytime a Stop packet is received
* session _ time : calculated if not present in the accounting packet
... | time = timezone . now ( )
status_type = data . pop ( 'status_type' )
if status_type == 'Interim-Update' :
data [ 'update_time' ] = time
if status_type == 'Stop' :
data [ 'update_time' ] = time
data [ 'stop_time' ] = time
return data |
def windows_union ( windows ) :
"""Given a list of ( beginning , ending ) , return a minimal version that contains the same ranges .
: rtype : list""" | def fix_overlap ( left , right ) :
if left == right :
return [ left ]
assert left [ 0 ] < right [ 0 ]
if left [ 1 ] >= right [ 0 ] :
if right [ 1 ] > left [ 1 ] :
return [ ( left [ 0 ] , right [ 1 ] ) ]
else :
return [ left ]
return [ left , right ]
if len... |
def get_warmer ( self , doc_types = None , indices = None , name = None , querystring_args = None ) :
"""Retrieve warmer
: param doc _ types : list of document types
: param warmer : anything with ` ` serialize ` ` method or a dictionary
: param name : warmer name . If not provided , all warmers will be retur... | name = name or ''
if not querystring_args :
querystring_args = { }
doc_types_str = ''
if doc_types :
doc_types_str = '/' + ',' . join ( doc_types )
path = '/{0}{1}/_warmer/{2}' . format ( ',' . join ( indices ) , doc_types_str , name )
return self . _send_request ( method = 'GET' , path = path , params = querys... |
def list_formats ( format_type , backend = None ) :
"""Returns list of supported formats for a particular
backend .""" | if backend is None :
backend = Store . current_backend
mode = Store . renderers [ backend ] . mode if backend in Store . renderers else None
else :
split = backend . split ( ':' )
backend , mode = split if len ( split ) == 2 else ( split [ 0 ] , 'default' )
if backend in Store . renderers :
return S... |
def get ( self , obj_id ) :
"""Get a document or a page using its ID
Won ' t instantiate them if they are not yet available""" | if BasicPage . PAGE_ID_SEPARATOR in obj_id :
( docid , page_nb ) = obj_id . split ( BasicPage . PAGE_ID_SEPARATOR )
page_nb = int ( page_nb )
return self . _docs_by_id [ docid ] . pages [ page_nb ]
return self . _docs_by_id [ obj_id ] |
def regrep ( filename , patterns , reverse = False , terminate_on_match = False , postprocess = str ) :
"""A powerful regular expression version of grep .
Args :
filename ( str ) : Filename to grep .
patterns ( dict ) : A dict of patterns , e . g . ,
{ " energy " : " energy \ ( sigma - > 0 \ ) \ s + = \ s +... | compiled = { k : re . compile ( v ) for k , v in patterns . items ( ) }
matches = collections . defaultdict ( list )
gen = reverse_readfile ( filename ) if reverse else zopen ( filename , "rt" )
for i , l in enumerate ( gen ) :
for k , p in compiled . items ( ) :
m = p . search ( l )
if m :
... |
def record_file_factory ( self ) :
"""Load default record file factory .""" | try :
get_distribution ( 'invenio-records-files' )
from invenio_records_files . utils import record_file_factory
default = record_file_factory
except DistributionNotFound :
def default ( pid , record , filename ) :
return None
return load_or_import_from_config ( 'PREVIEWER_RECORD_FILE_FACOTRY' ,... |
def cover ( cls , bits , wildcard_probability ) :
"""Create a new bit condition that matches the provided bit string ,
with the indicated per - index wildcard probability .
Usage :
condition = BitCondition . cover ( bitstring , . 33)
assert condition ( bitstring )
Arguments :
bits : A BitString which th... | if not isinstance ( bits , BitString ) :
bits = BitString ( bits )
mask = BitString ( [ random . random ( ) > wildcard_probability for _ in range ( len ( bits ) ) ] )
return cls ( bits , mask ) |
def parse ( cls , s ) :
"""Parse a string to produce a : class : ` . Date ` .
Accepted formats :
' YYYY - MM - DD '
: param s :
: return :""" | try :
numbers = map ( int , s . split ( "-" ) )
except ( ValueError , AttributeError ) :
raise ValueError ( "Date string must be in format YYYY-MM-DD" )
else :
numbers = list ( numbers )
if len ( numbers ) == 3 :
return cls ( * numbers )
raise ValueError ( "Date string must be in format YYYY... |
def get_lobbies ( session , game_id ) :
"""Get lobbies for a game .""" | if isinstance ( game_id , str ) :
game_id = lookup_game_id ( game_id )
lobbies = _make_request ( session , LOBBY_URL , game_id )
for lobby in lobbies : # pylint : disable = len - as - condition
if len ( lobby [ 'ladders' ] ) > 0 :
lobby [ 'ladders' ] = lobby [ 'ladders' ] [ : - 1 ] . split ( '|' )
retur... |
def per_country_data ( self ) :
"""Return download data by country .
: return : dict of cache data ; keys are datetime objects , values are
dict of country ( str ) to count ( int )
: rtype : dict""" | ret = { }
for cache_date in self . cache_dates :
data = self . _cache_get ( cache_date )
ret [ cache_date ] = { }
for cc , count in data [ 'by_country' ] . items ( ) :
k = '%s (%s)' % ( self . _alpha2_to_country ( cc ) , cc )
ret [ cache_date ] [ k ] = count
if len ( ret [ cache_date ] )... |
async def find_recent_news ( self , ** params ) :
"""Looking up recent news for account .
Accepts :
- public _ key
Returns :
- list with dicts or empty""" | # Check if params is not empty
if params . get ( "message" ) :
params = json . loads ( params . get ( "message" , "{}" ) )
if not params :
return { "error" : 400 , "reason" : "Missed required fields" }
# Check if required parameter does exist
public_key = params . get ( "public_key" , None )
if not public_key :... |
def resolve ( self , pid ) :
"""Get Object Locations for Object .""" | client = d1_cli . impl . client . CLICNClient ( ** self . _cn_client_connect_params_from_session ( ) )
object_location_list_pyxb = client . resolve ( pid )
for location in object_location_list_pyxb . objectLocation :
d1_cli . impl . util . print_info ( location . url ) |
def request_raw ( self , method , url , params = None , supplied_headers = None ) :
"""Mechanism for issuing an API call""" | if self . api_key :
my_api_key = self . api_key
else :
from stripe import api_key
my_api_key = api_key
if my_api_key is None :
raise error . AuthenticationError ( "No API key provided. (HINT: set your API key using " '"stripe.api_key = <API-KEY>"). You can generate API keys ' "from the Stripe web interf... |
def add_file_arg ( self , filename ) :
"""Add a file argument to the executable . Arguments are appended after any
options and their order is guaranteed . Also adds the file name to the
list of required input data for this job .
@ param filename : file to add as argument .""" | self . __arguments . append ( filename )
if filename not in self . __input_files :
self . __input_files . append ( filename ) |
def split_words ( line ) :
"""Return the list of words contained in a line .""" | # Normalize any camel cased words first
line = _NORM_REGEX . sub ( r'\1 \2' , line )
return [ normalize ( w ) for w in _WORD_REGEX . split ( line ) ] |
def get_instruction ( self , idx , off = None ) :
"""Get a particular instruction by using ( default ) the index of the address if specified
: param idx : index of the instruction ( the position in the list of the instruction )
: type idx : int
: param off : address of the instruction
: type off : int
: r... | if off is not None :
idx = self . off_to_pos ( off )
if self . cached_instructions is None :
self . get_instructions ( )
return self . cached_instructions [ idx ] |
def _get_batches ( self , mapping , batch_size = 10000 ) :
"""Get data from the local db""" | action = mapping . get ( "action" , "insert" )
fields = mapping . get ( "fields" , { } ) . copy ( )
static = mapping . get ( "static" , { } )
lookups = mapping . get ( "lookups" , { } )
record_type = mapping . get ( "record_type" )
# Skip Id field on insert
if action == "insert" and "Id" in fields :
del fields [ "I... |
def zip_code ( anon , obj , field , val ) :
"""Returns a randomly generated US zip code ( not necessarily valid , but will look like one ) .""" | return anon . faker . zipcode ( field = field ) |
def eval ( self , amplstatements , ** kwargs ) :
"""Parses AMPL code and evaluates it as a possibly empty sequence of AMPL
declarations and statements .
As a side effect , it invalidates all entities ( as the passed statements
can contain any arbitrary command ) ; the lists of entities will be
re - populate... | if self . _langext is not None :
amplstatements = self . _langext . translate ( amplstatements , ** kwargs )
lock_and_call ( lambda : self . _impl . eval ( amplstatements ) , self . _lock )
self . _errorhandler_wrapper . check ( ) |
def escape_md_section ( text , snob = False ) :
"""Escapes markdown - sensitive characters across whole document sections .""" | text = md_backslash_matcher . sub ( r"\\\1" , text )
if snob :
text = md_chars_matcher_all . sub ( r"\\\1" , text )
text = md_dot_matcher . sub ( r"\1\\\2" , text )
text = md_plus_matcher . sub ( r"\1\\\2" , text )
text = md_dash_matcher . sub ( r"\1\\\2" , text )
return text |
def realsorted ( seq , key = None , reverse = False , alg = ns . DEFAULT ) :
"""Convenience function to properly sort signed floats .
A signed float in a string could be " a - 5.7 " . This is a wrapper around
` ` natsorted ( seq , alg = ns . REAL ) ` ` .
The behavior of : func : ` realsorted ` for ` natsort `... | return natsorted ( seq , key , reverse , alg | ns . REAL ) |
def bakan_bahar_ensemble_align ( coords , tolerance = 0.001 , verbose = False ) :
'''input : a list of coordinates in the format :
[ ( x , y , z ) , ( x , y , z ) , ( x , y , z ) ] , # atoms in model 1
[ ( x , y , z ) , ( x , y , z ) , ( x , y , z ) ] , # atoms in model 2
# etc .''' | rmsd_tolerance = float ( "inf" )
average_struct_coords = np . array ( random . choice ( coords ) )
cycle_count = 0
while ( rmsd_tolerance > tolerance ) :
if verbose :
print 'Cycle %d alignment, current tolerance: %.4f (threshold %.4f)' % ( cycle_count , rmsd_tolerance , tolerance )
old_average_struct_co... |
def __get_settings ( self ) :
"""Returns the current search and replace settings .
: return : Settings .
: rtype : dict""" | return { "case_sensitive" : self . Case_Sensitive_checkBox . isChecked ( ) , "whole_word" : self . Whole_Word_checkBox . isChecked ( ) , "regular_expressions" : self . Regular_Expressions_checkBox . isChecked ( ) , "backward_search" : self . Backward_Search_checkBox . isChecked ( ) , "wrap_around" : self . Wrap_Around_... |
def send_datagram ( self , message ) :
"""Send a message over the UDP socket .
: param message : the message to send""" | host , port = message . destination
logger . debug ( "send_datagram - " + str ( message ) )
serializer = Serializer ( )
raw_message = serializer . serialize ( message )
try :
self . _socket . sendto ( raw_message , ( host , port ) )
except Exception as e :
if self . _cb_ignore_write_exception is not None and is... |
def recursively_convert_to_json_serializable ( test_obj ) :
"""Helper function to convert a dict object to one that is serializable
Args :
test _ obj : an object to attempt to convert a corresponding json - serializable object
Returns :
( dict ) A converted test _ object
Warning :
test _ obj may also be... | # Validate that all aruguments are of approved types , coerce if it ' s easy , else exception
# print ( type ( test _ obj ) , test _ obj )
# Note : Not 100 % sure I ' ve resolved this correctly . . .
try :
if not isinstance ( test_obj , list ) and np . isnan ( test_obj ) : # np . isnan is functionally vectorized , ... |
def submit_offline_reports ( self ) :
"""Submit offline reports using the enabled methods ( SMTP and / or HQ )
Returns a tuple of ( N sent reports , N remaining reports )""" | smtp_enabled = bool ( self . _smtp )
hq_enabled = bool ( self . _hq )
offline_reports = self . get_offline_reports ( )
logging . info ( 'Submitting %d offline crash reports' % len ( offline_reports ) )
offline_reports = offline_reports [ : self . send_at_most ]
if smtp_enabled :
try :
smtp_success = self . ... |
def frequency_cutoff_from_name ( name , m1 , m2 , s1z , s2z ) :
"""Returns the result of evaluating the frequency cutoff function
specified by ' name ' on a template with given parameters .
Parameters
name : string
Name of the cutoff function
m1 : float or numpy . array
First component mass in solar mas... | params = { "mass1" : m1 , "mass2" : m2 , "spin1z" : s1z , "spin2z" : s2z }
return named_frequency_cutoffs [ name ] ( params ) |
def _R ( delta , nums_actions , payoff_arrays , best_dev_gains , points , vertices , equations , u , IC , action_profile_payoff , extended_payoff , new_pts , W_new , tol = 1e-10 ) :
"""Updating the payoff convex hull by iterating all action pairs .
Using the R operator proposed by Abreu and Sannikov 2014.
Param... | n_new_pt = 0
for a0 in range ( nums_actions [ 0 ] ) :
for a1 in range ( nums_actions [ 1 ] ) :
action_profile_payoff [ 0 ] = payoff_arrays [ 0 ] [ a0 , a1 ]
action_profile_payoff [ 1 ] = payoff_arrays [ 1 ] [ a1 , a0 ]
IC [ 0 ] = u [ 0 ] + best_dev_gains [ 0 ] [ a0 , a1 ]
IC [ 1 ] = ... |
def can_be_appended_to ( self , left_converter , strict : bool ) -> bool :
"""Utility method to check if this ( self ) converter can be appended after the output of the provided converter .
This method does not check if it makes sense , it just checks if the output type of the left converter is
compliant with t... | is_able_to_take_input = self . is_able_to_convert ( strict , from_type = left_converter . to_type , to_type = JOKER )
if left_converter . is_generic ( ) :
return is_able_to_take_input and left_converter . is_able_to_convert ( strict , from_type = JOKER , to_type = self . from_type )
else :
return is_able_to_tak... |
def edge_refine_triangulation_by_vertices ( self , vertices ) :
"""return points defining a refined triangulation obtained by bisection of all edges
in the triangulation connected to any of the vertices in the list provided""" | triangles = self . identify_vertex_triangles ( vertices )
return self . edge_refine_triangulation_by_triangles ( triangles ) |
def set_handler ( self , language , obj ) :
"""Define a custom language handler for RiveScript objects .
Pass in a ` ` None ` ` value for the object to delete an existing handler ( for
example , to prevent Python code from being able to be run by default ) .
Look in the ` ` eg ` ` folder of the rivescript - p... | # Allow them to delete a handler too .
if obj is None :
if language in self . _handlers :
del self . _handlers [ language ]
else :
self . _handlers [ language ] = obj |
def sample_entropy ( time_series , sample_length , tolerance = None ) :
"""Calculates the sample entropy of degree m of a time _ series .
This method uses chebychev norm .
It is quite fast for random data , but can be slower is there is
structure in the input time series .
Args :
time _ series : numpy arr... | # The code below follows the sample length convention of Ref [ 1 ] so :
M = sample_length - 1 ;
time_series = np . array ( time_series )
if tolerance is None :
tolerance = 0.1 * np . std ( time_series )
n = len ( time_series )
# Ntemp is a vector that holds the number of matches . N [ k ] holds matches templates of... |
def add_message ( request , level , message , extra_tags = '' , fail_silently = False ) :
"""Attempts to add a message to the request using the ' messages ' app .""" | if not horizon_message_already_queued ( request , message ) :
if request . is_ajax ( ) :
tag = constants . DEFAULT_TAGS [ level ]
# if message is marked as safe , pass " safe " tag as extra _ tags so
# that client can skip HTML escape for the message when rendering
if isinstance ( me... |
def _get_next_buffered_row ( self ) :
"""Get the next row for iteration .""" | if self . _iter_row == self . _iter_nrows :
raise StopIteration
if self . _row_buffer_index >= self . _iter_row_buffer :
self . _buffer_iter_rows ( self . _iter_row )
data = self . _row_buffer [ self . _row_buffer_index ]
self . _iter_row += 1
self . _row_buffer_index += 1
return data |
def add_file_ident_desc ( self , new_fi_desc , logical_block_size ) : # type : ( UDFFileIdentifierDescriptor , int ) - > int
'''A method to add a new UDF File Identifier Descriptor to this UDF File
Entry .
Parameters :
new _ fi _ desc - The new UDF File Identifier Descriptor to add .
logical _ block _ size ... | if not self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'UDF File Entry not initialized' )
if self . icb_tag . file_type != 4 :
raise pycdlibexception . PyCdlibInvalidInput ( 'Can only add a UDF File Identifier to a directory' )
self . fi_descs . append ( new_fi_desc )
num_bytes_to_add = UD... |
def send_build_close ( params , response_url ) :
'''send build close sends a final response ( post ) to the server to bring down
the instance . The following must be included in params :
repo _ url , logfile , repo _ id , secret , log _ file , token''' | # Finally , package everything to send back to shub
response = { "log" : json . dumps ( params [ 'log_file' ] ) , "repo_url" : params [ 'repo_url' ] , "logfile" : params [ 'logfile' ] , "repo_id" : params [ 'repo_id' ] , "container_id" : params [ 'container_id' ] }
body = '%s|%s|%s|%s|%s' % ( params [ 'container_id' ] ... |
def update_port_precommit ( self , context ) :
"""Update port pre - database transaction commit event .""" | vlan_segment , vxlan_segment = self . _get_segments ( context . top_bound_segment , context . bottom_bound_segment )
orig_vlan_segment , orig_vxlan_segment = self . _get_segments ( context . original_top_bound_segment , context . original_bottom_bound_segment )
if ( self . _is_vm_migrating ( context , vlan_segment , or... |
def _pyshark_read_frame ( self ) :
"""Read frames .""" | from pcapkit . toolkit . pyshark import packet2dict , tcp_traceflow
# fetch PyShark packet
packet = next ( self . _extmp )
# def _ pyshark _ packet2chain ( packet ) :
# " " " Fetch PyShark packet protocol chain . " " "
# return ' : ' . join ( map ( lambda layer : layer . layer _ name . upper ( ) , packet . layers ) )
#... |
def job_from_file ( job_ini , job_id , username , ** kw ) :
"""Create a full job profile from a job config file .
: param job _ ini :
Path to a job . ini file
: param job _ id :
ID of the created job
: param username :
The user who will own this job profile and all results
: param kw :
Extra paramet... | hc_id = kw . get ( 'hazard_calculation_id' )
try :
oq = readinput . get_oqparam ( job_ini , hc_id = hc_id )
except Exception :
logs . dbcmd ( 'finish' , job_id , 'failed' )
raise
if 'calculation_mode' in kw :
oq . calculation_mode = kw . pop ( 'calculation_mode' )
if 'description' in kw :
oq . descr... |
def copy ( self ) :
'''Copy the container , put an invalidated copy of the condition in the new container''' | dup = super ( Conditional , self ) . copy ( )
condition = self . _condition . copy ( )
condition . invalidate ( self )
dup . _condition = condition
return dup |
def state ( self ) :
"""Which state the session is in .
Starting - all messages needed to get stream started .
Playing - keep - alive messages every self . session _ timeout .""" | if self . method in [ 'OPTIONS' , 'DESCRIBE' , 'SETUP' , 'PLAY' ] :
state = STATE_STARTING
elif self . method in [ 'KEEP-ALIVE' ] :
state = STATE_PLAYING
else :
state = STATE_STOPPED
_LOGGER . debug ( 'RTSP session (%s) state %s' , self . host , state )
return state |
def get_checksum ( self ) :
"""Return the md5 checksum of the delta file .""" | with open ( self . file , 'rb' ) as f :
cs = md5 ( f . read ( ) ) . hexdigest ( )
return cs |
def from_raw ( self , raw : RawScalar ) -> Optional [ bytes ] :
"""Override superclass method .""" | try :
return base64 . b64decode ( raw , validate = True )
except TypeError :
return None |
def get_content ( self , url , params = None , limit = 0 , place_holder = None , root_field = 'data' , thing_field = 'children' , after_field = 'after' , object_filter = None , ** kwargs ) :
"""A generator method to return reddit content from a URL .
Starts at the initial url , and fetches content using the ` aft... | _use_oauth = kwargs . get ( '_use_oauth' , self . is_oauth_session ( ) )
objects_found = 0
params = params or { }
fetch_all = fetch_once = False
if limit is None :
fetch_all = True
params [ 'limit' ] = 1024
# Just use a big number
elif limit > 0 :
params [ 'limit' ] = limit
else :
fetch_once = True
... |
def best_prediction ( self ) :
"""The highest value from among the predictions made by the action
sets in this match set .""" | if self . _best_prediction is None and self . _action_sets :
self . _best_prediction = max ( action_set . prediction for action_set in self . _action_sets . values ( ) )
return self . _best_prediction |
def get_widget_types ( self , scope , project = None ) :
"""GetWidgetTypes .
[ Preview API ] Get all available widget metadata in alphabetical order .
: param str scope :
: param str project : Project ID or project name
: rtype : : class : ` < WidgetTypesResponse > < azure . devops . v5_0 . dashboard . mode... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
query_parameters = { }
if scope is not None :
query_parameters [ '$scope' ] = self . _serialize . query ( 'scope' , scope , 'str' )
response = self . _send ( http_method = 'GET' , loc... |
def _unmangle_attribute_name ( name ) :
"""Unmangles attribute names so that correct Python variable names are
used for mapping attribute names .""" | # Python keywords cannot be used as variable names , an underscore should
# be appended at the end of each of them when defining attribute names .
name = _PYTHON_KEYWORD_MAP . get ( name , name )
# Attribute names are mangled with double underscore , as colon cannot
# be used as a variable character symbol in Python . ... |
def cmp_store_tlv_params ( self , intf , tlv_data ) :
"""Compare and store the received TLV .
Compares the received TLV with stored TLV . Store the new TLV if it is
different .""" | flag = False
attr_obj = self . get_attr_obj ( intf )
remote_evb_mode = self . pub_lldp . get_remote_evb_mode ( tlv_data )
if attr_obj . remote_evb_mode_uneq_store ( remote_evb_mode ) :
flag = True
remote_evb_cfgd = self . pub_lldp . get_remote_evb_cfgd ( tlv_data )
if attr_obj . remote_evb_cfgd_uneq_store ( remote_... |
def report_missing_dependencies ( self ) :
"""Show a QMessageBox with a list of missing hard dependencies""" | missing_deps = dependencies . missing_dependencies ( )
if missing_deps :
QMessageBox . critical ( self , _ ( 'Error' ) , _ ( "<b>You have missing dependencies!</b>" "<br><br><tt>%s</tt><br><br>" "<b>Please install them to avoid this message.</b>" "<br><br>" "<i>Note</i>: Spyder could work without some of these " "d... |
def check_required_args ( required_args , args ) :
"""Checks if all required _ args have a value .
: param required _ args : list of required args
: param args : kwargs
: return : True ( if an exception isn ' t raised )""" | for arg in required_args :
if arg not in args :
raise KeyError ( 'Required argument: %s' % arg )
return True |
def _run_varnishadm ( cmd , params = ( ) , ** kwargs ) :
'''Execute varnishadm command
return the output of the command
cmd
The command to run in varnishadm
params
Any additional args to add to the command line
kwargs
Additional options to pass to the salt cmd . run _ all function''' | cmd = [ 'varnishadm' , cmd ]
cmd . extend ( [ param for param in params if param is not None ] )
log . debug ( 'Executing: %s' , ' ' . join ( cmd ) )
return __salt__ [ 'cmd.run_all' ] ( cmd , python_shell = False , ** kwargs ) |
def execute ( self , conn , transaction = False ) :
"""Lists all primary datasets if pattern is not provided .""" | sql = self . sql
binds = { }
cursors = self . dbi . processData ( sql , binds , conn , transaction , returnCursor = True )
result = [ ]
for c in cursors :
result . extend ( self . formatCursor ( c , size = 100 ) )
return result |
def get_metric_group_definition ( self , group_name ) :
"""Get a faked metric group definition by its group name .
Parameters :
group _ name ( : term : ` string ` ) : Name of the metric group .
Returns :
: class : ~ zhmcclient . FakedMetricGroupDefinition ` : Definition of the
metric group .
Raises :
... | if group_name not in self . _metric_group_defs :
raise ValueError ( "A metric group definition with this name does " "not exist: {}" . format ( group_name ) )
return self . _metric_group_defs [ group_name ] |
def untranslated_policy ( self , default ) :
'''Get the policy for untranslated content''' | return self . generator . settings . get ( self . info . get ( 'policy' , None ) , default ) |
def read_rcfile ( ) :
"""Try to read a rcfile from a list of paths""" | files = [ '{}/.millipederc' . format ( os . environ . get ( 'HOME' ) ) , '/usr/local/etc/millipederc' , '/etc/millipederc' , ]
for filepath in files :
if os . path . isfile ( filepath ) :
with open ( filepath ) as rcfile :
return parse_rcfile ( rcfile )
return { } |
def clear ( self , decorated_function = None ) :
""": meth : ` WCacheStorage . clear ` method implementation ( Clears statistics also )""" | if decorated_function is not None and decorated_function in self . _storage :
self . _storage . pop ( decorated_function )
else :
self . _storage . clear ( )
if self . __statistic is True :
self . __cache_missed = 0
self . __cache_hit = 0 |
def selectSort ( list1 , list2 ) :
"""Razeni 2 poli najednou ( list ) pomoci metody select sort
input :
list1 - prvni pole ( hlavni pole pro razeni )
list2 - druhe pole ( vedlejsi pole ) ( kopirujici pozice pro razeni
podle hlavniho pole list1)
returns :
dve serazena pole - hodnoty se ridi podle prvniho... | length = len ( list1 )
for index in range ( 0 , length ) :
min = index
for index2 in range ( index + 1 , length ) :
if list1 [ index2 ] > list1 [ min ] :
min = index2
# Prohozeni hodnot hlavniho pole
list1 [ index ] , list1 [ min ] = list1 [ min ] , list1 [ index ]
# Prohozeni ho... |
def set_host_def ( self , hostdef ) :
'''Sets the hostdef param which will get passed to the Host Agent which
the agency starts if it becomes the master .''' | if self . _hostdef is not None :
self . info ( "Overwriting previous hostdef, which was %r" , self . _hostdef )
self . _hostdef = hostdef |
def initdoc ( request , namespace , docid , mode , template , context = None , configuration = None ) :
"""Initialise a document ( not invoked directly )""" | perspective = request . GET . get ( 'perspective' , 'document' )
if context is None :
context = { }
if 'configuration' in request . session :
configuration = request . session [ 'configuration' ]
elif configuration is None :
return fatalerror ( request , "No configuration specified" )
if configuration not i... |
def hhl_circuit ( A , C , t , register_size , * input_prep_gates ) :
"""Constructs the HHL circuit .
A is the input Hermitian matrix .
C and t are tunable parameters for the algorithm .
register _ size is the size of the eigenvalue register .
input _ prep _ gates is a list of gates to be applied to | 0 > to... | ancilla = cirq . GridQubit ( 0 , 0 )
# to store eigenvalues of the matrix
register = [ cirq . GridQubit ( i + 1 , 0 ) for i in range ( register_size ) ]
# to store input and output vectors
memory = cirq . GridQubit ( register_size + 1 , 0 )
c = cirq . Circuit ( )
hs = HamiltonianSimulation ( A , t )
pe = PhaseEstimatio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.