signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def findFileParam ( self , comp ) :
"""Finds the filename auto - parameter that component * comp * is
in , and returns all the filenames for that parameter . Notes this
assumes that * comp * will only be in a single filename auto - parameter .
: param comp : Component to search parameter membership for
: ty... | for p in self . _parameters :
if p [ 'parameter' ] == 'filename' and comp in p [ 'selection' ] :
return p [ 'names' ] |
def register ( parser ) :
"""Register commands with the given parser .""" | cmd_machines . register ( parser )
cmd_machine . register ( parser )
cmd_allocate . register ( parser )
cmd_deploy . register ( parser )
cmd_commission . register ( parser )
cmd_release . register ( parser )
cmd_abort . register ( parser )
cmd_mark_fixed . register ( parser )
cmd_mark_broken . register ( parser )
cmd_p... |
def insert ( self , node , before = None ) :
"""Insert a new node in the list .
If * before * is specified , the new node is inserted before this node .
Otherwise , the node is inserted at the end of the list .""" | node . _list = self
if self . _first is None :
self . _first = self . _last = node
# first node in list
self . _size += 1
return node
if before is None :
self . _last . _next = node
# insert as last node
node . _prev = self . _last
self . _last = node
else :
node . _next = before
... |
def twoSurfplots ( self ) :
"""Plot multiple subplot figure for 2D array""" | # Could more elegantly just call surfplot twice
# And also could include xyzinterp as an option inside surfplot .
# Noted here in case anyone wants to take that on in the future . . .
plt . subplot ( 211 )
plt . title ( 'Load thickness, mantle equivalent [m]' , fontsize = 16 )
if self . latlon :
plt . imshow ( self... |
def deliver_hook ( target , payload , instance_id = None , hook_id = None , ** kwargs ) :
"""target : the url to receive the payload .
payload : a python primitive data structure
instance _ id : a possibly None " trigger " instance ID
hook _ id : the ID of defining Hook object""" | r = requests . post ( url = target , data = json . dumps ( payload ) , headers = { "Content-Type" : "application/json" , "Authorization" : "Token %s" % settings . HOOK_AUTH_TOKEN , } , )
r . raise_for_status ( )
return r . text |
def login ( ) :
"""Enables the user to login to the remote GMQL service .
If both username and password are None , the user will be connected as guest .""" | from . RemoteConnection . RemoteManager import RemoteManager
global __remote_manager , __session_manager
logger = logging . getLogger ( )
remote_address = get_remote_address ( )
res = __session_manager . get_session ( remote_address )
if res is None : # there is no session for this address , let ' s login as guest
... |
def top ( num_processes = 5 , interval = 3 ) :
'''Return a list of top CPU consuming processes during the interval .
num _ processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples :
. . code - block : : bash
salt ' * ' ps . top
salt ' * ... | result = [ ]
start_usage = { }
for pid in psutil . pids ( ) :
try :
process = psutil . Process ( pid )
user , system = process . cpu_times ( )
except ValueError :
user , system , _ , _ = process . cpu_times ( )
except psutil . NoSuchProcess :
continue
start_usage [ proces... |
def find_config ( test_file = None , defaults = None , root = os . curdir ) :
"""Find the path to the default config file .
We look at : root : for the : default : config file . If we can ' t find it
there we start looking at the parent directory recursively until we
find a file named : default : and return t... | if defaults is None :
defaults = [ ".benchbuild.yml" , ".benchbuild.yaml" ]
def walk_rec ( cur_path , root ) :
cur_path = local . path ( root ) / test_file
if cur_path . exists ( ) :
return cur_path
new_root = local . path ( root ) / os . pardir
return walk_rec ( cur_path , new_root ) if new... |
def init ( opts , no_install = False , quiet = False ) :
"""Initialize a purged environment or copied environment directory
Usage :
datacats init [ - in ] [ - - syslog ] [ - s NAME ] [ - - address = IP ] [ - - interactive ]
[ - - site - url SITE _ URL ] [ ENVIRONMENT _ DIR [ PORT ] ] [ - - no - init - db ]
... | if opts [ '--address' ] and is_boot2docker ( ) :
raise DatacatsError ( 'Cannot specify address on boot2docker.' )
environment_dir = opts [ 'ENVIRONMENT_DIR' ]
port = opts [ 'PORT' ]
address = opts [ '--address' ]
start_web = not opts [ '--image-only' ]
create_sysadmin = not opts [ '--no-sysadmin' ]
site_name = opts... |
def receive ( host , timeout ) :
"""Print all messages in queue .
Args :
host ( str ) : Specified - - host .
timeout ( int ) : How log should script wait for message .""" | parameters = settings . get_amqp_settings ( ) [ host ]
queues = parameters [ "queues" ]
queues = dict ( map ( lambda ( x , y ) : ( y , x ) , queues . items ( ) ) )
# reverse items
queue = queues [ parameters [ "out_key" ] ]
channel = _get_channel ( host , timeout )
for method_frame , properties , body in channel . cons... |
def named_field_regex ( keypat_tups ) :
"""named _ field _ regex
Args :
keypat _ tups ( list ) : tuples of ( name , pattern ) or a string for an unnamed
pattern
Returns :
str : regex
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . util _ regex import * # NOQA
> > > keypat _ tups = [
. . . ... | # Allow for unnamed patterns
keypat_tups_ = [ ( None , tup ) if isinstance ( tup , six . string_types ) else tup for tup in keypat_tups ]
named_fields = [ named_field ( key , pat ) for key , pat in keypat_tups_ ]
regex = '' . join ( named_fields )
return regex |
def update_config_mode ( self , prompt = None ) :
"""Update config mode .""" | # TODO : Fix the conflict with config mode attribute at connection
if prompt :
self . mode = self . driver . update_config_mode ( prompt )
else :
self . mode = self . driver . update_config_mode ( self . prompt ) |
def setup_argparse ( ) :
"""Setup the argparse argument parser
: return : instance of argparse
: rtype : ArgumentParser""" | parser = argparse . ArgumentParser ( description = 'Convert old ini-style GNS3 topologies (<=0.8.7) to ' 'the newer version 1+ JSON format' )
parser . add_argument ( '--version' , action = 'version' , version = '%(prog)s ' + __version__ )
parser . add_argument ( '-n' , '--name' , help = 'Topology name (default uses the... |
def AddValue ( self , name , number , aliases = None , description = None ) :
"""Adds an enumeration value .
Args :
name ( str ) : name .
number ( int ) : number .
aliases ( Optional [ list [ str ] ] ) : aliases .
description ( Optional [ str ] ) : description .
Raises :
KeyError : if the enumeration ... | if name in self . values_per_name :
raise KeyError ( 'Value with name: {0:s} already exists.' . format ( name ) )
if number in self . values_per_number :
raise KeyError ( 'Value with number: {0!s} already exists.' . format ( number ) )
for alias in aliases or [ ] :
if alias in self . values_per_alias :
... |
def overlay ( main_parent_node , overlay_parent_node , eof_action = 'repeat' , ** kwargs ) :
"""Overlay one video on top of another .
Args :
x : Set the expression for the x coordinates of the overlaid video on the main video . Default value is 0 . In
case the expression is invalid , it is set to a huge value... | kwargs [ 'eof_action' ] = eof_action
return FilterNode ( [ main_parent_node , overlay_parent_node ] , overlay . __name__ , kwargs = kwargs , max_inputs = 2 ) . stream ( ) |
def beautify ( self , string ) :
"""Wraps together all actions needed to beautify a string , i . e .
parse the string and then stringify the phrases ( replace tags
with formatting codes ) .
Arguments :
string ( str ) : The string to beautify / parse .
Returns :
The parsed , stringified and ultimately be... | if not string :
return string
# string may differ because of escaped characters
string , phrases = self . parse ( string )
if not phrases :
return string
if not self . positional and not self . always :
raise errors . ArgumentError ( "Found phrases, but no styles " "were supplied!" )
return self . stringify... |
def getScales ( self , term_i = None ) :
"""Returns the Parameters
Args :
term _ i : index of the term we are interested in
if term _ i = = None returns the whole vector of parameters""" | if term_i == None :
RV = self . vd . getScales ( )
else :
assert term_i < self . n_terms , 'Term index non valid'
RV = self . vd . getScales ( term_i )
return RV |
def points_properties_df ( self ) :
"""Return a dictionary of point / point _ properties in preparation for storage in SQL .""" | pprops = { }
for each in self . points :
p = each . properties . asdict . copy ( )
p . pop ( "device" , None )
p . pop ( "network" , None )
p . pop ( "simulated" , None )
p . pop ( "overridden" , None )
pprops [ each . properties . name ] = p
df = pd . DataFrame ( pprops )
return df |
def makeDirectory ( self , full_path , dummy = 40841 ) :
"""Make a directory
> > > nd . makeDirectory ( ' / test ' )
: param full _ path : The full path to get the directory property . Should be end with ' / ' .
: return : ` ` True ` ` when success to make a directory or ` ` False ` `""" | if full_path [ - 1 ] is not '/' :
full_path += '/'
data = { 'dstresource' : full_path , 'userid' : self . user_id , 'useridx' : self . useridx , 'dummy' : dummy , }
s , metadata = self . POST ( 'makeDirectory' , data )
return s |
def key ( self , direction , mechanism , purviews = False , _prefix = None ) :
"""Cache key . This is the call signature of | Subsystem . find _ mice ( ) | .""" | return "subsys:{}:{}:{}:{}:{}" . format ( self . subsystem_hash , _prefix , direction , mechanism , purviews ) |
def __stringlist ( self , ttype , tvalue ) :
"""Specific method to parse the ' string - list ' type
Syntax :
string - list = " [ " string * ( " , " string ) " ] " / string
; if there is only a single string , the brackets
; are optional""" | if ttype == "string" :
self . __curstringlist += [ tvalue . decode ( "utf-8" ) ]
self . __set_expected ( "comma" , "right_bracket" )
return True
if ttype == "comma" :
self . __set_expected ( "string" )
return True
if ttype == "right_bracket" :
self . __curcommand . check_next_arg ( "stringlist" ... |
def spherical_k_means ( X , n_clusters , sample_weight = None , init = "k-means++" , n_init = 10 , max_iter = 300 , verbose = False , tol = 1e-4 , random_state = None , copy_x = True , n_jobs = 1 , algorithm = "auto" , return_n_iter = False , ) :
"""Modified from sklearn . cluster . k _ means _ . k _ means .""" | if n_init <= 0 :
raise ValueError ( "Invalid number of initializations." " n_init=%d must be bigger than zero." % n_init )
random_state = check_random_state ( random_state )
if max_iter <= 0 :
raise ValueError ( "Number of iterations should be a positive number," " got %d instead" % max_iter )
best_inertia = np... |
def plot_number_observer_with_matplotlib ( * args , ** kwargs ) :
"""Generate a plot from NumberObservers and show it on IPython notebook
with matplotlib .
Parameters
obs : NumberObserver ( e . g . FixedIntervalNumberObserver )
fmt : str , optional
opt : dict , optional
matplotlib plot options .
Examp... | import matplotlib . pylab as plt
import numpy
import collections
special_keys = ( "xlim" , "ylim" , "xlabel" , "ylabel" , "legend" , "x" , "y" , "filename" )
plot_opts = { key : value for key , value in kwargs . items ( ) if key not in special_keys }
if 'axes.prop_cycle' in plt . rcParams . keys ( ) :
color_cycle =... |
def getdict ( locale ) :
"""Generate or get convertion dict cache for certain locale .
Dictionaries are loaded on demand .""" | global zhcdicts , dict_zhcn , dict_zhsg , dict_zhtw , dict_zhhk , pfsdict
if zhcdicts is None :
loaddict ( DICTIONARY )
if locale == 'zh-cn' :
if dict_zhcn :
got = dict_zhcn
else :
dict_zhcn = zhcdicts [ 'zh2Hans' ] . copy ( )
dict_zhcn . update ( zhcdicts [ 'zh2CN' ] )
got =... |
def valid_connection ( * outer_args , ** outer_kwargs ) : # pylint : disable = unused - argument , no - method - argument
"""Check if the daemon connection is established and valid""" | def decorator ( func ) : # pylint : disable = missing - docstring
def decorated ( * args , ** kwargs ) : # pylint : disable = missing - docstring
# outer _ args and outer _ kwargs are the decorator arguments
# args and kwargs are the decorated function arguments
link = args [ 0 ]
if not link... |
def handle_stream ( self , message ) :
"""Acts on message reception
: param message : string of an incoming message
parse all the fields and builds an Event object that is passed to the callback function""" | logging . debug ( "handle_stream(...)" )
event = Event ( )
for line in message . strip ( ) . splitlines ( ) :
( field , value ) = line . split ( ":" , 1 )
field = field . strip ( )
if field == "event" :
event . name = value . lstrip ( )
elif field == "data" :
value = value . lstrip ( )
... |
def css_class ( self , cell ) :
"""Return the CSS class for this column .""" | if isinstance ( self . _css_class , basestring ) :
return self . _css_class
else :
return self . _css_class ( cell ) |
def hourly_solar_radiation ( self ) :
"""Three data collections containing hourly direct normal , diffuse horizontal ,
and global horizontal radiation .""" | dir_norm , diff_horiz , glob_horiz = self . _sky_condition . radiation_values ( self . _location )
dir_norm_data = self . _get_daily_data_collections ( energyintensity . DirectNormalRadiation ( ) , 'Wh/m2' , dir_norm )
diff_horiz_data = self . _get_daily_data_collections ( energyintensity . DiffuseHorizontalRadiation (... |
def get_fwhm_tag ( expnum , ccd , prefix = None , version = 'p' ) :
"""Get the FWHM from the VOSpace annotation .
@ param expnum :
@ param ccd :
@ param prefix :
@ param version :
@ return :""" | uri = get_uri ( expnum , ccd , version , ext = 'fwhm' , prefix = prefix )
if uri not in fwhm :
key = "fwhm_{:1s}{:02d}" . format ( version , int ( ccd ) )
fwhm [ uri ] = get_tag ( expnum , key )
return fwhm [ uri ] |
def configure_uwsgi ( configurator_func ) :
"""Allows configuring uWSGI using Configuration objects returned
by the given configuration function .
. . code - block : python
# In configuration module , e . g ` uwsgicfg . py `
from uwsgiconf . config import configure _ uwsgi
configure _ uwsgi ( get _ config... | from . settings import ENV_CONF_READY , ENV_CONF_ALIAS , CONFIGS_MODULE_ATTR
if os . environ . get ( ENV_CONF_READY ) : # This call is from uWSGI trying to load an application .
# We prevent unnecessary configuration
# for setups where application is located in the same
# file as configuration .
del os . environ [ ... |
def get_batch ( self , user_list ) :
"""批量获取用户基本信息
开发者可通过该接口来批量获取用户基本信息 。 最多支持一次拉取100条 。
详情请参考
https : / / mp . weixin . qq . com / wiki ? t = resource / res _ main & id = mp1421140839
: param user _ list : user _ list , 支持 “ 使用示例 ” 中两种输入格式
: return : 用户信息的 list
使用示例 : :
from wechatpy import WeChatCli... | if all ( ( isinstance ( x , six . string_types ) for x in user_list ) ) :
user_list = [ { 'openid' : oid } for oid in user_list ]
res = self . _post ( 'user/info/batchget' , data = { 'user_list' : user_list } , result_processor = lambda x : x [ 'user_info_list' ] )
return res |
def _android_update_sdk ( self , * sdkmanager_commands ) :
"""Update the tools and package - tools if possible""" | auto_accept_license = self . buildozer . config . getbooldefault ( 'app' , 'android.accept_sdk_license' , False )
if auto_accept_license : # ` SIGPIPE ` is not being reported somehow , but ` EPIPE ` is .
# This leads to a stderr " Broken pipe " message which is harmless ,
# but doesn ' t look good on terminal , hence r... |
def get_msg_login ( self , username ) :
"""message for welcome .""" | account = self . get_account ( username )
if account :
account . update_last_login ( )
account . save ( )
return 'welcome.' |
def cli ( ctx , name , all ) :
"""Show example for doing some task in bubble ( experimental )""" | ctx . gbc . say ( 'all_example_functions' , stuff = all_examples_functions , verbosity = 1000 )
for example in all_examples_functions :
if all or ( name and example [ 'name' ] == name ) :
if all :
ctx . gbc . say ( 'example' , stuff = example , verbosity = 100 )
name = example [ 'nam... |
def get_session ( self , username , password , remote = "127.0.0.1" , proxy = None ) :
"""Create a session for a user .
Attempts to create a user session on the Crowd server .
Args :
username : The account username .
password : The account password .
remote :
The remote address of the user . This can be... | params = { "username" : username , "password" : password , "validation-factors" : { "validationFactors" : [ { "name" : "remote_address" , "value" : remote , } , ] } }
if proxy :
params [ "validation-factors" ] [ "validationFactors" ] . append ( { "name" : "X-Forwarded-For" , "value" : proxy , } )
response = self . ... |
def update ( self , message = None , subject = None , days = None , downloads = None , notify = None ) :
"""Update properties for a transfer .
: param message : updated message to recipient ( s )
: param subject : updated subject for trasfer
: param days : updated amount of days transfer is available
: para... | method , url = get_URL ( 'update' )
payload = { 'apikey' : self . config . get ( 'apikey' ) , 'logintoken' : self . session . cookies . get ( 'logintoken' ) , 'transferid' : self . transfer_id , }
data = { 'message' : message or self . transfer_info . get ( 'message' ) , 'message' : subject or self . transfer_info . ge... |
def iter_chunks ( cls , sock , return_bytes = False , timeout_object = None ) :
"""Generates chunks from a connected socket until an Exit chunk is sent or a timeout occurs .
: param sock : the socket to read from .
: param bool return _ bytes : If False , decode the payload into a utf - 8 string .
: param cls... | assert ( timeout_object is None or isinstance ( timeout_object , cls . TimeoutProvider ) )
orig_timeout_time = None
timeout_interval = None
while 1 :
if orig_timeout_time is not None :
remaining_time = time . time ( ) - ( orig_timeout_time + timeout_interval )
if remaining_time > 0 :
ori... |
def cfrom ( self ) :
"""The initial character position in the surface string .
Defaults to - 1 if there is no valid cfrom value .""" | cfrom = - 1
try :
if self . lnk . type == Lnk . CHARSPAN :
cfrom = self . lnk . data [ 0 ]
except AttributeError :
pass
# use default cfrom of - 1
return cfrom |
def get_window_from_xy ( self , xy ) :
"""Get the window index given a coordinate ( raster CRS ) .""" | a_transform = self . _get_template_for_given_resolution ( res = self . dst_res , return_ = "meta" ) [ "transform" ]
row , col = transform . rowcol ( a_transform , xy [ 0 ] , xy [ 1 ] )
ij_containing_xy = None
for ji , win in enumerate ( self . windows ) :
( row_start , row_end ) , ( col_start , col_end ) = rasterio... |
def load_from_docinfo ( self , docinfo , delete_missing = False , raise_failure = False ) :
"""Populate the XMP metadata object with DocumentInfo
Arguments :
docinfo : a DocumentInfo , e . g pdf . docinfo
delete _ missing : if the entry is not DocumentInfo , delete the equivalent
from XMP
raise _ failure ... | for uri , shortkey , docinfo_name , converter in self . DOCINFO_MAPPING :
qname = QName ( uri , shortkey )
# docinfo might be a dict or pikepdf . Dictionary , so lookup keys
# by str ( Name )
val = docinfo . get ( str ( docinfo_name ) )
if val is None :
if delete_missing and qname in self :
... |
def limits ( self , clip_negative = True ) :
"""Return intensity limits , i . e . ( min , max ) tuple , of the dtype .
Args :
clip _ negative : bool , optional
If True , clip the negative range ( i . e . return 0 for min intensity )
even if the image dtype allows negative values .
Returns
min , max : tu... | min , max = dtype_range [ self . as_numpy_dtype ]
# pylint : disable = redefined - builtin
if clip_negative :
min = 0
# pylint : disable = redefined - builtin
return min , max |
def ensure_project ( three = None , python = None , validate = True , system = False , warn = True , site_packages = False , deploy = False , skip_requirements = False , pypi_mirror = None , clear = False , ) :
"""Ensures both Pipfile and virtualenv exist for the project .""" | from . environments import PIPENV_USE_SYSTEM
# Clear the caches , if appropriate .
if clear :
print ( "clearing" )
sys . exit ( 1 )
# Automatically use an activated virtualenv .
if PIPENV_USE_SYSTEM :
system = True
if not project . pipfile_exists and deploy :
raise exceptions . PipfileNotFound
# Fail if... |
def set_orient ( self ) :
"""Return the computed orientation based on CD matrix .""" | self . orient = RADTODEG ( N . arctan2 ( self . cd12 , self . cd22 ) ) |
def _ParseItems ( self , parser_mediator , msiecf_file ) :
"""Parses a MSIE Cache File ( MSIECF ) items .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
msiecf _ file ( pymsiecf . file ) : MSIECF file .""" | format_version = msiecf_file . format_version
decode_error = False
cache_directories = [ ]
for cache_directory_name in iter ( msiecf_file . cache_directories ) :
try :
cache_directory_name = cache_directory_name . decode ( 'ascii' )
except UnicodeDecodeError :
decode_error = True
cache_d... |
def _update_internal_states ( self , message ) :
"""Updates internal device states .
: param message : : py : class : ` ~ alarmdecoder . messages . Message ` to update internal states with
: type message : : py : class : ` ~ alarmdecoder . messages . Message ` , : py : class : ` ~ alarmdecoder . messages . Expa... | if isinstance ( message , Message ) and not self . _ignore_message_states :
self . _update_armed_ready_status ( message )
self . _update_power_status ( message )
self . _update_chime_status ( message )
self . _update_alarm_status ( message )
self . _update_zone_bypass_status ( message )
self . _... |
def commentToJson ( comment ) :
"""Returns a serializable Comment dict
: param comment : Comment to get info for
: type comment : Comment
: returns : dict""" | obj = { 'id' : comment . id , 'comment' : comment . comment , 'user' : userToJson ( comment . user ) , 'date' : comment . submit_date . isoformat ( ) , }
return obj |
def get_users ( self , course ) :
"""Returns a sorted list of users""" | users = OrderedDict ( sorted ( list ( self . user_manager . get_users_info ( self . user_manager . get_course_registered_users ( course ) ) . items ( ) ) , key = lambda k : k [ 1 ] [ 0 ] if k [ 1 ] is not None else "" ) )
return users |
async def _reset_protocol ( self , exc = None ) :
"""Reset the protocol if an error occurs .""" | # Be responsible and clean up .
protocol = await self . _get_protocol ( )
await protocol . shutdown ( )
self . _protocol = None
# Let any observers know the protocol has been shutdown .
for ob_error in self . _observations_err_callbacks :
ob_error ( exc )
self . _observations_err_callbacks . clear ( ) |
def loader ( pattern , dimensions = None , distributed_dim = 'time' , read_only = False ) :
"""It provide a root descriptor to be used inside a with statement . It
automatically close the root when the with statement finish .
Keyword arguments :
root - - the root descriptor returned by the ' open ' function""... | if dimensions :
root = tailor ( pattern , dimensions , distributed_dim , read_only = read_only )
else :
root , _ = open ( pattern , read_only = read_only )
yield root
root . close ( ) |
def get_help_commands ( server_prefix ) :
"""Get the help commands for all modules
Args :
server _ prefix : The server command prefix
Returns :
datapacks ( list ) : A list of datapacks for the help commands for all the modules""" | datapacks = [ ]
_dir = os . path . realpath ( os . path . join ( os . getcwd ( ) , os . path . dirname ( __file__ ) ) )
for module_name in os . listdir ( "{}/../" . format ( _dir ) ) :
if not module_name . startswith ( "_" ) and not module_name . startswith ( "!" ) :
help_command = "`{}help {}`" . format ( ... |
def parse_net16string ( self ) :
"""> > > next ( InBuffer ( b " \\ 0 \\ x03eggs " ) . parse _ net16string ( ) ) = = b ' egg '
True""" | return parse_map ( operator . itemgetter ( 1 ) , parse_chain ( self . parse_net16int , self . parse_fixedbuffer ) ) |
def free ( self ) :
"""Free the memory referred to by the file - like , any subsequent
operations on this file - like or slices of it will fail .""" | # Free the memory
self . _machine_controller . sdram_free ( self . _start_address , self . _x , self . _y )
# Mark as freed
self . _freed = True |
def _adjust_merged_values_orm ( env , model_name , record_ids , target_record_id , field_spec ) :
"""This method deals with the values on the records to be merged +
the target record , performing operations that makes sense on the meaning
of the model .
: param field _ spec : Dictionary with field names as ke... | model = env [ model_name ]
fields = model . _fields . values ( )
all_records = model . browse ( tuple ( record_ids ) + ( target_record_id , ) )
target_record = model . browse ( target_record_id )
vals = { }
o2m_changes = 0
for field in fields :
if not field . store or field . compute or field . related :
co... |
def get_sequence ( queries , fap = None , fmt = 'fasta' , organism_taxid = 9606 , test = False ) :
"""http : / / www . ebi . ac . uk / Tools / dbfetch / dbfetch ? db = uniprotkb & id = P14060 + P26439 & format = fasta & style = raw & Retrieve = Retrieve
https : / / www . uniprot . org / uniprot / ? format = fasta... | url = 'http://www.ebi.ac.uk/Tools/dbfetch/dbfetch'
params = { 'id' : ' ' . join ( queries ) , 'db' : 'uniprotkb' , 'organism' : organism_taxid , 'format' : fmt , 'style' : 'raw' , 'Retrieve' : 'Retrieve' , }
response = requests . get ( url , params = params )
if test :
print ( response . url )
if response . ok :
... |
def libvlc_media_new_path ( p_instance , path ) :
'''Create a media for a certain file path .
See L { libvlc _ media _ release } .
@ param p _ instance : the instance .
@ param path : local filesystem path .
@ return : the newly created media or NULL on error .''' | f = _Cfunctions . get ( 'libvlc_media_new_path' , None ) or _Cfunction ( 'libvlc_media_new_path' , ( ( 1 , ) , ( 1 , ) , ) , class_result ( Media ) , ctypes . c_void_p , Instance , ctypes . c_char_p )
return f ( p_instance , path ) |
def triple_plot ( cccsum , cccsum_hist , trace , threshold , ** kwargs ) :
"""Plot a seismogram , correlogram and histogram .
: type cccsum : numpy . ndarray
: param cccsum : Array of the cross - channel cross - correlation sum
: type cccsum _ hist : numpy . ndarray
: param cccsum _ hist : cccsum for histog... | import matplotlib . pyplot as plt
if len ( cccsum ) != len ( trace . data ) :
print ( 'cccsum is: ' + str ( len ( cccsum ) ) + ' trace is: ' + str ( len ( trace . data ) ) )
msg = ' ' . join ( [ 'cccsum and trace must have the' , 'same number of data points' ] )
raise ValueError ( msg )
df = trace . stats .... |
def _update_chime_status ( self , message = None , status = None ) :
"""Uses the provided message to update the Chime state .
: param message : message to use to update
: type message : : py : class : ` ~ alarmdecoder . messages . Message `
: param status : chime status , overrides message bits .
: type sta... | chime_status = status
if isinstance ( message , Message ) :
chime_status = message . chime_on
if chime_status is None :
return
if chime_status != self . _chime_status :
self . _chime_status , old_status = chime_status , self . _chime_status
if old_status is not None :
self . on_chime_changed ( s... |
def export_xml_file_no_di ( self , directory , filename ) :
"""Exports diagram inner graph to BPMN 2.0 XML file ( without Diagram Interchange data ) .
: param directory : strings representing output directory ,
: param filename : string representing output file name .""" | bpmn_export . BpmnDiagramGraphExport . export_xml_file_no_di ( directory , filename , self ) |
def get_success_url ( self ) :
"""Returns redirect URL for valid form submittal .
: rtype : str .""" | if self . success_url :
url = force_text ( self . success_url )
else :
url = reverse ( '{0}:index' . format ( self . url_namespace ) )
return url |
def digest_filename ( filename , algorithm = DEFAULT_HASH_ALGORITHM , hash_library = DEFAULT_HASH_LIBRARY , normalize_line_endings = False ) :
"""< Purpose >
Generate a digest object , update its hash using a file object
specified by filename , and then return it to the caller .
< Arguments >
filename :
T... | # Are the arguments properly formatted ? If not , raise
# ' securesystemslib . exceptions . FormatError ' .
securesystemslib . formats . RELPATH_SCHEMA . check_match ( filename )
securesystemslib . formats . NAME_SCHEMA . check_match ( algorithm )
securesystemslib . formats . NAME_SCHEMA . check_match ( hash_library )
... |
def weingarten_image_curvature ( image , sigma = 1.0 , opt = 'mean' ) :
"""Uses the weingarten map to estimate image mean or gaussian curvature
ANTsR function : ` weingartenImageCurvature `
Arguments
image : ANTsImage
image from which curvature is calculated
sigma : scalar
smoothing parameter
opt : st... | if image . dimension not in { 2 , 3 } :
raise ValueError ( 'image must be 2D or 3D' )
if image . dimension == 2 :
d = image . shape
temp = np . zeros ( list ( d ) + [ 10 ] )
for k in range ( 1 , 7 ) :
voxvals = image [ : d [ 0 ] , : d [ 1 ] ]
temp [ : d [ 0 ] , : d [ 1 ] , k ] = voxvals
... |
def blend ( self , other ) :
"""Alpha blend * other * on top of the current image .""" | raise NotImplementedError ( "This method has not be implemented for " "xarray support." )
if self . mode != "RGBA" or other . mode != "RGBA" :
raise ValueError ( "Images must be in RGBA" )
src = other
dst = self
outa = src . channels [ 3 ] + dst . channels [ 3 ] * ( 1 - src . channels [ 3 ] )
for i in range ( 3 ) :... |
def decimal ( anon , obj , field , val ) :
"""Returns a random decimal""" | return anon . faker . decimal ( field = field ) |
def create_default_links ( self ) :
"""Create the default links between the IM and the device .""" | self . _plm . manage_aldb_record ( 0x40 , 0xe2 , 0x00 , self . address , self . cat , self . subcat , self . product_key )
self . manage_aldb_record ( 0x41 , 0xa2 , 0x00 , self . _plm . address , self . _plm . cat , self . _plm . subcat , self . _plm . product_key )
for link in self . _stateList :
state = self . _s... |
def _gen_xml ( name , cpu , mem , diskp , nicp , hypervisor , os_type , arch , graphics = None , loader = None , ** kwargs ) :
'''Generate the XML string to define a libvirt VM''' | mem = int ( mem ) * 1024
# MB
context = { 'hypervisor' : hypervisor , 'name' : name , 'cpu' : six . text_type ( cpu ) , 'mem' : six . text_type ( mem ) , }
if hypervisor in [ 'qemu' , 'kvm' ] :
context [ 'controller_model' ] = False
elif hypervisor == 'vmware' : # TODO : make bus and model parameterized , this work... |
def find ( self , ** kwargs ) :
"""Returns List ( typeof = ) .
Executes collection ' s find method based on keyword args
maps results ( dict to list of entity instances ) .
Set max _ limit parameter to limit the amount of data send back through network
Example : :
manager = EntityManager ( Product )
pro... | max_limit = None
if 'max_limit' in kwargs :
max_limit = kwargs . pop ( 'max_limit' )
cursor = self . __collection . find ( kwargs )
instances = [ ]
for doc in ( yield cursor . to_list ( max_limit ) ) :
instance = self . __entity ( )
instance . map_dict ( doc )
instances . append ( instance )
return inst... |
def calculate ( self ) :
"""Calculate the overall counts of best , worst , fastest , slowest , total
found , total not found and total runtime
Results are returned in a dictionary with the above parameters as keys .""" | best , worst , fastest , slowest = ( ) , ( ) , ( ) , ( )
found = notfound = total_time = 0
for source , rec in self . source_stats . items ( ) :
if not best or rec . successes > best [ 1 ] :
best = ( source , rec . successes , rec . success_rate ( ) )
if not worst or rec . successes < worst [ 1 ] :
... |
def prepare_data_maybe_download ( directory ) :
"""Download and unpack dialogs if necessary .""" | filename = 'ubuntu_dialogs.tgz'
url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz'
dialogs_path = os . path . join ( directory , 'dialogs' )
# test it there are some dialogs in the path
if not os . path . exists ( os . path . join ( directory , "10" , "1.tst" ) ) : # dialogs are missing
... |
def flatten ( l , types = ( list , ) ) :
"""Given a list / tuple that potentially contains nested lists / tuples of arbitrary nesting ,
flatten into a single dimension . In other words , turn [ ( 5 , 6 , [ 8 , 3 ] ) , 2 , [ 2 , 1 , ( 3 , 4 ) ] ]
into [ 5 , 6 , 8 , 3 , 2 , 2 , 1 , 3 , 4]
This is safe to call o... | # For backwards compatibility , this returned a list , not an iterable .
# Changing to return an iterable could break things .
if not isinstance ( l , types ) :
return l
return list ( flattened_iterator ( l , types ) ) |
def validate_registry_uri_authority ( auth : str ) -> None :
"""Raise an exception if the authority is not a valid ENS domain
or a valid checksummed contract address .""" | if is_ens_domain ( auth ) is False and not is_checksum_address ( auth ) :
raise ValidationError ( f"{auth} is not a valid registry URI authority." ) |
def admin_url_params ( request , params = None ) :
"""given a request , looks at GET and POST values to determine which params
should be added . Is used to keep the context of popup and picker mode .""" | params = params or { }
if popup_status ( request ) :
params [ IS_POPUP_VAR ] = '1'
pick_type = popup_pick_type ( request )
if pick_type :
params [ '_pick' ] = pick_type
return params |
def get_side_length_of_resize_handle ( view , item ) :
"""Calculate the side length of a resize handle
: param rafcon . gui . mygaphas . view . ExtendedGtkView view : View
: param rafcon . gui . mygaphas . items . state . StateView item : StateView
: return : side length
: rtype : float""" | from rafcon . gui . mygaphas . items . state import StateView , NameView
if isinstance ( item , StateView ) :
return item . border_width * view . get_zoom_factor ( ) / 1.5
elif isinstance ( item , NameView ) :
return item . parent . border_width * view . get_zoom_factor ( ) / 2.5
return 0 |
def _get_version_output ( self ) :
"""Ignoring errors , call ` ceph - - version ` and return only the version
portion of the output . For example , output like : :
ceph version 9.0.1-1234kjd ( asdflkj2k3jh234jhg )
Would return : :
9.0.1-1234kjd""" | if not self . executable :
return ''
command = [ self . executable , '--version' ]
out , _ , _ = self . _check ( self . conn , command )
try :
return out . decode ( 'utf-8' ) . split ( ) [ 2 ]
except IndexError :
return '' |
def queue_delete ( self , queue , if_unused = False , if_empty = False ) :
"""Delete queue by name .""" | return self . channel . queue_delete ( queue , if_unused , if_empty ) |
def group ( text , size ) :
"""Group ` ` text ` ` into blocks of ` ` size ` ` .
Example :
> > > group ( " test " , 2)
[ ' te ' , ' st ' ]
Args :
text ( str ) : text to separate
size ( int ) : size of groups to split the text into
Returns :
List of n - sized groups of text
Raises :
ValueError : I... | if size <= 0 :
raise ValueError ( "n must be a positive integer" )
return [ text [ i : i + size ] for i in range ( 0 , len ( text ) , size ) ] |
def ones_matrix_band_part ( rows , cols , num_lower , num_upper , out_shape = None ) :
"""Matrix band part of ones .
Args :
rows : int determining number of rows in output
cols : int
num _ lower : int , maximum distance backward . Negative values indicate
unlimited .
num _ upper : int , maximum distance... | if all ( [ isinstance ( el , int ) for el in [ rows , cols , num_lower , num_upper ] ] ) : # Needed info is constant , so we construct in numpy
if num_lower < 0 :
num_lower = rows - 1
if num_upper < 0 :
num_upper = cols - 1
lower_mask = np . tri ( cols , rows , num_lower ) . T
upper_mask... |
def shift_coordinate_grid ( self , x_shift , y_shift , pixel_unit = False ) :
"""shifts the coordinate system
: param x _ shif : shift in x ( or RA )
: param y _ shift : shift in y ( or DEC )
: param pixel _ unit : bool , if True , units of pixels in input , otherwise RA / DEC
: return : updated data class ... | self . _coords . shift_coordinate_grid ( x_shift , y_shift , pixel_unit = pixel_unit )
self . _x_grid , self . _y_grid = self . _coords . coordinate_grid ( self . nx ) |
def get_hash ( self , msg ) :
''': rettype : string''' | msg = msg . encode ( 'utf-8' , 'replace' )
return hashlib . sha1 ( msg ) . hexdigest ( ) |
def sonos_uri_from_id ( self , item_id ) :
"""Get a uri which can be sent for playing .
Args :
item _ id ( str ) : The unique id of a playable item for this music
service , such as that returned in the metadata from
` get _ metadata ` , eg ` ` spotify : track : 2qs5ZcLByNTctJKbhAZ9JE ` `
Returns :
str :... | # Real Sonos URIs look like this :
# x - sonos - http : tr % 3a92352286 . mp3 ? sid = 2 & flags = 8224 & sn = 4 The
# extension ( . mp3 ) presumably comes from the mime - type returned in a
# MusicService . get _ metadata ( ) result ( though for Spotify the mime - type
# is audio / x - spotify , and there is no extensi... |
def config ( self , show_row_hdrs = True , show_col_hdrs = True , show_col_hdr_in_cell = False , auto_resize = True ) :
"""Override the in - class params :
@ param show _ row _ hdrs : show row headers
@ param show _ col _ hdrs : show column headers
@ param show _ col _ hdr _ in _ cell : embed column header in... | self . show_row_hdrs = show_row_hdrs
self . show_col_hdrs = show_col_hdrs
self . show_col_hdr_in_cell = show_col_hdr_in_cell |
def fcpinfo ( rh ) :
"""Get fcp info and filter by the status .
Input :
Request Handle with the following properties :
function - ' GETVM '
subfunction - ' FCPINFO '
userid - userid of the virtual machine
parms [ ' status ' ] - The status for filter results .
Output :
Request Handle updated with the... | rh . printSysLog ( "Enter changeVM.dedicate" )
parms = [ "-T" , rh . userid ]
hideList = [ ]
results = invokeSMCLI ( rh , "System_WWPN_Query" , parms , hideInLog = hideList )
if results [ 'overallRC' ] != 0 : # SMAPI API failed .
rh . printLn ( "ES" , results [ 'response' ] )
rh . updateResults ( results )
# Us... |
def _generate_main_files_header ( notebook_object , notebook_title = "Notebook Title" , notebook_description = "Notebook Description" ) :
"""Internal function that is used for generation of the ' MainFiles ' notebooks header .
Parameters
notebook _ object : notebook object
Object of " notebook " class where t... | # = = = = = Creation of Header = = = = =
header_temp = HEADER_MAIN_FILES . replace ( "Notebook Title" , notebook_title )
notebook_object [ "cells" ] . append ( nb . v4 . new_markdown_cell ( header_temp ) )
# = = = = = Insertion of the div reserved to the Notebook Description = = = = =
notebook_object [ "cells" ] . appe... |
def readLipd ( usr_path = "" ) :
"""Read LiPD file ( s ) .
Enter a file path , directory path , or leave args blank to trigger gui .
: param str usr _ path : Path to file / directory ( optional )
: return dict _ d : Metadata""" | global cwd , settings , files
if settings [ "verbose" ] :
__disclaimer ( opt = "update" )
start = clock ( )
files [ ".lpd" ] = [ ]
__read ( usr_path , ".lpd" )
_d = __read_lipd_contents ( )
end = clock ( )
logger_benchmark . info ( log_benchmark ( "readLipd" , start , end ) )
return _d |
def show_fibrechannel_interface_info_output_show_fibrechannel_interface_show_fibrechannel_info_port_index ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_fibrechannel_interface_info = ET . Element ( "show_fibrechannel_interface_info" )
config = show_fibrechannel_interface_info
output = ET . SubElement ( show_fibrechannel_interface_info , "output" )
show_fibrechannel_interface = ET . SubElement ( output , "show-fibrechannel-interfa... |
def t_pragma_ID ( self , t ) :
r'[ _ a - zA - Z ] [ _ a - zA - Z0-9 ] *' | # pragma directives
if t . value . upper ( ) in ( 'PUSH' , 'POP' ) :
t . type = t . value . upper ( )
return t |
def GetAllUserSummaries ( ) :
"""Returns a string containing summary info for all GRR users .""" | grr_api = maintenance_utils . InitGRRRootAPI ( )
user_wrappers = sorted ( grr_api . ListGrrUsers ( ) , key = lambda x : x . username )
summaries = [ _Summarize ( w . data ) for w in user_wrappers ]
return "\n\n" . join ( summaries ) |
def add_filter ( self , ftype , func ) :
'''Register a new output filter . Whenever bottle hits a handler output
matching ` ftype ` , ` func ` is applyed to it .''' | if not isinstance ( ftype , type ) :
raise TypeError ( "Expected type object, got %s" % type ( ftype ) )
self . castfilter = [ ( t , f ) for ( t , f ) in self . castfilter if t != ftype ]
self . castfilter . append ( ( ftype , func ) )
self . castfilter . sort ( ) |
def filter ( self , endpoint , params ) :
"""Makes a get request by construction
the path from an endpoint and a dict
with filter query params
e . g .
params = { ' category _ _ in ' : [ 1,2 ] }
response = self . client . filter ( ' / experiences / ' , params )""" | params = self . parse_params ( params )
params = urlencode ( params )
path = '{0}?{1}' . format ( endpoint , params )
return self . get ( path ) |
def long_click ( self , duration = 2.0 ) :
"""Perform the long click action on the UI element ( s ) represented by the UI proxy . If this UI proxy represents a
set of UI elements , the first one in the set is clicked and the anchor point of the UI element is used as the
default one . Similar to click but press ... | try :
duration = float ( duration )
except ValueError :
raise ValueError ( 'Argument `duration` should be <float>. Got {}' . format ( repr ( duration ) ) )
pos_in_percentage = self . get_position ( self . _focus or 'anchor' )
self . poco . pre_action ( 'long_click' , self , pos_in_percentage )
ret = self . poco... |
def requirements ( fname ) :
"""Utility function to create a list of requirements from the output of
the pip freeze command saved in a text file .""" | packages = Setup . read ( fname , fail_silently = True ) . split ( '\n' )
packages = ( p . strip ( ) for p in packages )
packages = ( p for p in packages if p and not p . startswith ( '#' ) )
return list ( packages ) |
def _isnan ( self ) :
"""Return if each value is NaN .""" | if self . _can_hold_na :
return isna ( self )
else : # shouldn ' t reach to this condition by checking hasnans beforehand
values = np . empty ( len ( self ) , dtype = np . bool_ )
values . fill ( False )
return values |
def deactivate ( ) :
"""Deactivate a state in this thread .""" | if hasattr ( _mode , "current_state" ) :
del _mode . current_state
if hasattr ( _mode , "schema" ) :
del _mode . schema
for k in connections :
con = connections [ k ]
if hasattr ( con , 'reset_schema' ) :
con . reset_schema ( ) |
def get_enabled ( ) :
'''Return which jails are set to be run
CLI Example :
. . code - block : : bash
salt ' * ' jail . get _ enabled''' | ret = [ ]
for rconf in ( '/etc/rc.conf' , '/etc/rc.conf.local' ) :
if os . access ( rconf , os . R_OK ) :
with salt . utils . files . fopen ( rconf , 'r' ) as _fp :
for line in _fp :
line = salt . utils . stringutils . to_unicode ( line )
if not line . strip ( ) :... |
async def _discard ( self , path , * , recurse = None , separator = None , cas = None ) :
"""Deletes the Key""" | path = "/v1/kv/%s" % path
response = await self . _api . delete ( path , params = { "cas" : cas , "recurse" : recurse , "separator" : separator } )
return response |
def getkey ( ctx , pubkey ) :
"""Obtain private key in WIF format""" | click . echo ( ctx . bitshares . wallet . getPrivateKeyForPublicKey ( pubkey ) ) |
def get_node_network_state ( self , node_address : Address ) :
"""Returns the currently network status of ` node _ address ` .""" | return views . get_node_network_status ( chain_state = views . state_from_raiden ( self . raiden ) , node_address = node_address , ) |
def update_keyboard_mapping ( conn , e ) :
"""Whenever the keyboard mapping is changed , this function needs to be called
to update xpybutil ' s internal representing of the current keysym table .
Indeed , xpybutil will do this for you automatically .
Moreover , if something is changed that affects the curren... | global __kbmap , __keysmods
newmap = get_keyboard_mapping ( conn ) . reply ( )
if e is None :
__kbmap = newmap
__keysmods = get_keys_to_mods ( conn )
return
if e . request == xproto . Mapping . Keyboard :
changes = { }
for kc in range ( * get_min_max_keycode ( conn ) ) :
knew = get_keysym ( ... |
def cable_from_file ( filename ) :
"""Returns a cable from the provided file .
` filename `
An absolute path to the cable file .""" | html = codecs . open ( filename , 'rb' , 'utf-8' ) . read ( )
return cable_from_html ( html , reader . reference_id_from_filename ( filename ) ) |
def lin_moma2 ( self , objective , wt_obj ) :
"""Find the smallest redistribution vector using a linear objective .
The change in flux distribution is mimimized by minimizing the sum
of the absolute values of the differences of wild type FBA solution
and the knockout strain flux solution .
Creates the const... | reactions = set ( self . _adjustment_reactions ( ) )
z_diff = self . _z_diff
v = self . _v
v_wt = self . _v_wt
with self . constraints ( ) as constr :
for f_reaction in reactions : # Add the constraint that finds the optimal solution , such
# that the difference between the wildtype flux
# is similar to the... |
def contains ( self , location ) :
"""Checks that the provided point is on the sphere .""" | return self . almostEqual ( sum ( [ coord ** 2 for coord in location ] ) , self . radius ** 2 ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.