signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def ernst_table_exporter ( self , cycle , outfname = 'table_out' , sheetname = 'Sheet 1' ) :
"""This routine takes NuGrid data ( model output ) for a given
cycle and writes it into an Excel sheet .
This is one format as requested by Ernst Zinner in June 2013
( through Marco ) . If you want all radioactive iso... | from xlsxwriter . workbook import Workbook
# https : / / xlsxwriter . readthedocs . org / Note : We neex xlswriter . Please meake sure it is installed . Run pip install xlsxwriter to install it using pip . If pip is not installed , install it via easy _ install pip . Depending on the system you are on , you might need ... |
def image_create ( cmptparms , cspace ) :
"""Wrapper for openjpeg library function opj _ image _ create .""" | lst = [ ctypes . c_int , ctypes . POINTER ( ImageComptParmType ) , ctypes . c_int ]
OPENJPEG . opj_image_create . argtypes = lst
OPENJPEG . opj_image_create . restype = ctypes . POINTER ( ImageType )
image = OPENJPEG . opj_image_create ( len ( cmptparms ) , cmptparms , cspace )
return ( image ) |
def draw_line ( self , start , end , color ) :
"""Draw a line with the given color on the screen .
: param start : Start point of the line
: param end : End point of the line
: param color : Color of the line
: type start : tuple
: type end : tuple
: type color : tuple""" | def dist ( p , a , b ) :
return ( abs ( ( b [ 0 ] - a [ 0 ] ) * ( a [ 1 ] - p [ 1 ] ) - ( a [ 0 ] - p [ 0 ] ) * ( b [ 1 ] - a [ 1 ] ) ) / math . sqrt ( ( b [ 0 ] - a [ 0 ] ) ** 2 + ( b [ 1 ] - a [ 1 ] ) ** 2 ) )
points = [ ]
for x in range ( min ( start [ 0 ] , end [ 0 ] ) , max ( start [ 0 ] , end [ 0 ] ) + 1 ) :
... |
def calendars ( self ) :
"""Retrieves calendars for this month""" | today = datetime . today ( )
first_day , last_day = monthrange ( today . year , today . month )
from_dt = datetime ( today . year , today . month , first_day )
to_dt = datetime ( today . year , today . month , last_day )
params = dict ( self . params )
params . update ( { 'lang' : 'en-us' , 'usertz' : get_localzone ( )... |
from math import pi
def calculate_sphere_surface ( radius ) :
"""Function to compute the surface area of a sphere given its radius .
Examples :
> > > calculate _ sphere _ surface ( 10)
1256.6370614359173
> > > calculate _ sphere _ surface ( 15)
2827.4333882308138
> > > calculate _ sphere _ surface ( 20)... | sphere_surface = 4 * pi * radius ** 2
return sphere_surface |
def set_allowed_domains ( self , allowed_domains ) :
"""Set the sequence of allowed domains , or None .""" | if allowed_domains is not None :
allowed_domains = tuple ( allowed_domains )
self . _allowed_domains = allowed_domains |
def get_best_match ( self , options , service_name , api_version = None ) :
"""Given a collection of possible service options , selects the best match .
If no API version is provided , the path to the most recent API version
will be returned . If an API version is provided & there is an exact
match , the path... | if not options :
msg = "No JSON files provided. Please check your " + "configuration/install."
raise NoResourceJSONFound ( msg )
if api_version is None : # Give them the very latest option .
best_version = max ( options . keys ( ) )
return options [ best_version ] [ 0 ] , best_version
# They ' ve provid... |
def google_nest_count ( self , style ) :
"""calculate the nesting count of google doc lists""" | nest_count = 0
if 'margin-left' in style :
nest_count = int ( style [ 'margin-left' ] [ : - 2 ] ) / self . google_list_indent
return nest_count |
def uma_rp_get_rpt ( self , ticket , claim_token = None , claim_token_format = None , pct = None , rpt = None , scope = None , state = None ) :
"""Function to be used by a UMA Requesting Party to get RPT token .
Parameters :
* * * ticket ( str , REQUIRED ) : * * ticket
* * * claim _ token ( str , OPTIONAL ) :... | params = { "oxd_id" : self . oxd_id , "ticket" : ticket }
if claim_token :
params [ "claim_token" ] = claim_token
if claim_token_format :
params [ "claim_token_format" ] = claim_token_format
if pct :
params [ "pct" ] = pct
if rpt :
params [ "rpt" ] = rpt
if scope :
params [ "scope" ] = scope
if stat... |
def instruction_BVS ( self , opcode , ea ) :
"""Tests the state of the V ( overflow ) bit and causes a branch if it is
set . That is , branch if the twos complement result was invalid . When
used after an operation on twos complement binary values , this
instruction will branch if there was an overflow .
so... | if self . V == 1 : # log . info ( " $ % x BVS branch to $ % x , because V = = 1 \ t | % s " % (
# self . program _ counter , ea , self . cfg . mem _ info . get _ shortest ( ea )
self . program_counter . set ( ea ) |
def view_shot ( self , shot ) :
"""View the given shot
: param shot : the shot to view
: type shot : : class : ` jukeboxcore . djadapter . models . Shot `
: returns : None
: rtype : None
: raises : None""" | log . debug ( 'Viewing shot %s' , shot . name )
self . cur_shot = None
self . pages_tabw . setCurrentIndex ( 3 )
self . shot_name_le . setText ( shot . name )
self . shot_prj_le . setText ( shot . project . name )
self . shot_seq_le . setText ( shot . sequence . name )
self . shot_start_sb . setValue ( shot . startfram... |
def run_from_argv ( self , argv ) :
"""Changes the option _ list to use the options from the wrapped command .
Adds schema parameter to specify which schema will be used when
executing the wrapped command .""" | # load the command object .
try :
app_name = get_commands ( ) [ argv [ 2 ] ]
except KeyError :
raise CommandError ( "Unknown command: %r" % argv [ 2 ] )
if isinstance ( app_name , BaseCommand ) : # if the command is already loaded , use it directly .
klass = app_name
else :
klass = load_command_class ( ... |
def _guess_package ( self , path ) :
"""Used in execute _ codegen to actually invoke the compiler with the proper arguments , and in
_ sources _ to _ be _ generated to declare what the generated files will be .""" | supported_prefixes = ( 'com' , 'org' , 'net' , )
package = ''
slash = path . rfind ( os . path . sep )
prefix_with_slash = max ( path . rfind ( os . path . join ( '' , prefix , '' ) ) for prefix in supported_prefixes )
if prefix_with_slash < 0 :
package = path [ : slash ]
elif prefix_with_slash >= 0 :
package =... |
def _conflict_bail ( VC_err , version ) :
"""Setuptools was imported prior to invocation , so it is
unsafe to unload it . Bail out .""" | conflict_tmpl = textwrap . dedent ( """
The required version of setuptools (>={version}) is not available,
and can't be installed while this script is running. Please
install a more recent version first, using
'easy_install -U setuptools'.
(Currently using {VC_err.args[0]!r})
... |
def set_alias ( alias , ** kwargs ) :
"""Set a path alias .
Arguments :
alias - - The alias specification
entry - - The entry to alias it to
category - - The category to alias it to
url - - The external URL to alias it to""" | spec = alias . split ( )
path = spec [ 0 ]
values = { ** kwargs , 'path' : path }
if len ( spec ) > 1 :
values [ 'template' ] = spec [ 1 ]
record = model . PathAlias . get ( path = path )
if record :
record . set ( ** values )
else :
record = model . PathAlias ( ** values )
orm . commit ( )
return record |
def iter_followers ( self , first_user_id = None ) :
"""获取所有的用户openid列表
详情请参考
https : / / mp . weixin . qq . com / wiki ? t = resource / res _ main & id = mp1421140840
: return : 返回一个迭代器 , 可以用for进行循环 , 得到openid
使用示例 : :
from wechatpy import WeChatClient
client = WeChatClient ( ' appid ' , ' secret ' )
... | while True :
follower_data = self . get_followers ( first_user_id )
first_user_id = follower_data [ "next_openid" ]
# 微信有个bug ( 或者叫feature ) , 没有下一页 , 也返回next _ openid这个字段
# 所以要通过total _ count和data的长度比较判断 ( 比较麻烦 , 并且不稳定 )
# 或者获得结果前先判断data是否存在
if 'data' not in follower_data :
return
f... |
def create_many ( self , records ) :
"""Create a list of new instances of the related model .
: param records : instances attributes
: type records : list
: rtype : list""" | instances = [ ]
for record in records :
instances . append ( self . create ( ** record ) )
return instances |
def exec_command ( self , command , bufsize = - 1 , check_status = True ) :
"""Execute a command on the SSH server while preserving underling
agent forwarding and sudo privileges .
https : / / github . com / paramiko / paramiko / blob / 1.8 / paramiko / client . py # L348
: param command : the command to exec... | channel = self . transport . open_session ( )
if self . forward_agent :
AgentRequestHandler ( channel )
if self . sudoable :
channel . get_pty ( )
channel . exec_command ( command )
if check_status and channel . recv_exit_status ( ) != 0 :
raise RuntimeError ( "Command execution error: {}" . format ( comman... |
def reduce_opacity ( img , opacity ) :
"""Returns an image with reduced opacity .""" | assert opacity >= 0 and opacity <= 1
if img . mode != 'RGBA' :
img = img . convert ( 'RGBA' )
else :
img = img . copy ( )
alpha = img . split ( ) [ 3 ]
alpha = ImageEnhance . Brightness ( alpha ) . enhance ( opacity )
img . putalpha ( alpha )
return img |
def quaternion_conjugate ( quaternion ) :
"""Return conjugate of quaternion .
> > > q0 = random _ quaternion ( )
> > > q1 = quaternion _ conjugate ( q0)
> > > q1[0 ] = = q0[0 ] and all ( q1[1 : ] = = - q0[1 : ] )
True""" | q = np . array ( quaternion , dtype = np . float64 , copy = True )
np . negative ( q [ 1 : ] , q [ 1 : ] )
return q |
def get_master ( self , host , port , sentinel_port , sentinel_name ) :
""": param host : Redis host to send request
: param port : Redis port to send request
: param sentinel _ port : sentinel _ port optional
: param sentinel _ name : sentinel _ name optional
: return : master ip and port""" | if sentinel_port and sentinel_name :
master = Sentinel ( [ ( host , sentinel_port ) ] , socket_timeout = 1 ) . discover_master ( sentinel_name )
return master
return host , port |
def get_object_id ( self , datum ) :
"""Identifier of the role assignment .""" | # Role assignment doesn ' t have identifier so one will be created
# from the identifier of scope , user and role . This will guaranty the
# unicity .
scope_id = ""
if "project" in datum . scope :
scope_id = datum . scope [ "project" ] [ "id" ]
elif "domain" in datum . scope :
scope_id = datum . scope [ "domain... |
def warn ( filepath , expected ) :
"""Raise warning .
Parameters
filepath : path - like
Given filepath .
expected : string
Expected file suffix .""" | filepath = pathlib . Path ( filepath )
message = "file {0} has type {1} (expected {2})" . format ( filepath , filepath . suffix , expected )
warnings . warn ( message , WrongFileTypeWarning ) |
def defgate ( self , name , matrix , parameters = None ) :
"""Define a new static gate .
. . note : :
The matrix elements along each axis are ordered by bitstring . For two qubits the order
is ` ` 00 , 01 , 10 , 11 ` ` , where the the bits * * are ordered in reverse * * by the qubit index ,
i . e . , for qu... | return self . inst ( DefGate ( name , matrix , parameters ) ) |
def new ( self ) : # type : ( ) - > None
'''Create a new Rock Ridge Child Link record .
Parameters :
None .
Returns :
Nothing .''' | if self . _initialized :
raise pycdlibexception . PyCdlibInternalError ( 'CL record already initialized!' )
self . child_log_block_num = 0
# This gets set later
self . _initialized = True |
async def get_alarms ( ) :
"""Get alarms and timers from GH .""" | async with aiohttp . ClientSession ( ) as session :
ghlocalapi = Alarms ( LOOP , session , IPADDRESS )
await ghlocalapi . get_alarms ( )
print ( "Alarms:" , ghlocalapi . alarms ) |
def _access_token ( self , request : Request = None , page_id : Text = '' ) :
"""Guess the access token for that specific request .""" | if not page_id :
msg = request . message
# type : FacebookMessage
page_id = msg . get_page_id ( )
page = self . settings ( )
if page [ 'page_id' ] == page_id :
return page [ 'page_token' ]
raise PlatformOperationError ( 'Trying to get access token of the ' 'page "{}", which is not configured.' . format ... |
def current_api_key ( ) :
"""Determines the API key for the current request .
Returns :
The ApiKey instance .""" | if app . config . get ( 'IGNORE_AUTH' ) :
return models . ApiKey ( id = 'anonymous_superuser' , secret = '' , superuser = True )
ops = _get_api_key_ops ( )
api_key = ops . get ( )
logging . debug ( 'Authenticated as API key=%r' , api_key . id )
return api_key |
def get_meter ( self , site , start , end , point_type = 'Green_Button_Meter' , var = "meter" , agg = 'MEAN' , window = '24h' , aligned = True , return_names = True ) :
"""Get meter data from MDAL .
Parameters
site : str
Building name .
start : str
Start date - ' YYYY - MM - DDTHH : MM : SSZ '
end : str... | # Convert time to UTC
start = self . convert_to_utc ( start )
end = self . convert_to_utc ( end )
request = self . compose_MDAL_dic ( point_type = point_type , site = site , start = start , end = end , var = var , agg = agg , window = window , aligned = aligned )
resp = self . m . query ( request )
if return_names :
... |
def _makeini ( self , w , v ) :
"""C initializer string for a wire with a given value .""" | pieces = [ ]
for n in range ( self . _limbs ( w ) ) :
pieces . append ( hex ( v & ( ( 1 << 64 ) - 1 ) ) )
v >>= 64
return ',' . join ( pieces ) . join ( '{}' ) |
def save ( self , * args , ** kwargs ) :
"""call synchronizer " after _ external _ layer _ saved " method
for any additional operation that must be executed after save""" | after_save = kwargs . pop ( 'after_save' , True )
super ( LayerExternal , self ) . save ( * args , ** kwargs )
# call after _ external _ layer _ saved method of synchronizer
if after_save :
try :
synchronizer = self . synchronizer
except ImproperlyConfigured :
pass
else :
if synchron... |
def get_blob ( self , repository_id , sha1 , project = None , download = None , file_name = None , resolve_lfs = None ) :
"""GetBlob .
Get a single blob .
: param str repository _ id : The name or ID of the repository .
: param str sha1 : SHA1 hash of the file . You can get the SHA1 of a file using the " Git ... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if repository_id is not None :
route_values [ 'repositoryId' ] = self . _serialize . url ( 'repository_id' , repository_id , 'str' )
if sha1 is not None :
route_values [ 'sha1' ] ... |
def AddArguments ( cls , argument_group ) :
"""Adds command line arguments to an argument group .
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports .
Args :
argument _ group ( argparse . _ ArgumentGroup | argparse . Argument... | argument_group . add_argument ( '--disable_zeromq' , '--disable-zeromq' , action = 'store_false' , dest = 'use_zeromq' , default = True , help = ( 'Disable queueing using ZeroMQ. A Multiprocessing queue will be ' 'used instead.' ) ) |
def find_day_by_offset ( year , month , offset ) :
"""Get the month day based on date and offset
: param year : date year
: type year : int
: param month : date month
: type month : int
: param offset : offset in day to compute ( usually negative )
: type offset : int
: return : day number in the mont... | ( _ , days_in_month ) = calendar . monthrange ( year , month )
if offset >= 0 :
return min ( offset , days_in_month )
return max ( 1 , days_in_month + offset + 1 ) |
def deserialize_from_http_generics ( cls , body_bytes , headers ) : # type : ( Optional [ Union [ AnyStr , IO ] ] , Mapping ) - > Any
"""Deserialize from HTTP response .
Use bytes and headers to NOT use any requests / aiohttp or whatever
specific implementation .
Headers will tested for " content - type " """ | # Try to use content - type from headers if available
content_type = None
if 'content-type' in headers :
content_type = headers [ 'content-type' ] . split ( ";" ) [ 0 ] . strip ( ) . lower ( )
# Ouch , this server did not declare what it sent . . .
# Let ' s guess it ' s JSON . . .
# Also , since Autorest was consi... |
def remove_id ( self , key ) :
"""Suppress acces with id = key""" | self . infos . pop ( key , "" )
new_l = [ a for a in self if not ( a . Id == key ) ]
list . __init__ ( self , new_l ) |
def apply_host_template ( resource_root , name , cluster_name , host_ids , start_roles ) :
"""Apply a host template identified by name on the specified hosts and
optionally start them .
@ param resource _ root : The root Resource object .
@ param name : Host template name .
@ param cluster _ name : Cluster ... | host_refs = [ ]
for host_id in host_ids :
host_refs . append ( ApiHostRef ( resource_root , host_id ) )
params = { "startRoles" : start_roles }
return call ( resource_root . post , APPLY_HOST_TEMPLATE_PATH % ( cluster_name , name ) , ApiCommand , data = host_refs , params = params , api_version = 3 ) |
def kill ( self , name ) : # type : ( str ) - > None
"""Kills the given component
: param name : Name of the component to kill
: raise ValueError : Invalid component name""" | if not name :
raise ValueError ( "Name can't be None or empty" )
with self . __instances_lock :
try : # Running instance
stored_instance = self . __instances . pop ( name )
# Store the reference to the factory context
factory_context = stored_instance . context . factory_context
... |
def exit_interpreter ( self ) :
"""Exit interpreter""" | self . interpreter . exit_flag = True
if self . multithreaded :
self . interpreter . stdin_write . write ( to_binary_string ( '\n' ) )
self . interpreter . restore_stds ( ) |
def _runMainLoop ( self , rootJob ) :
"""Runs the main loop with the given job .
: param toil . job . Job rootJob : The root job for the workflow .
: rtype : Any""" | logProcessContext ( self . config )
with RealtimeLogger ( self . _batchSystem , level = self . options . logLevel if self . options . realTimeLogging else None ) : # FIXME : common should not import from leader
from toil . leader import Leader
return Leader ( config = self . config , batchSystem = self . _batch... |
def classificationAccuracyVsNoise ( sp , inputVectors , noiseLevelList ) :
"""Evaluate whether the SP output is classifiable , with varying amount of noise
@ param sp a spatial pooler instance
@ param inputVectors ( list ) list of input SDRs
@ param noiseLevelList ( list ) list of noise levels
: return :""" | numInputVector , inputSize = inputVectors . shape
if sp is None :
targetOutputColumns = copy . deepcopy ( inputVectors )
else :
columnNumber = np . prod ( sp . getColumnDimensions ( ) )
# calculate target output given the uncorrupted input vectors
targetOutputColumns = np . zeros ( ( numInputVector , co... |
def version ( family = 'ipv4' ) :
'''Return version from iptables - - version
CLI Example :
. . code - block : : bash
salt ' * ' iptables . version
IPv6:
salt ' * ' iptables . version family = ipv6''' | cmd = '{0} --version' . format ( _iptables_cmd ( family ) )
out = __salt__ [ 'cmd.run' ] ( cmd ) . split ( )
return out [ 1 ] |
def hide ( input_image_file , img_enc , secret_message = None , secret_file = None , img_format = None , ) :
"""Hide a message ( string ) in an image .""" | from zlib import compress
from base64 import b64encode
if secret_file != None :
with open ( secret_file , "r" ) as f :
secret_message = f . read ( )
try :
text = compress ( b64encode ( bytes ( secret_message , "utf-8" ) ) )
except :
text = compress ( b64encode ( secret_message ) )
img = tools . open... |
def delete_course ( self , courseid ) :
"""Erase all course data""" | # Wipes the course ( delete database )
self . wipe_course ( courseid )
# Deletes the course from the factory ( entire folder )
self . course_factory . delete_course ( courseid )
# Removes backup
filepath = os . path . join ( self . backup_dir , courseid )
if os . path . exists ( os . path . dirname ( filepath ) ) :
... |
def get_locale ( ) :
'''Get the current system locale
CLI Example :
. . code - block : : bash
salt ' * ' locale . get _ locale''' | ret = ''
lc_ctl = salt . utils . systemd . booted ( __context__ )
# localectl on SLE12 is installed but the integration is still broken in latest SP3 due to
# config is rewritten by by many % post installation hooks in the older packages .
# If you use it - - you will break your config . This is not the case in SLE15 a... |
def citingArticles ( self , uid , count = 100 , offset = 1 , editions = None , timeSpan = None , retrieveParameters = None ) :
"""The citingArticles operation finds citing articles for the article
specified by unique identifier . You may specify only one identifier per
request . Web of Science Core Collection (... | return self . _search . service . citingArticles ( databaseId = 'WOS' , uid = uid , editions = editions , timeSpan = timeSpan , queryLanguage = 'en' , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) ) |
def get_access_information ( self , code , # pylint : disable = W0221
update_session = True ) :
"""Return the access information for an OAuth2 authorization grant .
: param code : the code received in the request from the OAuth2 server
: param update _ session : Update the current session with the retrieved
t... | retval = super ( AuthenticatedReddit , self ) . get_access_information ( code )
if update_session :
self . set_access_credentials ( ** retval )
return retval |
def authors ( self ) :
"""A list of scopus _ api . _ ScopusAuthor objects .""" | authors = self . xml . find ( 'authors' , ns )
try :
return [ _ScopusAuthor ( author ) for author in authors ]
except TypeError :
return None |
def _generate_replacement ( interface_number , segment_number ) :
"""This will generate replacement string for
{ port0 } = > { port9}
{ segment0 } = > { segment9}""" | replacements = { }
for i in range ( 0 , 9 ) :
replacements [ "port" + str ( i ) ] = interface_number + i
replacements [ "segment" + str ( i ) ] = segment_number + i
return replacements |
def GET_query ( self , req_hook , req_args ) :
'''Generic GET query method''' | # GET request methods only require sessionTokens
headers = { 'content-type' : 'application/json' , 'sessionToken' : self . __session__ }
# HTTP GET query method using requests module
try :
if req_args is None :
response = requests . get ( self . __url__ + req_hook , headers = headers , verify = True )
e... |
def full_parent_name ( self ) :
"""Retrieves the fully qualified parent command name .
This the base command name required to execute it . For example ,
in ` ` ? one two three ` ` the parent name would be ` ` one two ` ` .""" | entries = [ ]
command = self
while command . parent is not None :
command = command . parent
entries . append ( command . name )
return ' ' . join ( reversed ( entries ) ) |
def get_assignments ( self , gradebook_id = '' , simple = False , max_points = True , avg_stats = False , grading_stats = False ) :
"""Get assignments for a gradebook .
Return list of assignments for a given gradebook ,
specified by a py : attribute : : gradebook _ id . You can control
if additional parameter... | # These are parameters required for the remote API call , so
# there aren ' t too many arguments
# pylint : disable = too - many - arguments
params = dict ( includeMaxPoints = json . dumps ( max_points ) , includeAvgStats = json . dumps ( avg_stats ) , includeGradingStats = json . dumps ( grading_stats ) )
assignments ... |
def lonlat_to_healpix ( self , lon , lat , return_offsets = False ) :
"""Convert longitudes / latitudes to HEALPix indices ( optionally with offsets )
Parameters
lon , lat : : class : ` ~ astropy . units . Quantity `
The longitude and latitude values as : class : ` ~ astropy . units . Quantity ` instances
w... | return lonlat_to_healpix ( lon , lat , self . nside , return_offsets = return_offsets , order = self . order ) |
def restore ( self ) :
"""Restore signal handlers to their original settings .""" | signal . signal ( signal . SIGINT , self . original_sigint )
signal . signal ( signal . SIGTERM , self . original_sigterm )
if os . name == 'nt' :
signal . signal ( signal . SIGBREAK , self . original_sigbreak ) |
def list_file ( self , commit , path , recursive = False ) :
"""Lists the files in a directory .
Params :
* commit : A tuple , string , or Commit object representing the commit .
* path : The path to the directory .
* recursive : If True , continue listing the files for sub - directories .""" | req = proto . ListFileRequest ( file = proto . File ( commit = commit_from ( commit ) , path = path ) )
res = self . stub . ListFile ( req , metadata = self . metadata )
file_infos = res . file_info
if recursive :
dirs = [ f for f in file_infos if f . file_type == proto . DIR ]
files = [ f for f in file_infos i... |
def make_payload ( base , method , params ) :
"""Build Betfair JSON - RPC payload .
: param str base : Betfair base ( " Sports " or " Account " )
: param str method : Betfair endpoint
: param dict params : Request parameters""" | payload = { 'jsonrpc' : '2.0' , 'method' : '{base}APING/v1.0/{method}' . format ( ** locals ( ) ) , 'params' : utils . serialize_dict ( params ) , 'id' : 1 , }
return payload |
def show_bokehjs ( bokehjs_action , develop = False ) :
'''Print a useful report after setuptools output describing where and how
BokehJS is installed .
Args :
bokehjs _ action ( str ) : one of ' built ' , ' installed ' , or ' packaged '
how ( or if ) BokehJS was installed into the python source tree
deve... | print ( )
if develop :
print ( "Installed Bokeh for DEVELOPMENT:" )
else :
print ( "Installed Bokeh:" )
if bokehjs_action in [ 'built' , 'installed' ] :
print ( " - using %s built BokehJS from bokehjs/build\n" % ( bright ( yellow ( "NEWLY" ) ) if bokehjs_action == 'built' else bright ( yellow ( "PREVIOUSLY... |
def handle_error ( self , error = None ) :
"""Trap for TCPServer errors , otherwise continue .""" | if _debug :
TCPServerActor . _debug ( "handle_error %r" , error )
# pass along to the director
if error is not None :
self . director . actor_error ( self , error )
else :
TCPServer . handle_error ( self ) |
def main ( argv = None ) :
"""Entry point
: param argv : Script arguments ( None for sys . argv )
: return : An exit code or None""" | # Parse arguments
parser = argparse . ArgumentParser ( prog = "pelix.shell.console" , parents = [ make_common_parser ( ) ] , description = "Pelix Shell Console" , )
# Parse arguments
args = parser . parse_args ( argv )
# Handle arguments
init = handle_common_arguments ( args )
# Set the initial bundles
bundles = [ "pel... |
def write ( self , features = None , outfile = None , format = 0 , is_leaf_fn = None , format_root_node = False , dist_formatter = None , support_formatter = None , name_formatter = None ) :
"""Returns the newick representation of current node . Several
arguments control the way in which extra data is shown for
... | nw = write_newick ( self , features = features , format = format , is_leaf_fn = is_leaf_fn , format_root_node = format_root_node , dist_formatter = dist_formatter , support_formatter = support_formatter , name_formatter = name_formatter )
if outfile is not None :
with open ( outfile , "w" ) as OUT :
OUT . w... |
def wait ( rh ) :
"""Wait for the virtual machine to go into the specified state .
Input :
Request Handle with the following properties :
function - ' POWERVM '
subfunction - ' WAIT '
userid - userid of the virtual machine
parms [ ' desiredState ' ] - Desired state
parms [ ' maxQueries ' ] - Maximum n... | rh . printSysLog ( "Enter powerVM.wait, userid: " + rh . userid )
if ( rh . parms [ 'desiredState' ] == 'off' or rh . parms [ 'desiredState' ] == 'on' ) :
results = waitForVMState ( rh , rh . userid , rh . parms [ 'desiredState' ] , maxQueries = rh . parms [ 'maxQueries' ] , sleepSecs = rh . parms [ 'poll' ] )
else... |
def filter ( self ) : # noqa A001
"""Filter tag ' s children .""" | return [ tag for tag in self . get_contents ( self . tag ) if not self . is_navigable_string ( tag ) and self . match ( tag ) ] |
def build_output_map ( protomap , get_tensor_by_name ) :
"""Builds a map of tensors from ` protomap ` using ` get _ tensor _ by _ name ` .
Args :
protomap : A proto map < string , TensorInfo > .
get _ tensor _ by _ name : A lambda that receives a tensor name and returns a
Tensor instance .
Returns :
A m... | def get_output_from_tensor_info ( tensor_info ) :
encoding = tensor_info . WhichOneof ( "encoding" )
if encoding == "name" :
return get_tensor_by_name ( tensor_info . name )
elif encoding == "coo_sparse" :
return tf . SparseTensor ( get_tensor_by_name ( tensor_info . coo_sparse . indices_ten... |
def verify_request ( self ) :
"""Verify LTI request
: raises : LTIException if request validation failed""" | request = self . lti_kwargs [ 'app' ] . current_request
if request . method == 'POST' : # Chalice expects JSON and does not nativly support forms data in
# a post body . The below is copied from the parsing of query
# strings as implimented in match _ route of Chalice local . py
parsed_url = request . raw_body . de... |
def update_font ( self ) :
"""Update font from Preferences""" | font = self . get_plugin_font ( )
for client in self . clients :
client . set_font ( font ) |
def project_activity ( index , start , end ) :
"""Compute the metrics for the project activity section of the enriched
git index .
Returns a dictionary containing a " metric " key . This key contains the
metrics for this section .
: param index : index object
: param start : start date to get the data fro... | results = { "metrics" : [ Commits ( index , start , end ) , Authors ( index , start , end ) ] }
return results |
def _update_event ( self , event_index , event_state , event_type , event_value , proc_list , proc_desc , peak_time ) :
"""Update an event in the list""" | if event_state == "OK" or event_state == "CAREFUL" : # Reset the automatic process sort key
self . reset_process_sort ( )
# Set the end of the events
endtime = time . mktime ( datetime . now ( ) . timetuple ( ) )
if endtime - self . events_list [ event_index ] [ 0 ] > peak_time : # If event is > peak _ ... |
def update_cache ( self ) :
"""Reset the lal cache . This can be used to update the cache if the
result may change due to more files being added to the filesystem ,
for example .""" | cache = locations_to_cache ( self . frame_src , latest = True )
stream = lalframe . FrStreamCacheOpen ( cache )
self . stream = stream |
def get ( self , model , ** spec ) :
"""get a single model instance by handle
: param model : model
: param handle : instance handle
: return :""" | handles = self . __find_handles ( model , ** spec )
if len ( handles ) > 1 :
raise MultipleObjectsReturned ( )
if not handles :
raise ObjectDoesNotExist ( )
return self . get_instance ( model , handles [ 0 ] ) |
def post ( self , request ) :
"""As per : rfc : ` 3.2 ` the token endpoint * only * supports POST requests .""" | if constants . ENFORCE_SECURE and not request . is_secure ( ) :
return self . error_response ( { 'error' : 'invalid_request' , 'error_description' : _ ( "A secure connection is required." ) } )
if not 'grant_type' in request . POST :
return self . error_response ( { 'error' : 'invalid_request' , 'error_descript... |
def get_coordination_numbers ( d ) :
"""Helper method to get the coordination number of all sites in the final
structure from a run .
Args :
Run dict generated by VaspToDbTaskDrone .
Returns :
Coordination numbers as a list of dict of [ { " site " : site _ dict ,
" coordination " : number } , . . . ] ."... | structure = Structure . from_dict ( d [ "output" ] [ "crystal" ] )
f = VoronoiNN ( )
cn = [ ]
for i , s in enumerate ( structure . sites ) :
try :
n = f . get_cn ( structure , i )
number = int ( round ( n ) )
cn . append ( { "site" : s . as_dict ( ) , "coordination" : number } )
except E... |
def parse ( line ) :
"""Parse accesslog line to map Python dictionary .
Returned dictionary has following keys :
- time : access time ( datetime ; naive )
- utcoffset : UTC offset of access time ( timedelta )
- host : remote IP address .
- path : HTTP request path , this will be splitted from query .
- ... | m = LOG_FORMAT . match ( line )
if m is None :
return
access = Access . _make ( m . groups ( ) )
entry = { 'host' : access . host , 'path' : access . path , 'query' : access . query , 'method' : access . method , 'protocol' : access . protocol , 'status' : int ( access . status ) }
entry [ 'time' ] = datetime . dat... |
def _compute_projection ( self , X , W ) :
"""Compute the LPP projection matrix
Parameters
X : array _ like , ( n _ samples , n _ features )
The input data
W : array _ like or sparse matrix , ( n _ samples , n _ samples )
The precomputed adjacency matrix
Returns
P : ndarray , ( n _ features , self . n... | # TODO : check W input ; handle sparse case
X = check_array ( X )
D = np . diag ( W . sum ( 1 ) )
L = D - W
evals , evecs = eigh_robust ( np . dot ( X . T , np . dot ( L , X ) ) , np . dot ( X . T , np . dot ( D , X ) ) , eigvals = ( 0 , self . n_components - 1 ) )
return evecs |
def _clean_required_args ( self , url , redirect_uri , client_type ) :
"""Validate and clean the command ' s arguments .
Arguments :
url ( str ) : Client ' s application URL .
redirect _ uri ( str ) : Client application ' s OAuth2 callback URI .
client _ type ( str ) : Client ' s type , indicating whether t... | # Validate URLs
for url_to_validate in ( url , redirect_uri ) :
try :
URLValidator ( ) ( url_to_validate )
except ValidationError :
raise CommandError ( "URLs provided are invalid. Please provide valid application and redirect URLs." )
# Validate and map client type to the appropriate django - o... |
def initQApplication ( ) :
"""Initializes the QtWidgets . QApplication instance . Creates one if it doesn ' t exist .
Sets Argos specific attributes , such as the OrganizationName , so that the application
persistent settings are read / written to the correct settings file / winreg . It is therefore
important... | # PyQtGraph recommends raster graphics system for OS - X .
if 'darwin' in sys . platform :
graphicsSystem = "raster"
# raster , native or opengl
os . environ . setdefault ( 'QT_GRAPHICSSYSTEM' , graphicsSystem )
logger . info ( "Setting QT_GRAPHICSSYSTEM to: {}" . format ( graphicsSystem ) )
app = QtWid... |
def show_label ( self , text , size = None , color = None , font_desc = None ) :
"""display text . unless font _ desc is provided , will use system ' s default font""" | font_desc = pango . FontDescription ( font_desc or _font_desc )
if color :
self . set_color ( color )
if size :
font_desc . set_absolute_size ( size * pango . SCALE )
self . show_layout ( text , font_desc ) |
def _verify_service_agreement_signature ( self , did , agreement_id , service_definition_id , consumer_address , signature , ddo = None ) :
"""Verify service agreement signature .
Verify that the given signature is truly signed by the ` consumer _ address `
and represents this did ' s service agreement . .
: ... | if not ddo :
ddo = self . _asset_resolver . resolve ( did )
service_agreement = ServiceAgreement . from_ddo ( service_definition_id , ddo )
agreement_hash = service_agreement . get_service_agreement_hash ( agreement_id , ddo . asset_id , consumer_address , Web3Provider . get_web3 ( ) . toChecksumAddress ( ddo . pro... |
def bundle_visualization ( self , bundle_id , channel = None ) :
'''Get the bundle visualization .
@ param bundle _ id The ID of the bundle .
@ param channel Optional channel name .''' | url = self . bundle_visualization_url ( bundle_id , channel = channel )
response = self . _get ( url )
return response . content |
def remove_child ( self , child ) :
"""Remove a child widget from this widget .
: param child : Object inheriting : class : ` BaseElement `""" | self . children . remove ( child )
child . parent = None
if self . view and self . view . is_loaded :
self . view . dispatch ( { 'name' : 'remove' , 'selector' : '#' + child . id } ) |
def pave_community ( self ) :
"""Usage :
containment pave _ community""" | settings . project_config . path . mkdir ( )
settings . project_config . base . write_text ( self . context . base_text )
settings . project_config . os_packages . write_text ( "[]" )
settings . project_config . lang_packages . write_text ( "{}" ) |
def installed_packages ( self ) :
""": return : list of installed packages""" | packages = [ ]
CMDLINE = [ sys . executable , "-mpip" , "freeze" ]
try :
for package in subprocess . check_output ( CMDLINE ) . decode ( 'utf-8' ) . splitlines ( ) :
for comparator in [ "==" , ">=" , "<=" , "<" , ">" ] :
if comparator in package : # installed package names usually look like Pill... |
def autofit ( self ) :
"""Return | False | if there is a ` ` < w : tblLayout > ` ` child with ` ` w : type ` `
attribute set to ` ` ' fixed ' ` ` . Otherwise return | True | .""" | tblLayout = self . tblLayout
if tblLayout is None :
return True
return False if tblLayout . type == 'fixed' else True |
def jd2dt ( jd ) :
"""Convert julian date to datetime""" | n = int ( round ( float ( jd ) ) )
a = n + 32044
b = ( 4 * a + 3 ) // 146097
c = a - ( 146097 * b ) // 4
d = ( 4 * c + 3 ) // 1461
e = c - ( 1461 * d ) // 4
m = ( 5 * e + 2 ) // 153
day = e + 1 - ( 153 * m + 2 ) // 5
month = m + 3 - 12 * ( m // 10 )
year = 100 * b + d - 4800 + m / 10
tfrac = 0.5 + float ( jd ) - n
tfra... |
def restore_snapshot ( self , si , logger , session , vm_uuid , resource_fullname , snapshot_name ) :
"""Restores a virtual machine to a snapshot
: param vim . ServiceInstance si : py _ vmomi service instance
: param logger : Logger
: param session : CloudShellAPISession
: type session : cloudshell _ api . ... | vm = self . pyvmomi_service . find_by_uuid ( si , vm_uuid )
logger . info ( "Revert snapshot" )
snapshot = SnapshotRestoreCommand . _get_snapshot ( vm = vm , snapshot_name = snapshot_name )
session . SetResourceLiveStatus ( resource_fullname , "Offline" , "Powered Off" )
task = snapshot . RevertToSnapshot_Task ( )
retu... |
def get_next ( self ) :
"""Return the next set of objects in a list""" | url = self . _get_link ( 'next' )
resource = self . object_type . get_resource_class ( self . client )
resp = resource . perform_api_call ( resource . REST_READ , url )
return List ( resp , self . object_type , self . client ) |
async def update_from_devices ( self ) :
"""Retrieve a list of & devices and values .""" | res = await self . get_json ( URL_DEVICES . format ( self . _url ) )
if res :
self . devices . update_devices ( res )
return True
return False |
def warm ( self , jittering_ratio = 0.2 ) :
"""Progressively load the previous snapshot during the day .
Loading all the snapshots at once can takes a substantial amount of time . This method , if called
periodically during the day will progressively load those snapshots one by one . Because many workers are
... | if self . snapshot_to_load == None :
last_period = self . current_period - dt . timedelta ( days = self . expiration - 1 )
self . compute_refresh_period ( )
self . snapshot_to_load = [ ]
base_filename = "%s/%s_%s_*.dat" % ( self . snapshot_path , self . name , self . expiration )
availables_snapshot... |
def cast ( self , mapping ) :
"""Allocate the scene script a cast of personae for each of its entities .
: param mapping : A dictionary of { Entity , Persona }
: return : The SceneScript object .""" | # See ' citation ' method in
# http : / / docutils . sourceforge . net / docutils / parsers / rst / states . py
for c , p in mapping . items ( ) :
self . doc . note_citation ( c )
self . doc . note_explicit_target ( c , c )
c . persona = p
self . log . debug ( "{0} to be played by {1}" . format ( c [ "n... |
def _remove_trustee ( self , device ) :
'''Remove a trustee from the trust domain .
: param device : MangementRoot object - - device to remove''' | trustee_name = get_device_info ( device ) . name
name_object_map = get_device_names_to_objects ( self . devices )
delete_func = self . _get_delete_trustee_cmd
for truster in self . domain :
if trustee_name in self . domain [ truster ] and truster != trustee_name :
truster_obj = name_object_map [ truster ]
... |
def _convert_and_assert_per_example_weights_compatible ( input_ , per_example_weights , dtype ) :
"""Converts per _ example _ weights to a tensor and validates the shape .""" | per_example_weights = tf . convert_to_tensor ( per_example_weights , name = 'per_example_weights' , dtype = dtype )
if input_ . get_shape ( ) . ndims :
expected_length = input_ . get_shape ( ) . dims [ 0 ]
message = ( 'per_example_weights must have rank 1 and length %s, but was: %s' % ( expected_length , per_ex... |
def _Connect ( host = None , port = None , user = None , password = None , database = None , client_key_path = None , client_cert_path = None , ca_cert_path = None ) :
"""Connect to MySQL and check if server fulfills requirements .""" | connection_args = _GetConnectionArgs ( host = host , port = port , user = user , password = password , database = database , client_key_path = client_key_path , client_cert_path = client_cert_path , ca_cert_path = ca_cert_path )
conn = MySQLdb . Connect ( ** connection_args )
with contextlib . closing ( conn . cursor (... |
def load_config_file ( config_file : str ) -> HmipConfig :
"""Loads the config ini file .
: raises a FileNotFoundError when the config file does not exist .""" | _config = configparser . ConfigParser ( )
with open ( config_file , "r" ) as fl :
_config . read_file ( fl )
logging_filename = _config . get ( "LOGGING" , "FileName" , fallback = "hmip.log" )
if logging_filename == "None" :
logging_filename = None
_hmip_config = HmipConfig ( _config [ "AUTH" ] ... |
def _collect_masters_map ( self , response ) :
'''Collect masters map from the network .
: return :''' | while True :
try :
data , addr = self . _socket . recvfrom ( 0x400 )
if data :
if addr not in response :
response [ addr ] = [ ]
response [ addr ] . append ( data )
else :
break
except Exception as err :
if not response :
... |
def ok ( prompt = 'OK ' , loc = { } , glo = { } , cmd = "" ) :
'''Invoke the peforth interpreter .
An statement : peforth . ok ( prompt = ' OK ' , loc = locals ( ) , glo = globals ( ) , cmd = " " )
is like a breakpoint . The prompt indicates which breakpoint it is if there are
many . Arguments loc ( locals ) ... | if loc or glo :
vm . push ( ( loc , glo , prompt ) )
# parent ' s data
while True :
if cmd == "" :
if vm . tick ( 'accept' ) and not vm . multiple : # Input can be single line ( default ) or
vm . execute ( 'accept' )
# multiple lines . Press Ctrl - D to toggle
cmd... |
def getpreferredencoding ( ) :
"""Determine the proper output encoding for terminal rendering""" | # Borrowed from Invoke
# ( see https : / / github . com / pyinvoke / invoke / blob / 93af29d / invoke / runners . py # L881)
_encoding = locale . getpreferredencoding ( False )
if six . PY2 and not sys . platform == "win32" :
_default_encoding = locale . getdefaultlocale ( ) [ 1 ]
if _default_encoding is not No... |
def binary_thin ( image , strel1 , strel2 ) :
"""Morphologically thin an image
strel1 - the required values of the pixels in order to survive
strel2 - at each pixel , the complement of strel1 if we care about the value""" | hit_or_miss = scind . binary_hit_or_miss ( image , strel1 , strel2 )
return np . logical_and ( image , np . logical_not ( hit_or_miss ) ) |
def read ( fname ) :
"""Return content of specified file""" | path = os . path . join ( SCRIPTDIR , fname )
if PY3 :
f = open ( path , 'r' , encoding = 'utf8' )
else :
f = open ( path , 'r' )
content = f . read ( )
f . close ( )
return content |
def process_forever ( self , timeout = 0.2 ) :
"""Run an infinite loop , processing data from connections .
This method repeatedly calls process _ once .
Arguments :
timeout - - Parameter to pass to process _ once .""" | # This loop should specifically * not * be mutex - locked .
# Otherwise no other thread would ever be able to change
# the shared state of a Reactor object running this function .
log . debug ( "process_forever(timeout=%s)" , timeout )
one = functools . partial ( self . process_once , timeout = timeout )
consume ( infi... |
def link_asset_content_key ( access_token , asset_id , encryptionkey_id , ams_redirected_rest_endpoint ) :
'''Link Media Service Asset and Content Key .
Args :
access _ token ( str ) : A valid Azure authentication token .
asset _ id ( str ) : A Media Service Asset ID .
encryption _ id ( str ) : A Media Serv... | path = '/Assets'
full_path = '' . join ( [ path , "('" , asset_id , "')" , "/$links/ContentKeys" ] )
full_path_encoded = urllib . parse . quote ( full_path , safe = '' )
endpoint = '' . join ( [ ams_rest_endpoint , full_path_encoded ] )
uri = '' . join ( [ ams_redirected_rest_endpoint , 'ContentKeys' , "('" , encryptio... |
def link ( self , family : str , sample : str , analysis_type : str , files : List [ str ] ) :
"""Link FASTQ files for a sample .""" | root_dir = Path ( self . families_dir ) / family / analysis_type / sample / 'fastq'
root_dir . mkdir ( parents = True , exist_ok = True )
for fastq_data in files :
fastq_path = Path ( fastq_data [ 'path' ] )
fastq_name = self . name_file ( lane = fastq_data [ 'lane' ] , flowcell = fastq_data [ 'flowcell' ] , sa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.