signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def _CheckFieldMaskMessage ( message ) :
"""Raises ValueError if message is not a FieldMask .""" | message_descriptor = message . DESCRIPTOR
if ( message_descriptor . name != 'FieldMask' or message_descriptor . file . name != 'google/protobuf/field_mask.proto' ) :
raise ValueError ( 'Message {0} is not a FieldMask.' . format ( message_descriptor . full_name ) ) |
def add_choice ( self , choice , inline_region , identifier = None , name = '' ) :
"""stub""" | if inline_region not in self . my_osid_object_form . _my_map [ 'choices' ] :
raise IllegalState ( 'that inline region does not exist. Please call add_inline_region first' )
if identifier is None :
identifier = str ( ObjectId ( ) )
current_identifiers = [ c [ 'id' ] for c in self . my_osid_object_form . _my_map ... |
def composite_decorator ( func ) :
"""Decorator for wrapping functions that calculate a weighted sum""" | @ wraps ( func )
def wrapper ( self , * args , ** kwargs ) :
total = [ ]
for weight , iso in zip ( self . weights , self . isochrones ) :
subfunc = getattr ( iso , func . __name__ )
total . append ( weight * subfunc ( * args , ** kwargs ) )
return np . sum ( total , axis = 0 )
return wrapper |
def add_params ( param_list_left , param_list_right ) :
"""Add two lists of parameters one by one
: param param _ list _ left : list of numpy arrays
: param param _ list _ right : list of numpy arrays
: return : list of numpy arrays""" | res = [ ]
for x , y in zip ( param_list_left , param_list_right ) :
res . append ( x + y )
return res |
def delete_processing_block ( processing_block_id ) :
"""Delete Processing Block with the specified ID""" | scheduling_block_id = processing_block_id . split ( ':' ) [ 0 ]
config = get_scheduling_block ( scheduling_block_id )
processing_blocks = config . get ( 'processing_blocks' )
processing_block = list ( filter ( lambda x : x . get ( 'id' ) == processing_block_id , processing_blocks ) ) [ 0 ]
config [ 'processing_blocks' ... |
def SetServerInformation ( self , server , port ) :
"""Set the server information .
Args :
server ( str ) : IP address or hostname of the server .
port ( int ) : Port number of the server .""" | self . _host = server
self . _port = port
logger . debug ( 'Elasticsearch server: {0!s} port: {1:d}' . format ( server , port ) ) |
def status ( resources , * args , ** kwargs ) :
"""Print status report for zero or more resources .""" | template = '{:<50}{:>10}'
client = redis . Redis ( decode_responses = True , ** kwargs )
# resource details
for loop , resource in enumerate ( resources ) : # blank between resources
if loop :
print ( )
# strings needed
keys = Keys ( resource )
wildcard = keys . key ( '*' )
# header
temp... |
def save ( self ) :
"""Creates a new user and account . Returns the newly created user .""" | username , email , password = ( self . cleaned_data [ 'username' ] , self . cleaned_data [ 'email' ] , self . cleaned_data [ 'password1' ] )
user = get_user_model ( ) . objects . create_user ( username , email , password , not defaults . ACCOUNTS_ACTIVATION_REQUIRED , defaults . ACCOUNTS_ACTIVATION_REQUIRED )
return us... |
def order_upgrades ( self , upgrades , history = None ) :
"""Order upgrades according to their dependencies .
( topological sort using
Kahn ' s algorithm - http : / / en . wikipedia . org / wiki / Topological _ sorting ) .
: param upgrades : Dict of upgrades
: param history : Dict of applied upgrades""" | history = history or { }
graph_incoming , graph_outgoing = self . _create_graph ( upgrades , history )
# Removed already applied upgrades ( assumes all dependencies prior to
# this upgrade has been applied ) .
for node_id in six . iterkeys ( history ) :
start_nodes = [ node_id , ]
while start_nodes :
no... |
def oplot ( self , x , y , ** kw ) :
"""generic plotting method , overplotting any existing plot""" | self . panel . oplot ( x , y , ** kw ) |
def compose ( layers , bbox = None , layer_filter = None , color = None , ** kwargs ) :
"""Compose layers to a single : py : class : ` PIL . Image ` .
If the layers do not have visible pixels , the function returns ` None ` .
Example : :
image = compose ( [ layer1 , layer2 ] )
In order to skip some layers ,... | from PIL import Image
if not hasattr ( layers , '__iter__' ) :
layers = [ layers ]
def _default_filter ( layer ) :
return layer . is_visible ( )
layer_filter = layer_filter or _default_filter
valid_layers = [ x for x in layers if layer_filter ( x ) ]
if len ( valid_layers ) == 0 :
return None
if bbox is Non... |
def _validate_virtualbox ( self ) :
'''a method to validate that virtualbox is running on Win 7/8 machines
: return : boolean indicating whether virtualbox is running''' | # validate operating system
if self . localhost . os . sysname != 'Windows' :
return False
win_release = float ( self . localhost . os . release )
if win_release >= 10.0 :
return False
# validate docker - machine installation
from os import devnull
from subprocess import call , check_output , STDOUT
sys_command... |
def _get_format_from_filename ( file , mode ) :
"""Return a format string obtained from file ( or file . name ) .
If file already exists ( = read mode ) , an empty string is returned on
error . If not , an exception is raised .
The return type will always be str or unicode ( even if
file / file . name is a ... | format = ''
file = getattr ( file , 'name' , file )
try : # This raises an exception if file is not a ( Unicode / byte ) string :
format = _os . path . splitext ( file ) [ - 1 ] [ 1 : ]
# Convert bytes to unicode ( raises AttributeError on Python 3 str ) :
format = format . decode ( 'utf-8' , 'replace' )
ex... |
def json_dict_copy ( json_object , property_list , defaultValue = None ) :
"""property _ list = [
{ " name " : " name " , " alternateName " : [ " name " , " title " ] } ,
{ " name " : " birthDate " , " alternateName " : [ " dob " , " dateOfBirth " ] } ,
{ " name " : " description " }""" | ret = { }
for prop in property_list :
p_name = prop [ "name" ]
for alias in prop . get ( "alternateName" , [ ] ) :
if json_object . get ( alias ) is not None :
ret [ p_name ] = json_object . get ( alias )
break
if not p_name in ret :
if p_name in json_object :
... |
def on_cursor_shape_changed ( self , combo ) :
"""Changes the value of cursor _ shape in dconf""" | index = combo . get_active ( )
self . settings . style . set_int ( 'cursor-shape' , index ) |
def load_arguments ( self , argv , base = None ) :
'''Process given argument list based on registered arguments and given
optional base : class : ` argparse . ArgumentParser ` instance .
This method saves processed arguments on itself , and this state won ' t
be lost after : meth : ` clean ` calls .
Process... | plugin_parser = argparse . ArgumentParser ( add_help = False )
plugin_parser . add_argument ( '--plugin' , action = 'append' , default = [ ] )
parent = base or plugin_parser
parser = argparse . ArgumentParser ( parents = ( parent , ) , add_help = False , ** getattr ( parent , 'defaults' , { } ) )
plugins = [ plugin for... |
def parse_parameters ( cls , parameters , possible_fields = None ) :
"""Parses a list of parameters to get the list of fields needed in
order to evaluate those parameters .
Parameters
parameters : ( list of ) strings
The list of desired parameters . These can be ( functions of ) fields
or virtual fields .... | if possible_fields is not None : # make sure field names are strings and not unicode
possible_fields = dict ( [ [ f , dt ] for f , dt in possible_fields . items ( ) ] )
class ModifiedArray ( cls ) :
_staticfields = possible_fields
cls = ModifiedArray
return cls ( 1 , names = parameters ) . fieldname... |
def delete_ip_scope ( network_address , auth , url ) :
'''Function to delete an entire IP segment from the IMC IP Address management under terminal access
: param network _ address
: param auth
: param url
> > > from pyhpeimc . auth import *
> > > from pyhpeimc . plat . termaccess import *
> > > auth = ... | scope_id = get_scope_id ( network_address , auth , url )
delete_ip_address_url = '''/imcrs/res/access/assignedIpScope/''' + str ( scope_id )
f_url = url + delete_ip_address_url
r = requests . delete ( f_url , auth = auth , headers = HEADERS )
try :
return r
if r . status_code == 204 : # print ( " IP Segment Suc... |
def qtrim_back ( self , name , size = 1 ) :
"""Sets the list element at ` ` index ` ` to ` ` value ` ` . An error is returned for out of
range indexes .
: param string name : the queue name
: param int size : the max length of removed elements
: return : the length of removed elements
: rtype : int""" | size = get_positive_integer ( "size" , size )
return self . execute_command ( 'qtrim_back' , name , size ) |
def _SkipFieldContents ( tokenizer ) :
"""Skips over contents ( value or message ) of a field .
Args :
tokenizer : A tokenizer to parse the field name and values .""" | # Try to guess the type of this field .
# If this field is not a message , there should be a " : " between the
# field name and the field value and also the field value should not
# start with " { " or " < " which indicates the beginning of a message body .
# If there is no " : " or there is a " { " or " < " after " : ... |
def smiles_to_compound ( smiles , assign_descriptors = True ) :
"""Convert SMILES text to compound object
Raises :
ValueError : SMILES with unsupported format""" | it = iter ( smiles )
mol = molecule ( )
try :
for token in it :
mol ( token )
result , _ = mol ( None )
except KeyError as err :
raise ValueError ( "Unsupported Symbol: {}" . format ( err ) )
result . graph . remove_node ( 0 )
logger . debug ( result )
if assign_descriptors :
molutil . assign_de... |
def name_strip ( self , name , is_policy = False , prefix = True ) :
"""Transforms name to AWS valid characters and adds prefix and type
: param name : Name of the role / policy
: param is _ policy : True if policy should be added as suffix
: param prefix : True if prefix should be added
: return : Transfor... | str = self . name_build ( name , is_policy , prefix )
str = str . title ( )
str = str . replace ( '-' , '' )
return str |
def psnr ( prediction , ground_truth , maxp = None , name = 'psnr' ) :
"""` Peek Signal to Noise Ratio < https : / / en . wikipedia . org / wiki / Peak _ signal - to - noise _ ratio > ` _ .
. . math : :
PSNR = 20 \ cdot \ log _ { 10 } ( MAX _ p ) - 10 \ cdot \ log _ { 10 } ( MSE )
Args :
prediction : a : cl... | maxp = float ( maxp )
def log10 ( x ) :
with tf . name_scope ( "log10" ) :
numerator = tf . log ( x )
denominator = tf . log ( tf . constant ( 10 , dtype = numerator . dtype ) )
return numerator / denominator
mse = tf . reduce_mean ( tf . square ( prediction - ground_truth ) )
if maxp is Non... |
def clear_cache ( modeladmin , request , queryset = None ) :
"""Clears media cache files such as thumbnails .""" | execute = request . POST . get ( 'execute' )
files_in_storage = [ ]
storage = get_media_storage ( )
cache_files_choices = [ ]
for storage_name in get_cache_files ( ) :
link = mark_safe ( '<a href="%s">%s</a>' % ( storage . url ( storage_name ) , storage_name ) )
cache_files_choices . append ( ( storage_name , l... |
def lag_calc ( self , stream , pre_processed , shift_len = 0.2 , min_cc = 0.4 , horizontal_chans = [ 'E' , 'N' , '1' , '2' ] , vertical_chans = [ 'Z' ] , cores = 1 , interpolate = False , plot = False , parallel = True , process_cores = None , debug = 0 ) :
"""Compute picks based on cross - correlation alignment . ... | return Party ( families = [ self ] ) . lag_calc ( stream = stream , pre_processed = pre_processed , shift_len = shift_len , min_cc = min_cc , horizontal_chans = horizontal_chans , vertical_chans = vertical_chans , cores = cores , interpolate = interpolate , plot = plot , parallel = parallel , process_cores = process_co... |
def _delete_port_profile_from_ucsm ( self , handle , port_profile , ucsm_ip ) :
"""Deletes Port Profile from UCS Manager .""" | port_profile_dest = ( const . PORT_PROFILESETDN + const . VNIC_PATH_PREFIX + port_profile )
handle . StartTransaction ( )
# Find port profile on the UCS Manager
p_profile = handle . GetManagedObject ( None , self . ucsmsdk . VnicProfile . ClassId ( ) , { self . ucsmsdk . VnicProfile . NAME : port_profile , self . ucsms... |
def string_to_element ( element_as_string , include_namespaces = False ) :
""": return : an element parsed from a string value , or the element as is if already parsed""" | if element_as_string is None :
return None
elif isinstance ( element_as_string , ElementTree ) :
return element_as_string . getroot ( )
elif isinstance ( element_as_string , ElementType ) :
return element_as_string
else :
element_as_string = _xml_content_to_string ( element_as_string )
if not isinstance... |
def _get_model ( vehicle ) :
"""Clean the model field . Best guess .""" | model = vehicle [ 'model' ]
model = model . replace ( vehicle [ 'year' ] , '' )
model = model . replace ( vehicle [ 'make' ] , '' )
return model . strip ( ) . split ( ' ' ) [ 0 ] |
def update ( self , friendly_name = values . unset , default_service_role_sid = values . unset , default_channel_role_sid = values . unset , default_channel_creator_role_sid = values . unset , read_status_enabled = values . unset , reachability_enabled = values . unset , typing_indicator_timeout = values . unset , cons... | data = values . of ( { 'FriendlyName' : friendly_name , 'DefaultServiceRoleSid' : default_service_role_sid , 'DefaultChannelRoleSid' : default_channel_role_sid , 'DefaultChannelCreatorRoleSid' : default_channel_creator_role_sid , 'ReadStatusEnabled' : read_status_enabled , 'ReachabilityEnabled' : reachability_enabled ,... |
def p_var_decl_at ( p ) :
"""var _ decl : DIM idlist typedef AT expr""" | p [ 0 ] = None
if len ( p [ 2 ] ) != 1 :
syntax_error ( p . lineno ( 1 ) , 'Only one variable at a time can be declared this way' )
return
idlist = p [ 2 ] [ 0 ]
entry = SYMBOL_TABLE . declare_variable ( idlist [ 0 ] , idlist [ 1 ] , p [ 3 ] )
if entry is None :
return
if p [ 5 ] . token == 'CONST' :
tm... |
def replace_built ( self , built_packages ) :
"""Return a copy of this resolvable set but with built packages .
: param dict built _ packages : A mapping from a resolved package to its locally built package .
: returns : A new resolvable set with built package replacements made .""" | def map_packages ( resolved_packages ) :
packages = OrderedSet ( built_packages . get ( p , p ) for p in resolved_packages . packages )
return _ResolvedPackages ( resolved_packages . resolvable , packages , resolved_packages . parent , resolved_packages . constraint_only )
return _ResolvableSet ( [ map_packages... |
def makePhe ( segID , N , CA , C , O , geo ) :
'''Creates a Phenylalanine residue''' | # # R - Group
CA_CB_length = geo . CA_CB_length
C_CA_CB_angle = geo . C_CA_CB_angle
N_C_CA_CB_diangle = geo . N_C_CA_CB_diangle
CB_CG_length = geo . CB_CG_length
CA_CB_CG_angle = geo . CA_CB_CG_angle
N_CA_CB_CG_diangle = geo . N_CA_CB_CG_diangle
CG_CD1_length = geo . CG_CD1_length
CB_CG_CD1_angle = geo . CB_CG_CD1_angl... |
def _update_console ( self , value = None ) :
"""Update the progress bar to the given value ( out of the total
given to the constructor ) .""" | if self . _total == 0 :
frac = 1.0
else :
frac = float ( value ) / float ( self . _total )
file = self . _file
write = file . write
if frac > 1 :
bar_fill = int ( self . _bar_length )
else :
bar_fill = int ( float ( self . _bar_length ) * frac )
write ( '\r|' )
color_print ( '=' * bar_fill , 'blue' , fi... |
def __gen_hierarchy_file ( self , layer ) :
"""Hierarchical structures ( < structList > elements ) are used to create
hierarchically nested annotation graphs ( e . g . to express consists - of
relationships or dominance - edges in syntax trees , RST ) .
A < struct > element will be created for each hierarchic... | paula_id = '{0}.{1}.{2}_{3}' . format ( layer , self . corpus_name , self . name , layer )
self . paulamap [ 'hierarchy' ] [ layer ] = paula_id
E , tree = gen_paula_etree ( paula_id )
dominance_edges = select_edges_by ( self . dg , layer = layer , edge_type = EdgeTypes . dominance_relation , data = True )
span_edges = ... |
def setUpMethods ( self , port ) :
'''set up all methods representing the port operations .
Parameters :
port - - Port that defines the operations .''' | assert isinstance ( port , WSDLTools . Port ) , 'expecting WSDLTools.Port not: ' % type ( port )
sd = self . _services . get ( port . getService ( ) . name )
assert sd is not None , 'failed to initialize.'
binding = port . getBinding ( )
portType = port . getPortType ( )
action_in = ''
for bop in binding . operations :... |
def resolve ( hostname , family = AF_UNSPEC ) :
"""Resolve hostname to one or more IP addresses through the operating system .
Resolution is carried out for the given address family . If no
address family is specified , only IPv4 and IPv6 addresses are returned . If
multiple IP addresses are found , all are r... | af_ok = ( AF_INET , AF_INET6 )
if family != AF_UNSPEC and family not in af_ok :
raise ValueError ( "Invalid family '%s'" % family )
ips = ( )
try :
addrinfo = socket . getaddrinfo ( hostname , None , family )
except socket . gaierror as exc : # EAI _ NODATA and EAI _ NONAME are expected if this name is not ( ye... |
def astuple ( self ) :
"""Create a tuple ` ` { fieldvalue1 , . . . } ` ` of the Message object .
: return : A tuple representation of the message .
: rtype : Tuple [ Any ]""" | return tuple ( getattr ( self , f . name ) for f in fields ( self ) ) |
def structure_from_string ( data ) :
"""Parses a rndstr . in or lat . in file into pymatgen ' s
Structure format .
: param data : contents of a rndstr . in or lat . in file
: return : Structure object""" | data = data . splitlines ( )
data = [ x . split ( ) for x in data if x ]
# remove empty lines
# following specification / terminology given in manual
if len ( data [ 0 ] ) == 6 : # lattice parameters
a , b , c , alpha , beta , gamma = map ( float , data [ 0 ] )
coord_system = Lattice . from_parameters ( a , b ,... |
def import_table ( self , source , table_name ) :
"""Copy a table from another SQLite database to this one .""" | query = "SELECT * FROM `%s`" % table_name . lower ( )
df = pandas . read_sql ( query , source . connection )
df . to_sql ( table_name , con = self . own_connection ) |
def timeline ( self , uri ) :
'''Get the domain tagging timeline for a given uri .
Could be a domain , ip , or url .
For details , see https : / / docs . umbrella . com / investigate - api / docs / timeline''' | uri = self . _uris [ "timeline" ] . format ( uri )
resp_json = self . get_parse ( uri )
return resp_json |
def p_simple_indirect_reference ( p ) :
'''simple _ indirect _ reference : DOLLAR simple _ indirect _ reference
| reference _ variable''' | if len ( p ) == 3 :
p [ 0 ] = ast . Variable ( p [ 2 ] , lineno = p . lineno ( 1 ) )
else :
p [ 0 ] = p [ 1 ] |
def get_all_spot_instance_requests ( self , request_ids = None , filters = None ) :
"""Retrieve all the spot instances requests associated with your account .
: type request _ ids : list
: param request _ ids : A list of strings of spot instance request IDs
: type filters : dict
: param filters : Optional f... | params = { }
if request_ids :
self . build_list_params ( params , request_ids , 'SpotInstanceRequestId' )
if filters :
if 'launch.group-id' in filters :
lgid = filters . get ( 'launch.group-id' )
if not lgid . startswith ( 'sg-' ) or len ( lgid ) != 11 :
warnings . warn ( "The 'launc... |
def get_file_sample ( self , numLines = 10 ) :
"""retrieve a sample of the file""" | res = ''
try :
with open ( self . fullname , 'r' ) as f :
for line_num , line in enumerate ( f ) :
res += str ( line_num ) . zfill ( 5 ) + ' ' + line
if line_num >= numLines - 1 :
break
return res
except Exception as ex :
print ( 'cant get_file_sample in "' , ... |
def get_resources ( self , collections ) :
"""Get resources that correspond to values from : collections : .
: param collections : Collection names for which resources should be
gathered
: type collections : list of str
: return : Gathered resources
: rtype : list of Resource instances""" | res_map = self . request . registry . _model_collections
resources = [ res for res in res_map . values ( ) if res . collection_name in collections ]
resources = [ res for res in resources if res ]
return set ( resources ) |
def new_digraph ( self , name , data = None , ** attr ) :
"""Return a new instance of type DiGraph , initialized with the given
data if provided .
: arg name : a name for the graph
: arg data : dictionary or NetworkX graph object providing initial state""" | self . _init_graph ( name , 'DiGraph' )
dg = DiGraph ( self , name , data , ** attr )
self . _graph_objs [ name ] = dg
return dg |
def to_index ( self , ordered_dims = None ) :
"""Convert all index coordinates into a : py : class : ` pandas . Index ` .
Parameters
ordered _ dims : sequence , optional
Possibly reordered version of this object ' s dimensions indicating
the order in which dimensions should appear on the result .
Returns ... | if ordered_dims is None :
ordered_dims = self . dims
elif set ( ordered_dims ) != set ( self . dims ) :
raise ValueError ( 'ordered_dims must match dims, but does not: ' '{} vs {}' . format ( ordered_dims , self . dims ) )
if len ( ordered_dims ) == 0 :
raise ValueError ( 'no valid index for a 0-dimensional... |
def sg_query_streamer ( self , index ) :
"""Query the current status of a streamer .""" | resp = self . sensor_graph . query_streamer ( index )
if resp is None :
return [ struct . pack ( "<L" , _pack_sgerror ( SensorGraphError . STREAMER_NOT_ALLOCATED ) ) ]
return [ struct . pack ( "<LLLLBBBx" , * resp ) ] |
def getStats ( self ) :
"""Returns the GA4GH protocol representation of this read group ' s
ReadStats .""" | stats = protocol . ReadStats ( )
stats . aligned_read_count = self . getNumAlignedReads ( )
stats . unaligned_read_count = self . getNumUnalignedReads ( )
# TODO base _ count requires iterating through all reads
return stats |
async def kickChatMember ( self , chat_id , user_id , until_date = None ) :
"""See : https : / / core . telegram . org / bots / api # kickchatmember""" | p = _strip ( locals ( ) )
return await self . _api_request ( 'kickChatMember' , _rectify ( p ) ) |
def find_best_matching_node ( self , new , old_nodes ) :
"""Find the node that best matches the new node given the old nodes . If no
good match exists return ` None ` .""" | name = new . __class__ . __name__
# : TODO : We should pick the BEST one from this list
# : based on some " matching " criteria ( such as matching ref name or params )
matches = [ c for c in old_nodes if name == c . __class__ . __name__ ]
if self . debug :
print ( "Found matches for {}: {} " . format ( new , matche... |
def pygmentify ( value , ** kwargs ) :
"""Return a highlighted code block with Pygments .""" | soup = BeautifulSoup ( value , 'html.parser' )
for pre in soup . find_all ( 'pre' ) : # Get code
code = '' . join ( [ to_string ( item ) for item in pre . contents ] )
code = code . replace ( '<' , '<' )
code = code . replace ( '>' , '>' )
code = code . replace ( ''' , "'" )
code = code . ... |
def check_spelling ( spelling_lang , txt ) :
"""Check the spelling in the text , and compute a score . The score is the
number of words correctly ( or almost correctly ) spelled , minus the number
of mispelled words . Words " almost " correct remains neutral ( - > are not
included in the score )
Returns :
... | if os . name == "nt" :
assert ( not "check_spelling() not available on Windows" )
return
with _ENCHANT_LOCK : # Maximum distance from the first suggestion from python - enchant
words_dict = enchant . request_dict ( spelling_lang )
try :
tknzr = enchant . tokenize . get_tokenizer ( spelling_lang ... |
def direct2dDistance ( self , point ) :
"""consider the distance between two mapPoints , ignoring all terrain , pathing issues""" | if not isinstance ( point , MapPoint ) :
return 0.0
return ( ( self . x - point . x ) ** 2 + ( self . y - point . y ) ** 2 ) ** ( 0.5 )
# simple distance formula |
def stop_script ( self , script_id ) :
"""Stops a running script .
script _ id : = id of stored script .
status = pi . stop _ script ( sid )""" | res = yield from self . _pigpio_aio_command ( _PI_CMD_PROCS , script_id , 0 )
return _u2i ( res ) |
def register ( cls , instance_class , name = None ) :
"""Register a class with the factory .
: param instance _ class : the class to register with the factory ( not a
string )
: param name : the name to use as the key for instance class lookups ;
defaults to the name of the class""" | if name is None :
name = instance_class . __name__
cls . INSTANCE_CLASSES [ name ] = instance_class |
def delete_role_config_group ( self , name ) :
"""Delete a role config group by name .
@ param name : Role config group name .
@ return : The deleted ApiRoleConfigGroup object .
@ since : API v3""" | return role_config_groups . delete_role_config_group ( self . _get_resource_root ( ) , self . name , name , self . _get_cluster_name ( ) ) |
def render_field_errors ( field ) :
"""Render field errors as html .""" | if field . errors :
html = """<p class="help-block">Error: {errors}</p>""" . format ( errors = '. ' . join ( field . errors ) )
return HTMLString ( html )
return None |
def build ( self ) :
"""Builds the ` HelicalHelix ` .""" | helical_helix = Polypeptide ( )
primitive_coords = self . curve_primitive . coordinates
helices = [ Helix . from_start_and_end ( start = primitive_coords [ i ] , end = primitive_coords [ i + 1 ] , helix_type = self . minor_helix_type , aa = 1 ) for i in range ( len ( primitive_coords ) - 1 ) ]
residues_per_turn = self ... |
def singlediode ( self ) :
"""Deprecated""" | ( photocurrent , saturation_current , resistance_series , resistance_shunt , nNsVth ) = ( self . system . calcparams_desoto ( self . effective_irradiance , self . temps [ 'temp_cell' ] ) )
self . desoto = ( photocurrent , saturation_current , resistance_series , resistance_shunt , nNsVth )
self . dc = self . system . s... |
def get_all_for_project ( self , name , ** kwargs ) :
"""Gets the Build Records produced from the BuildConfiguration by name .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please define a ` callback ` function
to be invoked when receiving the response .
> ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'callback' ) :
return self . get_all_for_project_with_http_info ( name , ** kwargs )
else :
( data ) = self . get_all_for_project_with_http_info ( name , ** kwargs )
return data |
def os_packages ( metadata ) :
"""Installs operating system dependent packages""" | family = metadata [ 0 ]
release = metadata [ 1 ]
if 'Amazon' in family and '2' not in release :
stdout_message ( 'Identified Amazon Linux 1 os distro' )
commands = [ 'sudo yum -y update' , 'sudo yum -y groupinstall "Development tools"' ]
for cmd in commands :
stdout_message ( subprocess . getoutput ... |
def solve_select ( expr , vars ) :
"""Use IAssociative . select to get key ( rhs ) from the data ( lhs ) .
This operation supports both scalars and repeated values on the LHS -
selecting from a repeated value implies a map - like operation and returns a
new repeated value .""" | data , _ = __solve_for_repeated ( expr . lhs , vars )
key = solve ( expr . rhs , vars ) . value
try :
results = [ associative . select ( d , key ) for d in repeated . getvalues ( data ) ]
except ( KeyError , AttributeError ) : # Raise a better exception for accessing a non - existent key .
raise errors . Efilte... |
def check_finished ( self , max_plugins_output_length ) : # pylint : disable = too - many - branches
"""Handle action if it is finished ( get stdout , stderr , exit code . . . )
: param max _ plugins _ output _ length : max plugin data length
: type max _ plugins _ output _ length : int
: return : None""" | self . last_poll = time . time ( )
_ , _ , child_utime , child_stime , _ = os . times ( )
# Not yet finished . . .
if self . process . poll ( ) is None : # We must wait , but checks are variable in time so we do not wait the same
# for a little check or a long ping . So we do like TCP : slow start with a very
# shot ti... |
def _parse_category ( fname , categories ) :
"""Parse unicode category tables .""" | version , date , values = None , None , [ ]
print ( "parsing {} .." . format ( fname ) )
for line in open ( fname , 'rb' ) :
uline = line . decode ( 'utf-8' )
if version is None :
version = uline . split ( None , 1 ) [ 1 ] . rstrip ( )
continue
elif date is None :
date = uline . spli... |
def getTreeWalker ( treeType , implementation = None , ** kwargs ) :
"""Get a TreeWalker class for various types of tree with built - in support
: arg str treeType : the name of the tree type required ( case - insensitive ) .
Supported values are :
* " dom " : The xml . dom . minidom DOM implementation
* " ... | treeType = treeType . lower ( )
if treeType not in treeWalkerCache :
if treeType == "dom" :
from . import dom
treeWalkerCache [ treeType ] = dom . TreeWalker
elif treeType == "genshi" :
from . import genshi
treeWalkerCache [ treeType ] = genshi . TreeWalker
elif treeType == "... |
def draw ( self , painter , options , widget ) :
"""Handle the draw event for the widget .""" | self . declaration . draw ( painter , options , widget ) |
def loadFromURL ( self , url , schema = None ) :
"""Return an XMLSchema instance loaded from the given url .
url - - URL to dereference
schema - - Optional XMLSchema instance .""" | reader = self . __readerClass ( )
if self . __base_url :
url = basejoin ( self . __base_url , url )
reader . loadFromURL ( url )
schema = schema or XMLSchema ( )
schema . setBaseUrl ( url )
schema . load ( reader )
self . __setIncludes ( schema )
self . __setImports ( schema )
return schema |
def project_versions ( self , project ) :
"""Get a list of version Resources present on a project .
: param project : ID or key of the project to get versions from
: type project : str
: rtype : List [ Version ]""" | r_json = self . _get_json ( 'project/' + project + '/versions' )
versions = [ Version ( self . _options , self . _session , raw_ver_json ) for raw_ver_json in r_json ]
return versions |
def run ( self ) :
"""Run the job and immediately reschedule it .
: return : The return value returned by the ` job _ func `""" | logger . info ( 'Running job %s' , self )
ret = self . job_func ( )
self . last_run = datetime . datetime . now ( )
self . _schedule_next_run ( )
return ret |
def _convert_oauth2_credentials ( credentials ) :
"""Converts to : class : ` google . oauth2 . credentials . Credentials ` .
Args :
credentials ( Union [ oauth2client . client . OAuth2Credentials ,
oauth2client . client . GoogleCredentials ] ) : The credentials to
convert .
Returns :
google . oauth2 . c... | new_credentials = google . oauth2 . credentials . Credentials ( token = credentials . access_token , refresh_token = credentials . refresh_token , token_uri = credentials . token_uri , client_id = credentials . client_id , client_secret = credentials . client_secret , scopes = credentials . scopes )
new_credentials . _... |
def get_docker_io ( self , container_id , all_stats ) :
"""Return the container IO usage using the Docker API ( v1.0 or higher ) .
Input : id is the full container id
Output : a dict { ' time _ since _ update ' : 3000 , ' ior ' : 10 , ' iow ' : 65 } .
with :
time _ since _ update : number of seconds elapsed... | # Init the returned dict
io_new = { }
# Read the ior / iow stats ( in bytes )
try :
iocounters = all_stats [ "blkio_stats" ]
except KeyError as e : # all _ stats do not have io information
logger . debug ( "docker plugin - Cannot grab block IO usage for container {} ({})" . format ( container_id , e ) )
log... |
def set_filters ( self , filters ) :
"""Sets the filters for the server .
: Parameters :
filters
List of filters to set on this server , or None to remove all filters .
Elements in list should subclass Filter""" | if filters == None or isinstance ( filters , ( tuple , list ) ) :
self . filters = filters
else :
self . filters = [ filters ] |
def getZoom ( self , resolution ) :
"Return the zoom level for a given resolution" | assert resolution in self . RESOLUTIONS
return self . RESOLUTIONS . index ( resolution ) |
def pages_sub_menu ( context , page , url = '/' ) :
"""Get the root page of the given page and
render a nested list of all root ' s children pages .
Good for rendering a secondary menu .
: param page : the page where to start the menu from .
: param url : not used anymore .""" | lang = context . get ( 'lang' , pages_settings . PAGE_DEFAULT_LANGUAGE )
page = get_page_from_string_or_id ( page , lang )
if page :
root = page . get_root ( )
children = root . get_children_for_frontend ( )
context . update ( { 'children' : children , 'page' : page } )
return context |
def relaxNGValidateDoc ( self , doc ) :
"""Validate a document tree in memory .""" | if doc is None :
doc__o = None
else :
doc__o = doc . _o
ret = libxml2mod . xmlRelaxNGValidateDoc ( self . _o , doc__o )
return ret |
def apply_sql ( self , ex , values , lockref ) :
"""call the stmt in tree with values subbed on the tables in t _ d .
ex is a parsed statement returned by parse _ expression .
values is the tuple of % s replacements .
lockref can be anything as long as it stays the same ; it ' s used for assigning tranaction ... | sqex . depth_first_sub ( ex , values )
with self . lock_db ( lockref , isinstance ( ex , sqparse2 . StartX ) ) :
sqex . replace_subqueries ( ex , self , table . Table )
if isinstance ( ex , sqparse2 . SelectX ) :
return sqex . run_select ( ex , self , table . Table )
elif isinstance ( ex , sqparse2 ... |
def partition_block ( block ) :
"""If a block is not partitionable , returns a list with the same block .
Otherwise , returns a list with the resulting blocks , recursively .""" | result = [ block ]
if not block . is_partitionable :
return result
EDP = END_PROGRAM_LABEL + ':'
for i in range ( len ( block ) - 1 ) :
if i and block . asm [ i ] == EDP : # END _ PROGRAM label always starts a basic block
block , new_block = block_partition ( block , i - 1 )
LABELS [ END_PROGRAM... |
def fluoview_description_metadata ( description , ignoresections = None ) :
"""Return metatata from FluoView image description as dict .
The FluoView image description format is unspecified . Expect failures .
> > > descr = ( ' [ Intensity Mapping ] \\ nMap Ch0 : Range = 00000 to 02047 \\ n '
. . . ' [ Intens... | if not description . startswith ( '[' ) :
raise ValueError ( 'invalid FluoView image description' )
if ignoresections is None :
ignoresections = { 'Region Info (Fields)' , 'Protocol Description' }
result = { }
sections = [ result ]
comment = False
for line in description . splitlines ( ) :
if not comment :
... |
def get_frontend_node ( self ) :
"""Returns the first node of the class specified in the
configuration file as ` ssh _ to ` , or the first node of
the first class in alphabetic order .
: return : : py : class : ` Node `
: raise : : py : class : ` elasticluster . exceptions . NodeNotFound ` if no
valid fro... | if self . ssh_to :
if self . ssh_to in self . nodes :
cls = self . nodes [ self . ssh_to ]
if cls :
return cls [ 0 ]
else :
log . warning ( "preferred `ssh_to` `%s` is empty: unable to " "get the choosen frontend node from that class." , self . ssh_to )
else :
... |
def add_grad ( left , right ) :
"""Recursively add the gradient of two objects .
Args :
left : The left value to add . Can be either an array , a number , list or
dictionary .
right : The right value . Must be of the same type ( recursively ) as the left .
Returns :
The sum of the two gradients , which ... | # We assume that initial gradients are always identity WRT add _ grad .
# We also assume that only init _ grad could have created None values .
assert left is not None and right is not None
left_type = type ( left )
right_type = type ( right )
if left_type is ZeroGradient :
return right
if right_type is ZeroGradien... |
def variables ( self ) :
"""Returns : class : ` Variables ` instance .""" | return Variables ( [ ( k , self . _unescape ( k , v ) , sl ) for k , v , sl in self . _nodes_to_values ( ) ] ) |
def get_score_metadata ( self ) :
"""Gets the metadata for a score .
return : ( osid . Metadata ) - metadata for the score
* compliance : mandatory - - This method must be implemented . *""" | # Implemented from template for osid . resource . ResourceForm . get _ group _ metadata _ template
metadata = dict ( self . _mdata [ 'score' ] )
metadata . update ( { 'existing_decimal_values' : self . _my_map [ 'score' ] } )
return Metadata ( ** metadata ) |
def rearrange_nums ( nums ) :
"""Rearranges an array of integers , sorting the values at odd indices in
non - increasing order and the values at even indices in non - decreasing order .
Args :
nums ( List [ int ] ) : A 0 - indexed integer array .
Returns :
List [ int ] : A new array formed after rearrangi... | n = len ( nums )
ev = list ( sorted ( nums [ : : 2 ] ) )
od = list ( reversed ( sorted ( nums [ 1 : : 2 ] ) ) )
res = [ None for _ in range ( n ) ]
for i in range ( n ) :
if i % 2 == 0 :
res [ i ] = ev [ i // 2 ]
else :
res [ i ] = od [ i // 2 ]
return res |
def _load_assembly_mapping_data ( filename ) :
"""Load assembly mapping data .
Parameters
filename : str
path to compressed archive with assembly mapping data
Returns
assembly _ mapping _ data : dict
dict of assembly maps if loading was successful , else None
Notes
Keys of returned dict are chromoso... | try :
assembly_mapping_data = { }
with tarfile . open ( filename , "r" ) as tar : # http : / / stackoverflow . com / a / 2018576
for member in tar . getmembers ( ) :
if ".json" in member . name :
with tar . extractfile ( member ) as tar_file :
tar_bytes = ... |
def validate ( options ) :
"""Validates the application of this backend to a given metadata""" | try :
if options . backends . index ( 'modelinstance' ) > options . backends . index ( 'model' ) :
raise Exception ( "Metadata backend 'modelinstance' must come before 'model' backend" )
except ValueError :
raise Exception ( "Metadata backend 'modelinstance' must be installed in order to use 'model' bac... |
def run ( self ) :
"""Run import .""" | latest_track = Track . objects . all ( ) . order_by ( '-last_played' )
latest_track = latest_track [ 0 ] if latest_track else None
importer = self . get_importer ( )
tracks = importer . run ( )
# Create / update Django Track objects for importer tracks .
for track in tracks : # Only create / update if tracks with start... |
def _call_cli ( self , command , cwd = None , universal_newlines = False , redirect_stderr = False ) :
"""Executes the given command , internally using Popen . The output of
stdout and stderr are returned as a tuple . The returned tuple looks
like : ( stdout , stderr , returncode )
Parameters
command : stri... | command = str ( command . encode ( "utf-8" ) . decode ( "ascii" , "ignore" ) )
env = os . environ . copy ( )
env . update ( self . envvars )
stderr = STDOUT if redirect_stderr else PIPE
proc = Popen ( shlex . split ( command ) , stdout = PIPE , stderr = stderr , cwd = cwd , universal_newlines = universal_newlines , env... |
def to_csv ( self , path , iamc_index = False , ** kwargs ) :
"""Write timeseries data to a csv file
Parameters
path : string
file path
iamc _ index : bool , default False
if True , use ` [ ' model ' , ' scenario ' , ' region ' , ' variable ' , ' unit ' ] ` ;
else , use all ` data ` columns""" | self . _to_file_format ( iamc_index ) . to_csv ( path , index = False , ** kwargs ) |
def make_chunk_iter ( stream , separator , limit = None , buffer_size = 10 * 1024 ) :
"""Works like : func : ` make _ line _ iter ` but accepts a separator
which divides chunks . If you want newline based processing
you should use : func : ` make _ limited _ stream ` instead as it
supports arbitrary newline m... | _read = make_chunk_iter_func ( stream , limit , buffer_size )
_split = re . compile ( r'(%s)' % re . escape ( separator ) ) . split
buffer = [ ]
while 1 :
new_data = _read ( )
if not new_data :
break
chunks = _split ( new_data )
new_buf = [ ]
for item in chain ( buffer , chunks ) :
i... |
def changeLane ( self , vehID , laneIndex , duration ) :
"""changeLane ( string , int , int ) - > None
Forces a lane change to the lane with the given index ; if successful ,
the lane will be chosen for the given amount of time ( in ms ) .""" | self . _connection . _beginMessage ( tc . CMD_SET_VEHICLE_VARIABLE , tc . CMD_CHANGELANE , vehID , 1 + 4 + 1 + 1 + 1 + 4 )
self . _connection . _string += struct . pack ( "!BiBBBi" , tc . TYPE_COMPOUND , 2 , tc . TYPE_BYTE , laneIndex , tc . TYPE_INTEGER , duration )
self . _connection . _sendExact ( ) |
def inodeusage ( args = None ) :
'''Return inode usage information for volumes mounted on this minion
CLI Example :
. . code - block : : bash
salt ' * ' disk . inodeusage''' | flags = _clean_flags ( args , 'disk.inodeusage' )
if __grains__ [ 'kernel' ] == 'AIX' :
cmd = 'df -i'
else :
cmd = 'df -iP'
if flags :
cmd += ' -{0}' . format ( flags )
ret = { }
out = __salt__ [ 'cmd.run' ] ( cmd , python_shell = False ) . splitlines ( )
for line in out :
if line . startswith ( 'Filesy... |
def maybe_render_markdown ( string : str ) -> Any :
"""Render a string as Markdown only if in an IPython interpreter .""" | if is_ipython_interpreter ( ) : # pragma : no cover
from IPython . display import Markdown
# type : ignore # noqa : E501
return Markdown ( string )
else :
return string |
def url_to_path ( url ) : # type : ( str ) - > str
"""Convert a file : URL to a path .""" | assert url . startswith ( 'file:' ) , ( "You can only turn file: urls into filenames (not %r)" % url )
_ , netloc , path , _ , _ = urllib_parse . urlsplit ( url )
# if we have a UNC path , prepend UNC share notation
if netloc :
netloc = '\\\\' + netloc
path = urllib_request . url2pathname ( netloc + path )
return p... |
def gps_status_encode ( self , satellites_visible , satellite_prn , satellite_used , satellite_elevation , satellite_azimuth , satellite_snr ) :
'''The positioning status , as reported by GPS . This message is intended
to display status information about each satellite
visible to the receiver . See message GLOB... | return MAVLink_gps_status_message ( satellites_visible , satellite_prn , satellite_used , satellite_elevation , satellite_azimuth , satellite_snr ) |
def addfunctions ( abunch ) :
"""add functions to epbunch""" | key = abunch . obj [ 0 ] . upper ( )
# TODO : alternate strategy to avoid listing the objkeys in snames
# check if epbunch has field " Zone _ Name " or " Building _ Surface _ Name "
# and is in group u ' Thermal Zones and Surfaces '
# then it is likely to be a surface .
# of course we need to recode for surfaces that d... |
def validateArchiveList ( archiveList ) :
"""Validates an archiveList .
An ArchiveList must :
1 . Have at least one archive config . Example : ( 60 , 86400)
2 . No archive may be a duplicate of another .
3 . Higher precision archives ' precision must evenly divide all lower precision archives ' precision . ... | if not archiveList :
raise InvalidConfiguration ( "You must specify at least one archive configuration!" )
archiveList = sorted ( archiveList , key = lambda a : a [ 0 ] )
# sort by precision ( secondsPerPoint )
for i , archive in enumerate ( archiveList ) :
if i == len ( archiveList ) - 1 :
break
ne... |
def attributes ( self ) :
"""Return sync attributes .""" | attr = { 'name' : self . name , 'id' : self . sync_id , 'network_id' : self . network_id , 'serial' : self . serial , 'status' : self . status , 'region' : self . region , 'region_id' : self . region_id , }
return attr |
def metric_arun_2010 ( topic_word_distrib , doc_topic_distrib , doc_lengths ) :
"""Rajkumar Arun , V . Suresh , C . E . Veni Madhavan , and M . N . Narasimha Murthy . 2010 . On finding the natural number of
topics with latent dirichlet allocation : Some observations . In Advances in knowledge discovery and data m... | # Note : It will fail when num . of words in the vocabulary is less then the num . of topics ( which is very unusual ) .
# CM1 = SVD ( M1)
cm1 = np . linalg . svd ( topic_word_distrib , compute_uv = False )
# cm1 / = np . sum ( cm1 ) # normalize by L1 norm # the paper says nothing about normalizing so let ' s leave it ... |
def pull ( image , insecure_registry = False , api_response = False , client_timeout = salt . utils . docker . CLIENT_TIMEOUT ) :
'''. . versionchanged : : 2018.3.0
If no tag is specified in the ` ` image ` ` argument , all tags for the
image will be pulled . For this reason is it recommended to pass
` ` imag... | _prep_pull ( )
kwargs = { 'stream' : True , 'client_timeout' : client_timeout }
if insecure_registry :
kwargs [ 'insecure_registry' ] = insecure_registry
time_started = time . time ( )
response = _client_wrapper ( 'pull' , image , ** kwargs )
ret = { 'Time_Elapsed' : time . time ( ) - time_started , 'retcode' : 0 }... |
def isnat ( obj ) :
"""Check if a value is np . NaT .""" | if obj . dtype . kind not in ( 'm' , 'M' ) :
raise ValueError ( "%s is not a numpy datetime or timedelta" )
return obj . view ( int64_dtype ) == iNaT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.