signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _set_table ( table_name ) :
"""Specify the table to work on .""" | _State . connection ( )
_State . reflect_metadata ( )
_State . table = sqlalchemy . Table ( table_name , _State . metadata , extend_existing = True )
if list ( _State . table . columns . keys ( ) ) == [ ] :
_State . table_pending = True
else :
_State . table_pending = False |
def wait_for_job ( self ) :
"""Use a redis blocking list call to wait for a job , and return it .""" | blpop_result = self . connection . blpop ( self . keys , self . timeout )
if blpop_result is None :
return None
queue_redis_key , job_ident = blpop_result
self . set_status ( 'running' )
return self . get_queue ( queue_redis_key ) , self . get_job ( job_ident ) |
def nodes ( self ) -> List [ str ] :
"""Return the list of nodes configured in the scenario ' s yaml .
Should the scenario use version 1 , we check if there is a ' setting ' .
If so , we derive the list of nodes from this dictionary , using its
' first ' , ' last ' and ' template ' keys . Should any of these ... | if self . _scenario_version == 1 and 'range' in self . _config :
range_config = self . _config [ 'range' ]
try :
start , stop = range_config [ 'first' ] , range_config [ 'last' ] + 1
except KeyError :
raise MissingNodesConfiguration ( 'Setting "range" must be a dict containing keys "first" a... |
def _fig_iplot ( self , validate = True , sharing = None , filename = '' , online = None , asImage = False , asUrl = False , asPlot = False , dimensions = None , display_image = True , ** kwargs ) :
"""Plots a figure in IPython
figure : figure
Plotly figure to be charted
validate : bool
If True then all val... | return iplot ( self , validate = validate , sharing = sharing , filename = filename , online = online , asImage = asImage , asUrl = asUrl , asPlot = asPlot , dimensions = dimensions , display_image = display_image , ** kwargs ) |
def write_bytecode ( self , f ) :
"""Dump the bytecode into the file or file like object passed .""" | if self . code is None :
raise TypeError ( 'can\'t write empty bucket' )
f . write ( bc_magic )
pickle . dump ( self . checksum , f , 2 )
marshal_dump ( self . code , f ) |
def get_cluster_nodes ( self ) :
"""return list with all nodes in cluster""" | if not hasattr ( self , '_cluster_nodes_cache' ) :
server , port = self . _servers [ 0 ] . split ( ':' )
try :
self . _cluster_nodes_cache = ( get_cluster_info ( server , port , self . _ignore_cluster_errors ) [ 'nodes' ] )
except ( socket . gaierror , socket . timeout ) as err :
raise Excep... |
def list ( self , name = None , all = False , filters = None ) :
"""List images on the server .
Args :
name ( str ) : Only show images belonging to the repository ` ` name ` `
all ( bool ) : Show intermediate image layers . By default , these are
filtered out .
filters ( dict ) : Filters to be processed o... | resp = self . client . api . images ( name = name , all = all , filters = filters )
return [ self . get ( r [ "Id" ] ) for r in resp ] |
def on_bindok ( self , unused_frame ) :
"""This method is invoked by pika when it receives the Queue . BindOk
response from RabbitMQ .""" | self . _logger . info ( 'Queue bound' )
while not self . _stopping : # perform the action that publishes on this client
self . producer ( self )
self . _logger . info ( "producer done" ) |
def rotate ( self , radians ) :
"""Modifies the current transformation matrix ( CTM )
by rotating the user - space axes by angle : obj : ` radians ` .
The rotation of the axes takes places
after any existing transformation of user space .
: type radians : float
: param radians :
Angle of rotation , in r... | cairo . cairo_rotate ( self . _pointer , radians )
self . _check_status ( ) |
def register ( self , model , backend = None , read_backend = None , include_related = True , ** params ) :
'''Register a : class : ` Model ` with this : class : ` Router ` . If the
model was already registered it does nothing .
: param model : a : class : ` Model ` class .
: param backend : a : class : ` std... | backend = backend or self . _default_backend
backend = getdb ( backend = backend , ** params )
if read_backend :
read_backend = getdb ( read_backend )
registered = 0
if isinstance ( model , Structure ) :
self . _structures [ model ] = StructureManager ( model , backend , read_backend , self )
return model
f... |
def show_hc ( kwargs = None , call = None ) :
'''Show the details of an existing health check .
CLI Example :
. . code - block : : bash
salt - cloud - f show _ hc gce name = hc''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The show_hc function must be called with -f or --function.' )
if not kwargs or 'name' not in kwargs :
log . error ( 'Must specify name of health check.' )
return False
conn = get_conn ( )
return _expand_item ( conn . ex_get_healthcheck ( kwargs [ 'name' ]... |
def guess ( system ) :
"""input format guess function . First guess by extension , then test by lines""" | files = system . files
maybe = [ ]
if files . input_format :
maybe . append ( files . input_format )
# first , guess by extension
for key , val in input_formats . items ( ) :
if type ( val ) == list :
for item in val :
if files . ext . strip ( '.' ) . lower ( ) == item :
mayb... |
def sitemap_check ( url ) :
"""Sitemap - Crawler are supported by every site which have a
Sitemap set in the robots . txt .
: param str url : the url to work on
: return bool : Determines if Sitemap is set in the site ' s robots . txt""" | response = urllib2 . urlopen ( UrlExtractor . get_sitemap_url ( url , True ) )
# Check if " Sitemap " is set
return "Sitemap:" in response . read ( ) . decode ( 'utf-8' ) |
def _update_svrg_gradients ( self ) :
"""Calculates gradients based on the SVRG update rule .""" | param_names = self . _exec_group . param_names
for ctx in range ( self . _ctx_len ) :
for index , name in enumerate ( param_names ) :
g_curr_batch_reg = self . _exec_group . grad_arrays [ index ] [ ctx ]
g_curr_batch_special = self . _mod_aux . _exec_group . grad_arrays [ index ] [ ctx ]
g_s... |
def save_model ( self , fname , pretty = False ) :
"""Saves the xml to file .
Args :
fname : output file location
pretty : attempts ! ! to pretty print the output""" | with open ( fname , "w" ) as f :
xml_str = ET . tostring ( self . root , encoding = "unicode" )
if pretty : # TODO : get a better pretty print library
parsed_xml = xml . dom . minidom . parseString ( xml_str )
xml_str = parsed_xml . toprettyxml ( newl = "" )
f . write ( xml_str ) |
def check_url ( self , url , is_image_src = False ) :
"""This method is used to check a URL .
Returns : obj : ` True ` if the URL is " safe " , : obj : ` False ` otherwise .
The default implementation only allows HTTP and HTTPS links . That means
no ` ` mailto : ` ` , no ` ` xmpp : ` ` , no ` ` ftp : ` ` , et... | return bool ( self . _allowed_url_re . match ( url ) ) |
def main ( argv = None ) :
"""Command line entry point""" | if not argv :
argv = sys . argv [ 1 : ]
parser = argparse . ArgumentParser ( description = _HELP_TEXT )
parser . add_argument ( 'input' , nargs = '?' , default = None )
parser . add_argument ( 'output' , nargs = '?' , default = None )
parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' ... |
def get_widgets ( self , duplicates ) :
"Create and format widget set ." | widgets = [ ]
for ( img , fp , human_readable_label ) in self . _all_images [ : self . _batch_size ] :
img_widget = self . make_img_widget ( img , layout = Layout ( height = '250px' , width = '300px' ) )
dropdown = self . make_dropdown_widget ( description = '' , options = self . _labels , value = human_readabl... |
def to_bytes ( self ) :
"""Convert the entire image to bytes .
: rtype : bytes""" | # grab the chunks we needs
out = [ PNG_SIGN ]
# FIXME : it ' s tricky to define " other _ chunks " . HoneyView stop the
# animation if it sees chunks other than fctl or idat , so we put other
# chunks to the end of the file
other_chunks = [ ]
seq = 0
# for first frame
png , control = self . frames [ 0 ]
# header
out . ... |
def retry ( self , delay = 0 , group = None , message = None ) :
'''Retry this job in a little bit , in the same queue . This is meant
for the times when you detect a transient failure yourself''' | args = [ 'retry' , self . jid , self . queue_name , self . worker_name , delay ]
if group is not None and message is not None :
args . append ( group )
args . append ( message )
return self . client ( * args ) |
def dependency_state ( widgets , drop_defaults = True ) :
"""Get the state of all widgets specified , and their dependencies .
This uses a simple dependency finder , including :
- any widget directly referenced in the state of an included widget
- any widget in a list / tuple attribute in the state of an incl... | # collect the state of all relevant widgets
if widgets is None : # Get state of all widgets , no smart resolution needed .
state = Widget . get_manager_state ( drop_defaults = drop_defaults , widgets = None ) [ 'state' ]
else :
try :
widgets [ 0 ]
except ( IndexError , TypeError ) :
widgets ... |
def split_str ( string ) :
"""Split string in half to return two strings""" | split = string . split ( ' ' )
return ' ' . join ( split [ : len ( split ) // 2 ] ) , ' ' . join ( split [ len ( split ) // 2 : ] ) |
def _check_output ( self , command ) :
"""Wrap the call to subprocess . check _ output ( ) to raise customized exceptions and always return strings .""" | try :
if sys . version_info [ 0 ] > 2 :
return check_output ( self . base_command + command , stderr = STDOUT ) . decode ( 'utf8' )
else :
return check_output ( self . base_command + command , stderr = STDOUT )
except CalledProcessError as command_error :
raise GitCommandException ( * comman... |
def read_config ( path = None , final = False ) :
"""Read Renku configuration .""" | try :
with open ( config_path ( path , final = final ) , 'r' ) as configfile :
return yaml . safe_load ( configfile ) or { }
except FileNotFoundError :
return { } |
def provisionar ( self , equipamentos , vips ) :
"""Realiza a inserção ou alteração de um grupo virtual para o sistema de Orquestração de VM .
: param equipamentos : Lista de equipamentos gerada pelo método " add _ equipamento " da
classe " EspecificacaoGrupoVirtual " .
: param vips : Lista de VIPs ger... | code , map = self . submit ( { 'equipamentos' : { 'equipamento' : equipamentos } , 'vips' : { 'vip' : vips } } , 'POST' , 'grupovirtual/' )
return self . response ( code , map , force_list = [ 'equipamento' , 'vip' ] ) |
def text_from_affiliation_elements ( department , institution , city , country ) :
"format an author affiliation from details" | return ', ' . join ( element for element in [ department , institution , city , country ] if element ) |
def parse ( self , stream ) :
"""Parses the keys + values from a config file .""" | items = OrderedDict ( )
for i , line in enumerate ( stream ) :
line = line . strip ( )
if not line or line [ 0 ] in [ "#" , ";" , "[" ] or line . startswith ( "---" ) :
continue
white_space = "\\s*"
key = "(?P<key>[^:=;#\s]+?)"
value = white_space + "[:=\s]" + white_space + "(?P<value>.+?)"
... |
def gen_permutations ( self , index = 0 , args = None ) :
"""Iterate recursively over layout . json parameter names .
TODO : Add indicator values .
Args :
index ( int , optional ) : The current index position in the layout names list .
args ( list , optional ) : Defaults to None . The current list of args .... | if args is None :
args = [ ]
try :
name = self . layout_json_names [ index ]
display = self . layout_json_params . get ( name , { } ) . get ( 'display' )
input_type = self . install_json_params ( ) . get ( name , { } ) . get ( 'type' )
if self . validate_layout_display ( self . input_table , display... |
def start_pipeline ( self , args = None , multi = False ) :
"""Initialize setup . Do some setup , like tee output , print some diagnostics , create temp files .
You provide only the output directory ( used for pipeline stats , log , and status flag files ) .""" | # Perhaps this could all just be put into _ _ init _ _ , but I just kind of like the idea of a start function
self . make_sure_path_exists ( self . outfolder )
# By default , Pypiper will mirror every operation so it is displayed both
# on sys . stdout * * and * * to a log file . Unfortunately , interactive python sess... |
def symput ( self , name , value ) :
""": param name : name of the macro varable to set :
: param value : python variable to use for the value to assign to the macro variable :
- name is a character
- value is a variable that can be resolved to a string""" | ll = self . submit ( "%let " + name + "=%NRBQUOTE(" + str ( value ) + ");\n" ) |
def main ( ) :
"""Example application that prints messages from the panel to the terminal .""" | try : # Retrieve the first USB device
device = AlarmDecoder ( USBDevice . find ( ) )
# Set up an event handler and open the device
device . on_message += handle_message
with device . open ( ) :
while True :
time . sleep ( 1 )
except Exception as ex :
print ( 'Exception:' , ex ) |
def post ( self , request ) :
'''Create a token , given an email and password . Removes all other
tokens for that user .''' | serializer = CreateTokenSerializer ( data = request . data )
serializer . is_valid ( raise_exception = True )
email = serializer . validated_data . get ( 'email' )
password = serializer . validated_data . get ( 'password' )
user = authenticate ( username = email , password = password )
if not user :
return Response... |
def _merge_data ( self , data : AnyMapping , * additional : AnyMapping ) -> dict :
r"""Merge base data and additional dicts .
: param data : Base data .
: param \ * additional : Additional data dicts to be merged into base dict .""" | return defaults ( dict ( data ) if not isinstance ( data , dict ) else data , * ( dict ( item ) for item in additional ) ) |
def peak_load ( self ) :
"""Get sectoral peak load""" | peak_load = pd . Series ( self . consumption ) . mul ( pd . Series ( self . grid . network . config [ 'peakload_consumption_ratio' ] ) . astype ( float ) , fill_value = 0 )
return peak_load |
async def accumulate ( source , func = op . add , initializer = None ) :
"""Generate a series of accumulated sums ( or other binary function )
from an asynchronous sequence .
If ` ` initializer ` ` is present , it is placed before the items
of the sequence in the calculation , and serves as a default
when t... | iscorofunc = asyncio . iscoroutinefunction ( func )
async with streamcontext ( source ) as streamer : # Initialize
if initializer is None :
try :
value = await anext ( streamer )
except StopAsyncIteration :
return
else :
value = initializer
# First value
y... |
def construct_parameter_pattern ( parameter ) :
"""Given a parameter definition returns a regex pattern that will match that
part of the path .""" | name = parameter [ 'name' ]
type = parameter [ 'type' ]
repeated = '[^/]'
if type == 'integer' :
repeated = '\d'
return "(?P<{name}>{repeated}+)" . format ( name = name , repeated = repeated ) |
def with_ctx ( func = None ) :
'''Auto create a new context if not available''' | if not func :
return functools . partial ( with_ctx )
@ functools . wraps ( func )
def func_with_context ( _obj , * args , ** kwargs ) :
if 'ctx' not in kwargs or kwargs [ 'ctx' ] is None : # if context is empty , ensure context
with _obj . ctx ( ) as new_ctx :
kwargs [ 'ctx' ] = new_ctx
... |
def authenticatedUserForKey ( self , key ) :
"""Find a persistent session for a user .
@ type key : L { bytes }
@ param key : The persistent session identifier .
@ rtype : L { bytes } or C { None }
@ return : The avatar ID the session belongs to , or C { None } if no such
session exists .""" | session = self . store . findFirst ( PersistentSession , PersistentSession . sessionKey == key )
if session is None :
return None
else :
session . renew ( )
return session . authenticatedAs |
def _update_value ( config , key , instruction , is_sensitive ) :
"""creates ( if needed ) and updates the value of the key in the config with a
value entered by the user
Parameters
config : ConfigParser object
existing configuration
key : string
key to update
instruction : string
text to show in th... | if config . has_option ( PROFILE , key ) :
current_value = config . get ( PROFILE , key )
else :
current_value = None
proposed = click . prompt ( instruction , default = current_value , hide_input = is_sensitive , confirmation_prompt = is_sensitive , )
if key == 'host' or key == 'prod_folder' :
if proposed ... |
def from_parser_builder ( plugins_dict , exclude_lines_regex = None ) :
""": param plugins _ dict : plugins dictionary received from ParserBuilder .
See example in tests . core . usage _ test .
: type exclude _ lines _ regex : str | None
: param exclude _ lines _ regex : optional regex for ignored lines .
:... | output = [ ]
for plugin_name in plugins_dict :
output . append ( from_plugin_classname ( plugin_name , exclude_lines_regex = exclude_lines_regex , ** plugins_dict [ plugin_name ] ) )
return tuple ( output ) |
def build_columns ( self , X , verbose = False ) :
"""construct the model matrix columns for the term
Parameters
X : array - like
Input dataset with n rows
verbose : bool
whether to show warnings
Returns
scipy sparse array with n rows""" | columns = super ( FactorTerm , self ) . build_columns ( X , verbose = verbose )
if self . coding == 'dummy' :
columns = columns [ : , 1 : ]
return columns |
def create_token ( self , request , ** kwargs ) :
"""Create a new obfuscated url info to use for accessing unpublished content .
: param request : a WSGI request object
: param kwargs : keyword arguments ( optional )
: return : ` rest _ framework . response . Response `""" | data = { "content" : self . get_object ( ) . id , "create_date" : get_request_data ( request ) [ "create_date" ] , "expire_date" : get_request_data ( request ) [ "expire_date" ] }
serializer = ObfuscatedUrlInfoSerializer ( data = data )
if not serializer . is_valid ( ) :
return Response ( serializer . errors , stat... |
def new_scheduler ( self , tasks , root_subject_types , build_root , work_dir , local_store_dir , ignore_patterns , execution_options , construct_directory_digest , construct_snapshot , construct_file_content , construct_files_content , construct_process_result , type_address , type_path_globs , type_directory_digest ,... | def func ( fn ) :
return Function ( self . context . to_key ( fn ) )
def ti ( type_obj ) :
return TypeId ( self . context . to_id ( type_obj ) )
scheduler = self . lib . scheduler_create ( tasks , # Constructors / functions .
func ( construct_directory_digest ) , func ( construct_snapshot ) , func ( construct_f... |
def verify_quote ( self , quote_id , extra ) :
"""Verifies that a quote order is valid .
extras = {
' hardware ' : { ' hostname ' : ' test ' , ' domain ' : ' testing . com ' } ,
' quantity ' : 2
manager = ordering . OrderingManager ( env . client )
result = manager . verify _ quote ( 12345 , extras )
: ... | container = self . generate_order_template ( quote_id , extra )
clean_container = { }
# There are a few fields that wil cause exceptions in the XML endpoing if you send in ' '
# reservedCapacityId and hostId specifically . But we clean all just to be safe .
# This for some reason is only a problem on verify _ quote .
f... |
def compute_match ( mapping , weight_dict ) :
"""Given a node mapping , compute match number based on weight _ dict .
Args :
mappings : a list of node index in AMR 2 . The ith element ( value j ) means node i in AMR 1 maps to node j in AMR 2.
Returns :
matching triple number
Complexity : O ( m * n ) , m i... | # If this mapping has been investigated before , retrieve the value instead of re - computing .
if veryVerbose :
print ( "Computing match for mapping" , file = DEBUG_LOG )
print ( mapping , file = DEBUG_LOG )
if tuple ( mapping ) in match_triple_dict :
if veryVerbose :
print ( "saved value" , match_... |
def querystring ( self ) :
"""Return original querystring but containing only managed keys
: return dict : dict of managed querystring parameter""" | return { key : value for ( key , value ) in self . qs . items ( ) if key . startswith ( self . MANAGED_KEYS ) or self . _get_key_values ( 'filter[' ) } |
def handle_length ( schema , field , validator , parent_schema ) :
"""Adds validation logic for ` ` marshmallow . validate . Length ` ` , setting the
values appropriately for ` ` fields . List ` ` , ` ` fields . Nested ` ` , and
` ` fields . String ` ` .
Args :
schema ( dict ) : The original JSON schema we ... | if isinstance ( field , fields . String ) :
minKey = 'minLength'
maxKey = 'maxLength'
elif isinstance ( field , ( fields . List , fields . Nested ) ) :
minKey = 'minItems'
maxKey = 'maxItems'
else :
raise ValueError ( "In order to set the Length validator for JSON " "schema, the field must be either... |
def energy_based_strength_of_connection ( A , theta = 0.0 , k = 2 ) :
"""Energy Strength Measure .
Compute a strength of connection matrix using an energy - based measure .
Parameters
A : sparse - matrix
matrix from which to generate strength of connection information
theta : float
Threshold parameter i... | if ( theta < 0 ) :
raise ValueError ( 'expected a positive theta' )
if not sparse . isspmatrix ( A ) :
raise ValueError ( 'expected sparse matrix' )
if ( k < 0 ) :
raise ValueError ( 'expected positive number of steps' )
if not isinstance ( k , int ) :
raise ValueError ( 'expected integer' )
if sparse .... |
def phone_search_query ( self , ** kwargs ) :
"""Query the Yelp Phone Search API .
documentation : https : / / www . yelp . com / developers / documentation / v3 / business _ search _ phone
required parameters :
* phone - phone number""" | if not kwargs . get ( 'phone' ) :
raise ValueError ( 'A valid phone number (parameter "phone") must be provided.' )
return self . _query ( PHONE_SEARCH_API_URL , ** kwargs ) |
def checkIfRemoteIsNewer ( self , localfile ) :
"""Need to figure out how biothings records releases ,
for now if the file exists we will assume it is
a fully downloaded cache
: param localfile : str file path
: return : boolean True if remote file is newer else False""" | is_remote_newer = False
if localfile . exists ( ) and localfile . stat ( ) . st_size > 0 :
LOG . info ( "File exists locally, using cache" )
else :
is_remote_newer = True
LOG . info ( "No cache file, fetching entries" )
return is_remote_newer |
def remove_user ( self , name ) :
"""Remove user ` name ` from this : class : ` Database ` .
User ` name ` will no longer have permissions to access this
: class : ` Database ` .
: Parameters :
- ` name ` : the name of the user to remove""" | try :
cmd = SON ( [ ( "dropUser" , name ) ] )
# Don ' t send { } as writeConcern .
if self . write_concern . acknowledged and self . write_concern . document :
cmd [ "writeConcern" ] = self . write_concern . document
self . command ( cmd )
except OperationFailure as exc : # See comment in add _ ... |
def _get_auth_packet ( self , username , password , client ) :
"""Get the pyrad authentication packet for the username / password and the
given pyrad client .""" | pkt = client . CreateAuthPacket ( code = AccessRequest , User_Name = username )
pkt [ "User-Password" ] = pkt . PwCrypt ( password )
pkt [ "NAS-Identifier" ] = 'django-radius'
for key , val in list ( getattr ( settings , 'RADIUS_ATTRIBUTES' , { } ) . items ( ) ) :
pkt [ key ] = val
return pkt |
def from_hsv ( cls , h , s , v ) :
"""Constructs a : class : ` Colour ` from an HSV tuple .""" | rgb = colorsys . hsv_to_rgb ( h , s , v )
return cls . from_rgb ( * ( int ( x * 255 ) for x in rgb ) ) |
def is_valid_method ( model , resource = None ) :
"""Return the error message to be sent to the client if the current
request passes fails any user - defined validation .""" | validation_function_name = 'is_valid_{}' . format ( request . method . lower ( ) )
if hasattr ( model , validation_function_name ) :
return getattr ( model , validation_function_name ) ( request , resource ) |
def get_resource ( self , device_id , resource_path ) :
"""Get a resource .
: param str device _ id : ID of the device ( Required )
: param str path : Path of the resource to get ( Required )
: returns : Device resource
: rtype Resource""" | resources = self . list_resources ( device_id )
for r in resources :
if r . path == resource_path :
return r
raise CloudApiException ( "Resource not found" ) |
def run_cli ( self , cli , args = None , node_paths = None ) :
"""Returns a command that when executed will run an installed cli via package manager .""" | cli_args = [ cli ]
if args :
cli_args . append ( '--' )
cli_args . extend ( args )
return self . run_command ( args = cli_args , node_paths = node_paths ) |
def get_jobs ( deployment_name , token_manager = None , app_url = defaults . APP_URL ) :
"""return list of currently running jobs""" | headers = token_manager . get_access_token_headers ( )
data_urls = get_data_urls ( deployment_name , app_url = app_url , token_manager = token_manager )
jobs = [ ]
for data_url in data_urls :
url = '%s/api/v1/jobs' % data_url
response = requests . get ( url , headers = headers )
if response . status_code ==... |
def mark ( self , element ) :
"""marks the requested resource in the cache as not fresh
: param element :
: return :""" | logger . debug ( "Element : {elm}" . format ( elm = str ( element ) ) )
if element is not None :
logger . debug ( "Mark as not fresh" )
element . freshness = False
logger . debug ( str ( self . cache ) ) |
def _get_page_data ( self , pno , zoom = 0 ) :
"""Return a PNG image for a document page number . If zoom is other than 0 , one of
the 4 page quadrants are zoomed - in instead and the corresponding clip returned .""" | dlist = self . dlist_tab [ pno ]
# get display list
if not dlist : # create if not yet there
self . dlist_tab [ pno ] = self . doc [ pno ] . getDisplayList ( )
dlist = self . dlist_tab [ pno ]
r = dlist . rect
# page rectangle
mp = r . tl + ( r . br - r . tl ) * 0.5
# rect middle point
mt = r . tl + ( r . tr - ... |
def free_vpcid_for_switch_list ( vpc_id , nexus_ips ) :
"""Free a vpc id for the given list of switch _ ips .""" | LOG . debug ( "free_vpcid_for_switch_list() called" )
if vpc_id != 0 :
update_vpc_entry ( nexus_ips , vpc_id , False , False ) |
def rmdir ( self , path ) :
"""Remove the folder named C { path } .
@ param path : name of the folder to remove
@ type path : str""" | path = self . _adjust_cwd ( path )
self . _log ( DEBUG , 'rmdir(%r)' % path )
self . _request ( CMD_RMDIR , path ) |
def loc_to_index ( self , loc ) :
"""Return index of the render window given a location index .
Parameters
loc : int , tuple , or list
Index of the renderer to add the actor to . For example ,
` ` loc = 2 ` ` or ` ` loc = ( 1 , 1 ) ` ` .
Returns
idx : int
Index of the render window .""" | if loc is None :
return self . _active_renderer_index
elif isinstance ( loc , int ) :
return loc
elif isinstance ( loc , collections . Iterable ) :
assert len ( loc ) == 2 , '"loc" must contain two items'
return loc [ 0 ] * self . shape [ 0 ] + loc [ 1 ] |
def get_url ( field ) :
"""Return file ' s url based on base url set in settings .""" | hydrated_path = _get_hydrated_path ( field )
base_url = getattr ( settings , 'RESOLWE_HOST_URL' , 'localhost' )
return "{}/data/{}/{}" . format ( base_url , hydrated_path . data_id , hydrated_path . file_name ) |
def check_key ( key , allowed ) :
"""Validate that the specified key is allowed according the provided
list of patterns .""" | if key in allowed :
return True
for pattern in allowed :
if fnmatch ( key , pattern ) :
return True
return False |
def _on_read_only_error ( self , command , future ) :
"""Invoked when a Redis node returns an error indicating it ' s in
read - only mode . It will use the ` ` INFO REPLICATION ` ` command to
attempt to find the master server and failover to that , reissuing
the command to that server .
: param command : Th... | failover_future = concurrent . TracebackFuture ( )
def on_replication_info ( _ ) :
common . maybe_raise_exception ( failover_future )
LOGGER . debug ( 'Failover closing current read-only connection' )
self . _closing = True
database = self . _connection . database
self . _connection . close ( )
... |
def _canFormAraPhrase ( araVerb , otherVerb ) :
'''Teeb kindlaks , kas etteantud ' ära ' verb ( araVerb ) yhildub teise verbiga ;
Arvestab järgimisi ühilduvusi :
ains 2 . pööre : ära _ neg . o + V _ o
ains 3 . pööre : ära _ neg . gu + V _ gu
mitm 1 . pööre : ära _ neg . me + V _ me
ära _ neg ... | global _verbAraAgreements
for i in range ( 0 , len ( _verbAraAgreements ) , 2 ) :
araVerbTemplate = _verbAraAgreements [ i ]
otherVerbTemplate = _verbAraAgreements [ i + 1 ]
matchingAraAnalyses = araVerbTemplate . matchingAnalyseIndexes ( araVerb )
if matchingAraAnalyses :
matchingVerbAnalyses =... |
def remove_outcome_hook ( self , outcome_id ) :
"""Removes internal transition going to the outcome""" | for transition_id in list ( self . transitions . keys ( ) ) :
transition = self . transitions [ transition_id ]
if transition . to_outcome == outcome_id and transition . to_state == self . state_id :
self . remove_transition ( transition_id ) |
def get_friendly_title ( err ) :
"""Turn class , instance , or name ( str ) into an eyeball - friendly title .
E . g . FastfoodStencilSetNotListed - - > ' Stencil Set Not Listed '""" | if isinstance ( err , basestring ) :
string = err
else :
try :
string = err . __name__
except AttributeError :
string = err . __class__ . __name__
split = _SPLITCASE_RE . findall ( string )
if not split :
split . append ( string )
if len ( split ) > 1 and split [ 0 ] == 'Fastfood' :
... |
def services ( self ) :
"""Fetch all instances of services for this EP .""" | ids = [ ref [ 'id' ] for ref in self [ 'services' ] ]
return [ Service . fetch ( id ) for id in ids ] |
def find_conflicts_within_selection_set ( context : ValidationContext , cached_fields_and_fragment_names : Dict , compared_fragment_pairs : "PairSet" , parent_type : Optional [ GraphQLNamedType ] , selection_set : SelectionSetNode , ) -> List [ Conflict ] :
"""Find conflicts within selection set .
Find all confli... | conflicts : List [ Conflict ] = [ ]
field_map , fragment_names = get_fields_and_fragment_names ( context , cached_fields_and_fragment_names , parent_type , selection_set )
# ( A ) Find all conflicts " within " the fields of this selection set .
# Note : this is the * only place * ` collect _ conflicts _ within ` is cal... |
def getkeys ( self , path , filename = None , directories = False , recursive = False ) :
"""Get matching keys for a path""" | from . utils import connection_with_anon , connection_with_gs
parse = BotoClient . parse_query ( path )
scheme = parse [ 0 ]
bucket_name = parse [ 1 ]
key = parse [ 2 ]
if scheme == 's3' or scheme == 's3n' :
conn = connection_with_anon ( self . credentials )
bucket = conn . get_bucket ( bucket_name )
elif schem... |
def parse_from_file ( file_object ) :
"""Parses existing OOXML file .
: Args :
- file _ object ( : class : ` ooxml . docx . DOCXFile ` ) : OOXML file object
: Returns :
Returns parsed document of type : class : ` ooxml . doc . Document `""" | logger . info ( 'Parsing %s file.' , file_object . file_name )
# Read the files
doc_content = file_object . read_file ( 'document.xml' )
# Parse the document
document = parse_document ( doc_content )
try :
style_content = file_object . read_file ( 'styles.xml' )
parse_style ( document , style_content )
except K... |
def list_devices ( names = None , continue_from = None , ** kwargs ) :
"""List devices in settings file and print versions""" | if not names :
names = [ device for device , _type in settings . GOLDEN_DEVICES if _type == 'OpenThread' ]
if continue_from :
continue_from = names . index ( continue_from )
else :
continue_from = 0
for port in names [ continue_from : ] :
try :
with OpenThreadController ( port ) as otc :
... |
def DOMStorage_removeDOMStorageItem ( self , storageId , key ) :
"""Function path : DOMStorage . removeDOMStorageItem
Domain : DOMStorage
Method name : removeDOMStorageItem
Parameters :
Required arguments :
' storageId ' ( type : StorageId ) - > No description
' key ' ( type : string ) - > No descriptio... | assert isinstance ( key , ( str , ) ) , "Argument 'key' must be of type '['str']'. Received type: '%s'" % type ( key )
subdom_funcs = self . synchronous_command ( 'DOMStorage.removeDOMStorageItem' , storageId = storageId , key = key )
return subdom_funcs |
def delete_namespaced_network_policy ( self , name , namespace , ** kwargs ) :
"""delete a NetworkPolicy
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ namespaced _ network _ policy ( name , namespac... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_namespaced_network_policy_with_http_info ( name , namespace , ** kwargs )
else :
( data ) = self . delete_namespaced_network_policy_with_http_info ( name , namespace , ** kwargs )
return data |
def read_all_from_datastore ( self ) :
"""Reads all work pieces from the datastore .""" | self . _work = { }
client = self . _datastore_client
parent_key = client . key ( KIND_WORK_TYPE , self . _work_type_entity_id )
for entity in client . query_fetch ( kind = KIND_WORK , ancestor = parent_key ) :
work_id = entity . key . flat_path [ - 1 ]
self . work [ work_id ] = dict ( entity ) |
def desbloquear_sat ( self ) :
"""Sobrepõe : meth : ` ~ satcfe . base . FuncoesSAT . desbloquear _ sat ` .
: return : Uma resposta SAT padrão .
: rtype : satcfe . resposta . padrao . RespostaSAT""" | retorno = super ( ClienteSATLocal , self ) . desbloquear_sat ( )
return RespostaSAT . desbloquear_sat ( retorno ) |
def _pre_request ( self , url , method = u"get" , data = None , headers = None , ** kwargs ) :
"""hook for manipulating the _ pre request data""" | header = { u"Content-Type" : u"application/json" , u"User-Agent" : u"salesking_api_py_v1" , }
if headers :
headers . update ( header )
else :
headers = header
if url . find ( self . base_url ) != 0 :
url = u"%s%s" % ( self . base_url , url )
return ( url , method , data , headers , kwargs ) |
def run_suite ( self , suite , ** kwargs ) :
"""This is the version from Django 1.7.""" | return self . test_runner ( verbosity = self . verbosity , failfast = self . failfast , no_colour = self . no_colour , ) . run ( suite ) |
def send_xml ( self , text , code = 200 ) :
'''Send some XML .''' | self . send_response ( code )
if text :
self . send_header ( 'Content-type' , 'text/xml; charset="%s"' % UNICODE_ENCODING )
self . send_header ( 'Content-Length' , str ( len ( text ) ) )
self . end_headers ( )
if text :
self . wfile . write ( text )
self . wfile . flush ( ) |
def _factor_lhs ( self , out_port ) :
"""With : :
n : = self . cdim
out _ inv : = invert _ permutation ( self . permutation ) [ out _ port ]
m _ { k - > l } : = map _ signals _ circuit ( { k : l } , n )
solve the equation ( I ) containing ` ` self ` ` : :
m _ { out _ port - > ( n - 1 ) } < < self
= = ( ... | n = self . cdim
assert ( 0 <= out_port < n )
out_inv = self . permutation . index ( out_port )
# ( I ) is equivalent to
# m _ { out _ port - > ( n - 1 ) } < < self < < m _ { ( n - 1)
# - > out _ inv } = = ( red _ self + cid ( 1 ) ) ( I ' )
red_self_plus_cid1 = ( map_channels ( { out_port : ( n - 1 ) } , n ) << self << ... |
def set_table ( genome , table , table_name , connection_string , metadata ) :
"""alter the table to work between different
dialects""" | table = Table ( table_name , genome . _metadata , autoload = True , autoload_with = genome . bind , extend_existing = True )
# print " \ t " . join ( [ c . name for c in table . columns ] )
# need to prefix the indexes with the table name to avoid collisions
for i , idx in enumerate ( table . indexes ) :
idx . name... |
def print_themes ( cls , path = THEMES ) :
"""Prints a human - readable summary of the installed themes to stdout .
This is intended to be used as a command - line utility , outside of the
main curses display loop .""" | themes , errors = cls . list_themes ( path = path + '/' )
print ( '\nInstalled ({0}):' . format ( path ) )
installed = [ t for t in themes if t . source == 'installed' ]
if installed :
for theme in installed :
line = ' {0:<20}[requires {1} colors]'
print ( line . format ( theme . name , theme . r... |
def normalize ( self , df = None , norm_type = 'zscore' , axis = 'row' , keep_orig = False ) :
'''Normalize the matrix rows or columns using Z - score ( zscore ) or Quantile Normalization ( qn ) . Users can optionally pass in a DataFrame to be normalized ( and this will be incorporated into the Network object ) .''... | normalize_fun . run_norm ( self , df , norm_type , axis , keep_orig ) |
def display_image ( self , reset = 1 ) :
"""Utility routine used to display an updated frame from a framebuffer .""" | try :
fb = self . server . controller . get_frame ( self . frame )
except KeyError : # the selected frame does not exist , create it
fb = self . server . controller . init_frame ( self . frame )
if not fb . height :
width = fb . width
height = int ( len ( fb . buffer ) / width )
fb . height = height... |
def dragEnterEvent ( self , event ) :
"""Override Qt method""" | mimeData = event . mimeData ( )
formats = list ( mimeData . formats ( ) )
if "parent-id" in formats and int ( mimeData . data ( "parent-id" ) ) == id ( self . ancestor ) :
event . acceptProposedAction ( )
QTabBar . dragEnterEvent ( self , event ) |
def close_hover ( self , element , use_js = False ) :
"""Close hover by moving to a set offset " away " from the element being hovered .
: param element : element that triggered the hover to open
: param use _ js : use javascript to close hover
: return : None""" | try :
if use_js :
self . _js_hover ( 'mouseout' , element )
else :
actions = ActionChains ( self . driver )
actions . move_to_element_with_offset ( element , - 100 , - 100 )
actions . reset_actions ( )
except ( StaleElementReferenceException , MoveTargetOutOfBoundsException ) :
... |
def add_defined_filter ( self , * value ) :
"""Add a DefinedFilter expression to the query . This filter will be
considered true if the : class : ` smc . monitoring . values . Value ` instance
has a value .
. . seealso : : : class : ` smc _ monitoring . models . filters . DefinedFilter ` for examples .
: pa... | filt = DefinedFilter ( * value )
self . update_filter ( filt )
return filt |
def mode_new_collection ( ) :
"""Create a new collection of items with common attributes .""" | print globals ( ) [ 'mode_new_collection' ] . __doc__
collection_name = raw_input ( "Collection name: " )
item_attr_list = [ ]
collection_node_id = None
if collection_name :
collection_node_id = insert_node ( name = collection_name , value = None )
insert_query ( name = 'select_link_node_from_node.sql' , node_i... |
def get_raw_blast ( pdb_id , output_form = 'HTML' , chain_id = 'A' ) :
'''Look up full BLAST page for a given PDB ID
get _ blast ( ) uses this function internally
Parameters
pdb _ id : string
A 4 character string giving a pdb entry of interest
chain _ id : string
A single character designating the chain... | url_root = 'http://www.rcsb.org/pdb/rest/getBlastPDB2?structureId='
url = url_root + pdb_id + '&chainId=' + chain_id + '&outputFormat=' + output_form
req = urllib . request . Request ( url )
f = urllib . request . urlopen ( req )
result = f . read ( )
result = result . decode ( 'unicode_escape' )
assert result
return r... |
def _update ( self , rules : list ) :
"""Updates the given rules and stores
them on the router .""" | self . _rules = rules
to_store = '\n' . join ( rule . config_string for rule in rules )
sftp_connection = self . _sftp_connection
with sftp_connection . open ( self . RULE_PATH , mode = 'w' ) as file_handle :
file_handle . write ( to_store ) |
def greenhall_table1 ( alpha , d ) :
"""Table 1 from Greenhall 2004""" | row_idx = int ( - alpha + 2 )
# map 2 - > row0 and - 4 - > row6
col_idx = int ( d - 1 )
table1 = [ [ ( 2.0 / 3.0 , 1.0 / 3.0 ) , ( 7.0 / 9.0 , 1.0 / 2.0 ) , ( 22.0 / 25.0 , 2.0 / 3.0 ) ] , # alpha = + 2
[ ( 0.840 , 0.345 ) , ( 0.997 , 0.616 ) , ( 1.141 , 0.843 ) ] , [ ( 1.079 , 0.368 ) , ( 1.033 , 0.607 ) , ( 1.184 , 0... |
def project_closed ( self , project ) :
"""Called when a project is closed .
: param project : Project instance""" | for node in project . nodes :
if node . id in self . _nodes :
del self . _nodes [ node . id ] |
def _to_java_impl ( self ) :
"""Return Java estimator , estimatorParamMaps , and evaluator from this Python instance .""" | gateway = SparkContext . _gateway
cls = SparkContext . _jvm . org . apache . spark . ml . param . ParamMap
java_epms = gateway . new_array ( cls , len ( self . getEstimatorParamMaps ( ) ) )
for idx , epm in enumerate ( self . getEstimatorParamMaps ( ) ) :
java_epms [ idx ] = self . getEstimator ( ) . _transfer_para... |
def load_clients ( stream , configuration_class = ClientConfiguration ) :
"""Loads client configurations from a YAML document stream .
: param stream : YAML stream .
: type stream : file
: param configuration _ class : Class of the configuration object to create .
: type configuration _ class : class
: re... | client_dict = yaml . safe_load ( stream )
if isinstance ( client_dict , dict ) :
return { client_name : configuration_class ( ** client_config ) for client_name , client_config in six . iteritems ( client_dict ) }
raise ValueError ( "Valid configuration could not be decoded." ) |
def wait_for_completion ( self ) :
"""@ brief Wait until the breakpoint is hit .""" | while self . target . get_state ( ) == Target . TARGET_RUNNING :
pass
if self . flash_algo_debug :
regs = self . target . read_core_registers_raw ( list ( range ( 19 ) ) + [ 20 ] )
LOG . debug ( "Registers after flash algo: [%s]" , " " . join ( "%08x" % r for r in regs ) )
expected_fp = self . flash_alg... |
def scene_command ( self , command ) :
"""Wrapper to send posted scene command and get response""" | self . logger . info ( "scene_command: Group %s Command %s" , self . group_id , command )
command_url = self . hub . hub_url + '/0?' + command + self . group_id + "=I=0"
return self . hub . post_direct_command ( command_url ) |
def b58decode ( v ) :
'''Decode a Base58 encoded string''' | if not isinstance ( v , str ) :
v = v . decode ( 'ascii' )
origlen = len ( v )
v = v . lstrip ( alphabet [ 0 ] )
newlen = len ( v )
acc = b58decode_int ( v )
result = [ ]
while acc > 0 :
acc , mod = divmod ( acc , 256 )
result . append ( mod )
return ( b'\0' * ( origlen - newlen ) + bseq ( reversed ( result... |
def extract_xyz_matrix_from_pdb_chain ( pdb_lines , chain_id , atoms_of_interest = backbone_atoms , expected_num_residues = None , expected_num_residue_atoms = None , fail_on_model_records = True , include_all_columns = False ) :
'''Returns a pandas dataframe of X , Y , Z coordinates for the PDB chain .
Note : Th... | if fail_on_model_records and [ l for l in pdb_lines if l . startswith ( 'MODEL' ) ] :
raise Exception ( 'This function does not handle files with MODEL records. Please split those file by model first.' )
new_pdb_lines = [ ]
found_chain = False
for l in pdb_lines :
if l . startswith ( 'ATOM ' ) :
if l [... |
def parse ( self , ioc_obj ) :
"""parses an ioc to populate self . iocs and self . ioc _ name
: param ioc _ obj :
: return :""" | if ioc_obj is None :
return
iocid = ioc_obj . iocid
try :
sd = ioc_obj . metadata . xpath ( './/short_description/text()' ) [ 0 ]
except IndexError :
sd = 'NoName'
if iocid in self . iocs :
msg = 'duplicate IOC UUID [{}] [orig_shortName: {}][new_shortName: {}]' . format ( iocid , self . ioc_name [ iocid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.