signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def send_identity ( self ) :
"""Send the identity of the service .""" | service_name = { 'service_name' : self . messaging . _service_name }
service_name = _json . dumps ( service_name ) . encode ( 'utf8' )
identify_frame = ( b'' , b'IDENT' , _json . dumps ( [ ] ) . encode ( 'utf8' ) , service_name )
# NOTE : Have to do this manually since we built the frame
if self . messaging . _run_cont... |
def find ( self , query = None , limit = None ) :
"""Returns a list of documents in this collection that match a given query""" | results = [ ]
query = query or { }
# TODO : When indexes are implemented , we ' ll need to intelligently hit one of the
# index stores so we don ' t do a full table scan
cursor = self . db . execute ( "select id, data from %s" % self . name )
apply = partial ( self . _apply_query , query )
for match in filter ( apply ,... |
def cosine ( x ) :
'''cosine ( x ) is equivalent to cos ( x ) except that it also works on sparse arrays .''' | # cos ( 0 ) = 1 so no point in keeping these sparse
if sps . issparse ( x ) :
x = x . toarray ( x )
return np . cos ( x ) |
def substring_index ( str , delim , count ) :
"""Returns the substring from string str before count occurrences of the delimiter delim .
If count is positive , everything the left of the final delimiter ( counting from left ) is
returned . If count is negative , every to the right of the final delimiter ( count... | sc = SparkContext . _active_spark_context
return Column ( sc . _jvm . functions . substring_index ( _to_java_column ( str ) , delim , count ) ) |
def connect ( self , frontend = None , commands = None ) :
"""Inject pipes connecting the service to the frontend . Two arguments are
supported : frontend = for messages from the service to the frontend ,
and commands = for messages from the frontend to the service .
The injection should happen before the ser... | if frontend :
self . __pipe_frontend = frontend
self . __send_service_status_to_frontend ( )
if commands :
self . __pipe_commands = commands |
def set_suggested_sort ( self , sort = 'blank' ) :
"""Set ' Suggested Sort ' for the comments of the submission .
Comments can be sorted in one of ( confidence , top , new , hot ,
controversial , old , random , qa , blank ) .
: returns : The json response from the server .""" | url = self . reddit_session . config [ 'suggested_sort' ]
data = { 'id' : self . fullname , 'sort' : sort }
return self . reddit_session . request_json ( url , data = data ) |
def put ( self , pid , record , ** kwargs ) :
"""Replace a record .
Permissions : ` ` update _ permission _ factory ` `
The body should be a JSON object , which will fully replace the current
record metadata .
Procedure description :
# . The ETag is checked .
# . The record is updated by calling the rec... | if request . mimetype not in self . loaders :
raise UnsupportedMediaRESTError ( request . mimetype )
data = self . loaders [ request . mimetype ] ( )
if data is None :
raise InvalidDataRESTError ( )
self . check_etag ( str ( record . revision_id ) )
record . clear ( )
record . update ( data )
record . commit ( ... |
def mayavi_scraper ( block , block_vars , gallery_conf ) :
"""Scrape Mayavi images .
Parameters
block : tuple
A tuple containing the ( label , content , line _ number ) of the block .
block _ vars : dict
Dict of block variables .
gallery _ conf : dict
Contains the configuration of Sphinx - Gallery
R... | from mayavi import mlab
image_path_iterator = block_vars [ 'image_path_iterator' ]
image_paths = list ( )
e = mlab . get_engine ( )
for scene , image_path in zip ( e . scenes , image_path_iterator ) :
mlab . savefig ( image_path , figure = scene )
# make sure the image is not too large
scale_image ( image_p... |
def walk_preorder ( self ) :
"""Depth - first preorder walk over the cursor and its descendants .
Yields cursors .""" | yield self
for child in self . get_children ( ) :
for descendant in child . walk_preorder ( ) :
yield descendant |
def _get_basic_logger ( loggername , log_to_file , logpath ) :
"""Get a logger with our basic configuration done .
: param loggername : Name of logger .
: param log _ to _ file : Boolean , True if this logger should write a file .
: return : Logger""" | logger = logging . getLogger ( loggername )
logger . propagate = False
remove_handlers ( logger )
logger . setLevel ( logging . DEBUG )
logger_config = LOGGING_CONFIG . get ( loggername , DEFAULT_LOGGING_CONFIG )
if TRUNCATE_LOG or logger_config . get ( "truncate_logs" ) . get ( "truncate" ) :
cfilter = ContextFilt... |
def die ( exc : Exception = None , exit_code : int = 1 ) -> None :
"""It is not clear that Python guarantees to exit with a non - zero exit code
( errorlevel in DOS / Windows ) upon an unhandled exception . So this function
produces the usual stack trace then dies with the specified exit code .
See
http : /... | # noqa
if exc :
lines = traceback . format_exception ( None , # etype : ignored
exc , exc . __traceback__ )
# https : / / www . python . org / dev / peps / pep - 3134/
msg = "" . join ( lines )
# Method 1:
# print ( " " . join ( lines ) , file = sys . stderr , flush = True )
# Method 2:
... |
def results ( self ) :
"""Return a list of all the results currently available . This
excludes pending results . Results are returned as a single flat
list , so any repetition structure is lost .
: returns : a list of results""" | rs = [ ]
for k in self . _results . keys ( ) : # filter out pending job ids , which can be anything except dicts
ars = [ res for res in self . _results [ k ] if isinstance ( res , dict ) ]
rs . extend ( ars )
return rs |
def connect ( self , attempts = 20 , delay = 0.5 ) :
"""Connects to a gateway , blocking until a connection is made and bulbs
are found .
Step 1 : send a gateway discovery packet to the broadcast address , wait
until we ' ve received some info about the gateway .
Step 2 : connect to a discovered gateway , w... | # Broadcast discovery packets until we find a gateway .
sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM , socket . IPPROTO_UDP )
with closing ( sock ) :
sock . setsockopt ( socket . SOL_SOCKET , socket . SO_BROADCAST , 1 )
discover_packet = build_packet ( REQ_GATEWAY , ALL_BULBS , ALL_BULBS , ''... |
def html_page_for_render_items ( bundle , docs_json , render_items , title , template = None , template_variables = { } ) :
'''Render an HTML page from a template and Bokeh render items .
Args :
bundle ( tuple ) :
a tuple containing ( bokehjs , bokehcss )
docs _ json ( JSON - like ) :
Serialized Bokeh Doc... | if title is None :
title = DEFAULT_TITLE
bokeh_js , bokeh_css = bundle
json_id = make_id ( )
json = escape ( serialize_json ( docs_json ) , quote = False )
json = wrap_in_script_tag ( json , "application/json" , json_id )
script = wrap_in_script_tag ( script_for_render_items ( json_id , render_items ) )
context = t... |
def getLowerDetectionLimit ( self ) :
"""Returns the Lower Detection Limit ( LDL ) that applies to this
analysis in particular . If no value set or the analysis service
doesn ' t allow manual input of detection limits , returns the value set
by default in the Analysis Service""" | if self . isLowerDetectionLimit ( ) :
result = self . getResult ( )
try : # in this case , the result itself is the LDL .
return float ( result )
except ( TypeError , ValueError ) :
logger . warn ( "The result for the analysis %s is a lower " "detection limit, but not floatable: '%s'. " "Ret... |
def validate_body ( schema ) :
"""Validate the body of incoming requests for a flask view .
An example usage might look like this : :
from snapstore _ schemas import validate _ body
@ validate _ body ( {
' type ' : ' array ' ,
' items ' : {
' type ' : ' object ' ,
' properties ' : {
' snap _ id ' : ... | location = get_callsite_location ( )
def decorator ( fn ) :
validate_schema ( schema )
wrapper = wrap_request ( fn , schema )
record_schemas ( fn , wrapper , location , request_schema = sort_schema ( schema ) )
return wrapper
return decorator |
def _basic_deliver ( self , args , msg ) :
"""notify the client of a consumer message
This method delivers a message to the client , via a consumer .
In the asynchronous message delivery model , the client starts
a consumer using the Consume method , then the server responds
with Deliver methods as and when... | consumer_tag = args . read_shortstr ( )
delivery_tag = args . read_longlong ( )
redelivered = args . read_bit ( )
exchange = args . read_shortstr ( )
routing_key = args . read_shortstr ( )
msg . delivery_info = { 'channel' : self , 'consumer_tag' : consumer_tag , 'delivery_tag' : delivery_tag , 'redelivered' : redelive... |
def get_fieldsets ( self , request , obj = None ) :
"""Fieldsets configuration""" | return [ ( None , { 'fields' : ( 'type' , 'namespace' , 'app_title' , 'object_name' ) } ) , ( _ ( 'Generic' ) , { 'fields' : ( 'config.default_published' , 'config.use_placeholder' , 'config.use_abstract' , 'config.set_author' , 'config.use_related' , ) } ) , ( _ ( 'Layout' ) , { 'fields' : ( 'config.paginate_by' , 'co... |
def get ( self , sid ) :
"""Constructs a EngagementContext
: param sid : Engagement Sid .
: returns : twilio . rest . studio . v1 . flow . engagement . EngagementContext
: rtype : twilio . rest . studio . v1 . flow . engagement . EngagementContext""" | return EngagementContext ( self . _version , flow_sid = self . _solution [ 'flow_sid' ] , sid = sid , ) |
def add_message_event ( proto_message , span , message_event_type , message_id = 1 ) :
"""Adds a MessageEvent to the span based off of the given protobuf
message""" | span . add_time_event ( time_event = time_event . TimeEvent ( datetime . utcnow ( ) , message_event = time_event . MessageEvent ( message_id , type = message_event_type , uncompressed_size_bytes = proto_message . ByteSize ( ) ) ) ) |
def ascending ( self , name ) :
'''Add a descending index for ` ` name ` ` to this index .
: param name : Name to be used in the index''' | self . components . append ( ( name , Index . ASCENDING ) )
return self |
def naturaldelta ( value , months = True ) :
"""Given a timedelta or a number of seconds , return a natural
representation of the amount of time elapsed . This is similar to
` ` naturaltime ` ` , but does not add tense to the result . If ` ` months ` `
is True , then a number of months ( based on 30.5 days ) ... | now = _now ( )
date , delta = date_and_delta ( value )
if date is None :
return value
use_months = months
seconds = abs ( delta . seconds )
days = abs ( delta . days )
years = days // 365
days = days % 365
months = int ( days // 30.5 )
if not years and days < 1 :
if seconds == 0 :
return _ ( "a moment" ... |
def doTranslate ( option , urlOrPaths , serverEndpoint = ServerEndpoint , verbose = Verbose , tikaServerJar = TikaServerJar , responseMimeType = 'text/plain' , services = { 'all' : '/translate/all' } ) :
'''Translate the file from source language to destination language .
: param option :
: param urlOrPaths :
... | paths = getPaths ( urlOrPaths )
return [ doTranslate1 ( option , path , serverEndpoint , verbose , tikaServerJar , responseMimeType , services ) for path in paths ] |
def read ( self , nrml_file , validate = False , simple_fault_spacing = 1.0 , complex_mesh_spacing = 5.0 , mfd_spacing = 0.1 ) :
"""Build the source model from nrml format""" | self . source_file = nrml_file
if validate :
converter = SourceConverter ( 1.0 , simple_fault_spacing , complex_mesh_spacing , mfd_spacing , 10.0 )
converter . fname = nrml_file
root = nrml . read ( nrml_file )
if root [ 'xmlns' ] == 'http://openquake.org/xmlns/nrml/0.4' :
sg_nodes = [ root . sourceModel . ... |
def get_averages ( self ) :
"""Get the broadcast network averages for that day .
Returns a dictionary :
key : network name
value : sub - dictionary with ' viewers ' , ' rating ' , and ' share ' as keys""" | networks = [ unescape_html ( n . string ) for n in self . soup . find_all ( 'td' , width = '77' ) ]
table = self . soup . find_all ( 'td' , style = re . compile ( '^font' ) )
# Each element is a list split as [ rating , share ]
rateshares = [ r . string . split ( '/' ) for r in table [ : 5 ] if r . string ]
viewers = [... |
def set_interrupt ( self , enabled ) :
"""Enable or disable interrupts by setting enabled to True or False .""" | enable_reg = self . _readU8 ( TCS34725_ENABLE )
if enabled :
enable_reg |= TCS34725_ENABLE_AIEN
else :
enable_reg &= ~ TCS34725_ENABLE_AIEN
self . _write8 ( TCS34725_ENABLE , enable_reg )
time . sleep ( 1 ) |
def handle ( self , environ , start_response ) :
"""WSGI handler function .
The transport will serve a request by reading the message and putting
it into an internal buffer . It will then block until another
concurrently running function sends a reply using : py : meth : ` send _ reply ` .
The reply will th... | request = Request ( environ )
request . max_content_length = self . max_content_length
access_control_headers = { 'Access-Control-Allow-Methods' : 'POST' , 'Access-Control-Allow-Origin' : self . allow_origin , 'Access-Control-Allow-Headers' : 'Content-Type, X-Requested-With, Accept, Origin' }
if request . method == 'OP... |
def add_contents_to_zip ( zip_file , path ) :
"""Zip the contents of < path > into < zip _ file > .
: param str | unicode zip _ file : The file name of the zip file
: param str | unicode path : Full path of the directory to zip up""" | path = path . rstrip ( os . sep )
with zipfile . ZipFile ( zip_file , 'a' ) as zf :
for root , dirs , files in os . walk ( path ) :
for file in files :
file_path = os . path . join ( root , file )
zf . write ( file_path , file_path [ len ( path ) + 1 : ] ) |
def listProcessingEras ( self , processing_version = 0 ) :
"""API to list all Processing Eras in DBS .
: param processing _ version : Processing Version ( Optional ) . If provided just this processing _ version will be listed
: type processing _ version : str
: returns : List of dictionaries containing the fo... | try : # processing _ version = processing _ version . replace ( " * " , " % " )
return self . dbsProcEra . listProcessingEras ( processing_version )
except dbsException as de :
dbsExceptionHandler ( de . eCode , de . message , self . logger . exception , de . serverError )
except Exception as ex :
sError = ... |
def from_Track ( track , maxwidth = 80 , tuning = None ) :
"""Convert a mingus . containers . Track object to an ASCII tablature string .
' tuning ' should be set to a StringTuning object or to None to use the
Track ' s tuning ( or alternatively the default if the Track hasn ' t got its
own tuning ) .
' str... | result = [ ]
width = _get_width ( maxwidth )
if not tuning :
tuning = track . get_tuning ( )
lastlen = 0
for bar in track :
r = from_Bar ( bar , width , tuning , collapse = False )
barstart = r [ 1 ] . find ( '||' ) + 2
if ( len ( r [ 0 ] ) + lastlen ) - barstart < maxwidth and result != [ ] :
f... |
def get_corpus ( filename : str ) -> frozenset :
"""Read corpus from file and return a frozenset
: param string filename : file corpus""" | lines = [ ]
with open ( os . path . join ( corpus_path ( ) , filename ) , "r" , encoding = "utf-8-sig" ) as fh :
lines = fh . read ( ) . splitlines ( )
return frozenset ( lines ) |
def _set_desc ( self , v , load = False ) :
"""Setter method for desc , mapped from YANG variable / username / desc ( string )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ desc is considered as a private
method . Backends looking to populate this variable should
... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_dict = { 'length' : [ u'0 .. 64' ] } ) , default = unicode ( "" ) , is_leaf = True , yang_name = "desc" , rest_name = "desc" , parent = self , path_helper = self . _path... |
def _insert_data ( self , name , value , timestamp , interval , config , ** kwargs ) :
'''Helper to insert data into sql .''' | kwargs = { 'name' : name , 'interval' : interval , 'insert_time' : time . time ( ) , 'i_time' : config [ 'i_calc' ] . to_bucket ( timestamp ) , 'value' : value }
if not config [ 'coarse' ] :
kwargs [ 'r_time' ] = config [ 'r_calc' ] . to_bucket ( timestamp )
stmt = self . _table . insert ( ) . values ( ** kwargs )
... |
def generate_safemode_windows ( ) :
"""Produce batch file to run QML in safe - mode
Usage :
$ python - c " import compat ; compat . generate _ safemode _ windows ( ) "
$ run . bat""" | try :
import pyblish
import pyblish_qml
import PyQt5
except ImportError :
return sys . stderr . write ( "Run this in a terminal with access to " "the Pyblish libraries and PyQt5.\n" )
template = r"""@echo off
:: Clear all environment variables
@echo off
if exist ".\backup_env.bat" del ".\b... |
def get_file ( self , name ) :
"""Returns the output file with the specified name , if no output files
match , returns None .""" | files = self . get_output_files ( )
for f in files :
if f . get_name ( ) == name :
return f
return None |
def html ( self , groups = 'all' , template = None , ** context ) :
"""Return an html string of the routes specified by the doc ( ) method
A template can be specified . A list of routes is available under the
' autodoc ' value ( refer to the documentation for the generate ( ) for a
description of available va... | context [ 'autodoc' ] = context [ 'autodoc' ] if 'autodoc' in context else self . generate ( groups = groups )
context [ 'defaults' ] = context [ 'defaults' ] if 'defaults' in context else self . default_props
if template :
return render_template ( template , ** context )
else :
filename = os . path . join ( os... |
def _shade_remaining_missing ( self ) :
"""Helper method to shade any missing labels remaining on the current
page . Not intended for external use .
Note that this will modify the internal _ position attribute and should
therefore only be used once all the ' real ' labels have been drawn .""" | # Sanity check .
if not self . shade_missing :
return
# Run through each missing label left in the current page and shade it .
missing = self . _used . get ( self . page_count , set ( ) )
for position in missing :
self . _position = position
self . _shade_missing_label ( ) |
def compare ( items , params , rank = False ) :
"""Generate a comparison outcome that follows Luce ' s axiom .
This function samples an outcome for the comparison of a subset of items ,
from a model parametrized by ` ` params ` ` . If ` ` rank ` ` is True , it returns a
ranking over the items , otherwise it r... | probs = probabilities ( items , params )
if rank :
return np . random . choice ( items , size = len ( items ) , replace = False , p = probs )
else :
return np . random . choice ( items , p = probs ) |
def handle_log_message ( msg ) : # pylint : disable = useless - return
"""Process an internal log message .""" | msg . gateway . can_log = True
_LOGGER . debug ( 'n:%s c:%s t:%s s:%s p:%s' , msg . node_id , msg . child_id , msg . type , msg . sub_type , msg . payload )
return None |
def _validate_snap_name ( name , snap_name , strict = True , runas = None ) :
'''Validate snapshot name and convert to snapshot ID
: param str name :
Name / ID of VM whose snapshot name is being validated
: param str snap _ name :
Name / ID of snapshot
: param bool strict :
Raise an exception if multipl... | snap_name = salt . utils . data . decode ( snap_name )
# Try to convert snapshot name to an ID without { }
if re . match ( GUID_REGEX , snap_name ) :
return snap_name . strip ( '{}' )
else :
return snapshot_name_to_id ( name , snap_name , strict = strict , runas = runas ) |
def get_tree_size ( path ) :
"""Return total size of all files in directory tree at path .""" | size = 0
try :
for entry in scandir . scandir ( path ) :
if entry . is_symlink ( ) :
pass
elif entry . is_dir ( ) :
size += get_tree_size ( os . path . join ( path , entry . name ) )
else :
size += entry . stat ( ) . st_size
except OSError :
pass
retur... |
def _get_value ( self ) :
"""Return two delegating variables . Each variable should contain
a value attribute with the real value .""" | x , y = self . _point . x , self . _point . y
self . _px , self . _py = self . _item_point . canvas . get_matrix_i2i ( self . _item_point , self . _item_target ) . transform_point ( x , y )
return self . _px , self . _py |
def from_tabledata ( self , value , is_overwrite_table_name = True ) :
"""Set tabular attributes to the writer from | TableData | .
Following attributes are configured :
- : py : attr : ` ~ . table _ name ` .
- : py : attr : ` ~ . headers ` .
- : py : attr : ` ~ . value _ matrix ` .
| TableData | can be c... | self . __clear_preprocess ( )
if is_overwrite_table_name :
self . table_name = value . table_name
self . headers = value . headers
self . value_matrix = value . rows
if not value . has_value_dp_matrix :
return
self . _table_value_dp_matrix = value . value_dp_matrix
self . _column_dp_list = self . _dp_extractor ... |
def make_madry_ngpu ( nb_classes = 10 , input_shape = ( None , 28 , 28 , 1 ) , ** kwargs ) :
"""Create a multi - GPU model similar to Madry et al . ( arXiv : 1706.06083 ) .""" | layers = [ Conv2DnGPU ( 32 , ( 5 , 5 ) , ( 1 , 1 ) , "SAME" ) , ReLU ( ) , MaxPool ( ( 2 , 2 ) , ( 2 , 2 ) , "SAME" ) , Conv2DnGPU ( 64 , ( 5 , 5 ) , ( 1 , 1 ) , "SAME" ) , ReLU ( ) , MaxPool ( ( 2 , 2 ) , ( 2 , 2 ) , "SAME" ) , Flatten ( ) , LinearnGPU ( 1024 ) , ReLU ( ) , LinearnGPU ( nb_classes ) , Softmax ( ) ]
mo... |
def _get_client_secret ( client , service_id ) :
"""Get client secret for service
: param client : Accounts Service API Client
: param service _ id : Service ID
: return : Client secret ( if available )""" | try :
response = client . accounts . services [ service_id ] . secrets . get ( )
except httpclient . HTTPError as exc :
if exc . code == 404 : # If error is a 404 then this means the service _ id is not recognised . Raise this error immediately
msg = ( 'Service {} cannot be found.' . format ( service_id... |
def setMirrorMode ( self , mirror ) :
"""Sets the mirror mode to use in the next operation .
: param mirror : A string object with one of these values : ' ' , ' h ' , ' v ' , ' hv ' . " h " stands for horizontal mirroring , while " v " stands for vertical mirroring . " hv " sets both at the same time .
: rtype ... | assert ( mirror == '' or mirror == 'h' or mirror == 'v' or mirror == 'hv' or mirror == 'vh' ) , 'setMirrorMode: wrong mirror mode, got ' + str ( mirror ) + ' expected one of ["","h","v","hv"]'
# Round up all the coordinates and convert them to int
if mirror == '' :
mirror = 0
elif mirror == 'h' :
mirror = 1
eli... |
def _analyse_status_type ( line ) :
'''Figure out the sections in drbdadm status''' | spaces = _count_spaces_startswith ( line )
if spaces is None :
return ''
switch = { 0 : 'RESOURCE' , 2 : { ' disk:' : 'LOCALDISK' , ' role:' : 'PEERNODE' , ' connection:' : 'PEERNODE' } , 4 : { ' peer-disk:' : 'PEERDISK' } }
ret = switch . get ( spaces , 'UNKNOWN' )
# isinstance ( ret , str ) only works when run di... |
def set_properties ( self , properties ) :
"""Updates the service properties
: param properties : The new properties
: raise TypeError : The argument is not a dictionary""" | if not isinstance ( properties , dict ) :
raise TypeError ( "Waiting for dictionary" )
# Keys that must not be updated
for forbidden_key in OBJECTCLASS , SERVICE_ID :
try :
del properties [ forbidden_key ]
except KeyError :
pass
to_delete = [ ]
for key , value in properties . items ( ) :
... |
def calc_dmgrid ( d , maxloss = 0.05 , dt = 3000. , mindm = 0. , maxdm = 0. ) :
"""Function to calculate the DM values for a given maximum sensitivity loss .
maxloss is sensitivity loss tolerated by dm bin width . dt is assumed pulse width in microsec .""" | # parameters
tsamp = d [ 'inttime' ] * 1e6
# in microsec
k = 8.3
freq = d [ 'freq' ] . mean ( )
# central ( mean ) frequency in GHz
bw = 1e3 * ( d [ 'freq' ] [ - 1 ] - d [ 'freq' ] [ 0 ] )
ch = 1e3 * ( d [ 'freq' ] [ 1 ] - d [ 'freq' ] [ 0 ] )
# channel width in MHz
# width functions and loss factor
dt0 = lambda dm : n... |
def veas2tas ( eas , h ) :
"""Equivalent airspeed to true airspeed""" | rho = vdensity ( h )
tas = eas * np . sqrt ( rho0 / rho )
return tas |
def as_dict ( self ) :
"""Provides a simple though not complete dict serialization of the object ( OMP missing , not all limits are
kept in the dictionary , . . . other things to be checked )
Raise :
` ValueError ` if errors .""" | if self . has_omp :
raise NotImplementedError ( 'as_dict method of QueueAdapter not yet implemented when OpenMP is activated' )
return { '@module' : self . __class__ . __module__ , '@class' : self . __class__ . __name__ , 'priority' : self . priority , 'hardware' : self . hw . as_dict ( ) , 'queue' : { 'qtype' : se... |
def run_interrupted ( self ) :
"""Runs custodian in a interuppted mode , which sets up and
validates jobs but doesn ' t run the executable
Returns :
number of remaining jobs
Raises :
ValidationError : if a job fails validation
ReturnCodeError : if the process has a return code different from 0
NonReco... | start = datetime . datetime . now ( )
try :
cwd = os . getcwd ( )
v = sys . version . replace ( "\n" , " " )
logger . info ( "Custodian started in singleshot mode at {} in {}." . format ( start , cwd ) )
logger . info ( "Custodian running on Python version {}" . format ( v ) )
# load run log
if ... |
def _parse_dict ( cls , value ) :
"""Represents value as a dict .
: param value :
: rtype : dict""" | separator = '='
result = { }
for line in cls . _parse_list ( value ) :
key , sep , val = line . partition ( separator )
if sep != separator :
raise DistutilsOptionError ( 'Unable to parse option value to dict: %s' % value )
result [ key . strip ( ) ] = val . strip ( )
return result |
def load_etext ( etextno , refresh_cache = False , mirror = None , prefer_ascii = False ) :
"""Returns a unicode representation of the full body of a Project Gutenberg
text . After making an initial remote call to Project Gutenberg ' s servers ,
the text is persisted locally .""" | etextno = validate_etextno ( etextno )
cached = os . path . join ( _TEXT_CACHE , '{}.txt.gz' . format ( etextno ) )
if refresh_cache :
remove ( cached )
if not os . path . exists ( cached ) :
makedirs ( os . path . dirname ( cached ) )
download_uri = _format_download_uri ( etextno , mirror , prefer_ascii )
... |
def make_template_name ( self , model_type , sourcekey ) :
"""Make the name of a template file for particular component
Parameters
model _ type : str
Type of model to use for this component
sourcekey : str
Key to identify this component
Returns filename or None if component does not require a template f... | format_dict = self . __dict__ . copy ( )
format_dict [ 'sourcekey' ] = sourcekey
if model_type == 'IsoSource' :
return self . _name_factory . spectral_template ( ** format_dict )
elif model_type in [ 'MapCubeSource' , 'SpatialMap' ] :
return self . _name_factory . diffuse_template ( ** format_dict )
else :
... |
def set_timeout ( self , visibility_timeout ) :
"""Set the visibility timeout for the queue .
: type visibility _ timeout : int
: param visibility _ timeout : The desired timeout in seconds""" | retval = self . set_attribute ( 'VisibilityTimeout' , visibility_timeout )
if retval :
self . visibility_timeout = visibility_timeout
return retval |
def register_library_type ( name , type_ ) :
"""Register a Arctic Library Type handler""" | if name in LIBRARY_TYPES :
raise ArcticException ( "Library %s already registered as %s" % ( name , LIBRARY_TYPES [ name ] ) )
LIBRARY_TYPES [ name ] = type_ |
def build_region_list ( service , chosen_regions = [ ] , partition_name = 'aws' ) :
"""Build the list of target region names
: param service :
: param chosen _ regions :
: param partition _ name :
: return :""" | service = 'ec2containerservice' if service == 'ecs' else service
# Of course things aren ' t that easy . . .
# Get list of regions from botocore
regions = Session ( ) . get_available_regions ( service , partition_name = partition_name )
if len ( chosen_regions ) :
return list ( ( Counter ( regions ) & Counter ( cho... |
def list_components ( self , dependency_order = True ) :
"""Lists the Components by dependency resolving .
Usage : :
> > > manager = Manager ( ( " . / manager / tests / tests _ manager / resources / components / core " , ) )
> > > manager . register _ components ( )
True
> > > manager . list _ components ... | if dependency_order :
return list ( itertools . chain . from_iterable ( [ sorted ( list ( batch ) ) for batch in foundations . common . dependency_resolver ( dict ( ( key , value . require ) for ( key , value ) in self ) ) ] ) )
else :
return [ key for ( key , value ) in self ] |
def convert_la_to_rgba ( self , row , result ) :
"""Convert a grayscale image with alpha to RGBA .""" | for i in range ( len ( row ) // 3 ) :
for j in range ( 3 ) :
result [ ( 4 * i ) + j ] = row [ 2 * i ]
result [ ( 4 * i ) + 3 ] = row [ ( 2 * i ) + 1 ] |
def ShouldRetry ( self , exception ) :
"""Returns true if should retry based on the passed - in exception .
: param ( errors . HTTPFailure instance ) exception :
: rtype :
boolean""" | self . session_token_retry_count += 1
# clear previous location - based routing directive
self . request . clear_route_to_location ( )
if not self . endpoint_discovery_enable : # if endpoint discovery is disabled , the request cannot be retried anywhere else
return False
else :
if self . can_use_multiple_write_... |
def last_location_of_minimum ( x ) :
"""Returns the last location of the minimal value of x .
The position is calculated relatively to the length of x .
: param x : the time series to calculate the feature of
: type x : numpy . ndarray
: return : the value of this feature
: return type : float""" | x = np . asarray ( x )
return 1.0 - np . argmin ( x [ : : - 1 ] ) / len ( x ) if len ( x ) > 0 else np . NaN |
def su ( self ) -> 'Gate' :
"""Convert gate tensor to the special unitary group .""" | rank = 2 ** self . qubit_nb
U = asarray ( self . asoperator ( ) )
U /= np . linalg . det ( U ) ** ( 1 / rank )
return Gate ( tensor = U , qubits = self . qubits ) |
def renamed ( self , source , dest ) :
"""File was renamed in file explorer widget or in project explorer""" | filename = osp . abspath ( to_text_string ( source ) )
index = self . editorstacks [ 0 ] . has_filename ( filename )
if index is not None :
for editorstack in self . editorstacks :
editorstack . rename_in_data ( filename , new_filename = to_text_string ( dest ) ) |
def get_new_service_instance_stub ( service_instance , path , ns = None , version = None ) :
'''Returns a stub that points to a different path ,
created from an existing connection .
service _ instance
The Service Instance .
path
Path of the new stub .
ns
Namespace of the new stub .
Default value is... | # For python 2.7.9 and later , the default SSL context has more strict
# connection handshaking rule . We may need turn off the hostname checking
# and the client side cert verification .
context = None
if sys . version_info [ : 3 ] > ( 2 , 7 , 8 ) :
context = ssl . create_default_context ( )
context . check_ho... |
def if_mousedown ( handler ) :
"""Decorator for mouse handlers .
Only handle event when the user pressed mouse down .
( When applied to a token list . Scroll events will bubble up and are handled
by the Window . )""" | def handle_if_mouse_down ( mouse_event ) :
if mouse_event . event_type == MouseEventType . MOUSE_DOWN :
return handler ( mouse_event )
else :
return NotImplemented
return handle_if_mouse_down |
def arithm_expr_eval ( cell , expr ) :
"""Evaluates a given expression
: param expr : expression
: param cell : dictionary variable name - > expression
: returns : numerical value of expression
: complexity : linear""" | if isinstance ( expr , tuple ) :
( left , op , right ) = expr
lval = arithm_expr_eval ( cell , left )
rval = arithm_expr_eval ( cell , right )
if op == '+' :
return lval + rval
if op == '-' :
return lval - rval
if op == '*' :
return lval * rval
if op == '/' :
... |
def discover_modules ( self ) :
'''Return module sequence discovered from ` ` self . package _ name ` `
Parameters
None
Returns
mods : sequence
Sequence of module names within ` ` self . package _ name ` `
Examples
> > > dw = ApiDocWriter ( ' sphinx ' )
> > > mods = dw . discover _ modules ( )
> >... | modules = [ self . package_name ]
# raw directory parsing
for dirpath , dirnames , filenames in os . walk ( self . root_path ) : # Check directory names for packages
root_uri = self . _path2uri ( os . path . join ( self . root_path , dirpath ) )
# Normally , we ' d only iterate over dirnames , but since
# d... |
def update_records ( self , headers , zoneID , updateRecords ) :
"""Update DNS records .""" | IP = requests . get ( self . GET_EXT_IP_URL ) . text
message = True
errorsRecords = [ ]
sucessRecords = [ ]
for record in updateRecords :
updateEndpoint = '/' + zoneID + '/dns_records/' + record [ 0 ]
updateUrl = self . BASE_URL + updateEndpoint
data = json . dumps ( { 'id' : zoneID , 'type' : record [ 2 ] ... |
def handle_wiki ( msg ) :
"""Given a wiki message , return the FAS username .""" | if 'wiki.article.edit' in msg . topic :
username = msg . msg [ 'user' ]
elif 'wiki.upload.complete' in msg . topic :
username = msg . msg [ 'user_text' ]
else :
raise ValueError ( "Unhandled topic." )
return username |
def _normalize_number_values ( self , parameters ) :
"""Assures equal precision for all number values""" | for key , value in parameters . items ( ) :
if isinstance ( value , ( int , float ) ) :
parameters [ key ] = str ( Decimal ( value ) . normalize ( self . _context ) ) |
def show_pillar ( minion = '*' , ** kwargs ) :
'''Returns the compiled pillar either of a specific minion
or just the global available pillars . This function assumes
that no minion has the id ` ` * ` ` .
Function also accepts pillarenv as attribute in order to limit to a specific pillar branch of git
CLI E... | pillarenv = None
saltenv = 'base'
id_ , grains , _ = salt . utils . minions . get_minion_data ( minion , __opts__ )
if not grains and minion == __opts__ [ 'id' ] :
grains = salt . loader . grains ( __opts__ )
if grains is None :
grains = { 'fqdn' : minion }
for key in kwargs :
if key == 'saltenv' :
... |
def get_changed_files ( include_staged = False ) :
"""Returns a list of the files that changed in the Git repository . This is
used to check if the files that are supposed to be upgraded have changed .
If so , the upgrade will be prevented .""" | process = subprocess . Popen ( [ 'git' , 'status' , '--porcelain' ] , stdout = subprocess . PIPE , stderr = subprocess . STDOUT )
stdout , __ = process . communicate ( )
if process . returncode != 0 :
raise ValueError ( stdout )
files = [ ]
for line in stdout . decode ( ) . split ( '\n' ) :
if not line or line ... |
def ensure_release_scheme ( self , expected_scheme ) :
"""Make sure the release scheme is correctly configured .
: param expected _ scheme : The expected release scheme ( a string ) .
: raises : : exc : ` ~ exceptions . TypeError ` when : attr : ` release _ scheme `
doesn ' t match the expected release scheme... | if self . release_scheme != expected_scheme :
msg = "Repository isn't using '%s' release scheme!"
raise TypeError ( msg % expected_scheme ) |
def included_profiles ( self ) :
"""Load all profiles .""" | profiles = [ ]
for directory in self . tcex_json . get ( 'profile_include_dirs' ) or [ ] :
profiles . extend ( self . _load_config_include ( directory ) )
return profiles |
def format_sql_connectivity_update_settings ( result ) :
'''Formats the SqlConnectivityUpdateSettings object removing arguments that are empty''' | from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict ( )
if result . connectivity_type is not None :
order_dict [ 'connectivityType' ] = result . connectivity_type
if result . port is not None :
order_dict [ 'port' ] = result . port
if result . sql_auth_update... |
def getDirectory ( * args ) :
"""Normalizes the getDirectory method between the different Qt
wrappers .
: return ( < str > filename , < bool > accepted )""" | result = QtGui . QFileDialog . getDirectory ( * args )
# PyQt4 returns just a string
if type ( result ) is not tuple :
return result , bool ( result )
# PySide returns a tuple of str , bool
else :
return result |
def _init_params ( self ) :
"""Initialize parameters in the KVStore .
Parameters with incomplete initialization are ignored .""" | assert self . _kv_initialized , "Cannot initialize parameters in KVStore " "when KVStore is not initialized."
params_to_init = [ ]
if self . _kvstore :
for param in self . _params_to_init :
if param . _deferred_init :
params_to_init . append ( param )
else :
param_arrays = pa... |
def flatten ( x ) :
"""flatten ( sequence ) - > list
Returns a single , flat list which contains all elements retrieved
from the sequence and all recursively contained sub - sequences
( iterables ) .
Examples :
> > > [ 1 , 2 , [ 3,4 ] , ( 5,6 ) ]
[1 , 2 , [ 3 , 4 ] , ( 5 , 6 ) ]
> > > flatten ( [ [ [ ... | result = [ ]
for el in x : # if isinstance ( el , ( list , tuple ) ) :
if hasattr ( el , "__iter__" ) and not isinstance ( el , six . string_types ) :
result . extend ( flatten ( el ) )
else :
result . append ( el )
return list ( result ) |
def _center ( code , segment_dict ) :
"""Starting with ` code ` , follow segments from target to center .""" | while code in segment_dict :
segment = segment_dict [ code ]
yield segment
code = segment . center |
def _send_script ( self , device_info , control_info , script , progress_callback ) :
"""Send a script by repeatedly sending it as a bunch of RPCs .
This function doesn ' t do anything special , it just sends a bunch of RPCs
with each chunk of the script until it ' s finished .""" | for i in range ( 0 , len ( script ) , 20 ) :
chunk = script [ i : i + 20 ]
self . _send_rpc ( device_info , control_info , 8 , 0x2101 , chunk , 0.001 , 1.0 )
if progress_callback is not None :
progress_callback ( i + len ( chunk ) , len ( script ) ) |
def _get_diff ( self , cp_file ) :
"""Get a diff between running config and a proposed file .""" | diff = [ ]
self . _create_sot_file ( )
diff_out = self . device . show ( 'show diff rollback-patch file {0} file {1}' . format ( 'sot_file' , self . replace_file . split ( '/' ) [ - 1 ] ) , raw_text = True )
try :
diff_out = diff_out . split ( '#Generating Rollback Patch' ) [ 1 ] . replace ( 'Rollback Patch is Empt... |
def function_arguments ( func ) :
"""This returns a list of all arguments
: param func : callable object
: return : list of str of the arguments for the function""" | if getattr ( inspect , 'signature' , None ) is None :
return list ( inspect . getargspec ( func ) . args )
else :
return list ( inspect . signature ( func ) . parameters . keys ( ) ) |
def _merge_asized ( base , other , level = 0 ) :
"""Merge * * Asized * * instances ` base ` and ` other ` into ` base ` .""" | ref2key = lambda ref : ref . name . split ( ':' ) [ 0 ]
base . size += other . size
base . flat += other . flat
if level > 0 :
base . name = ref2key ( base )
# Add refs from other to base . Any new refs are appended .
base . refs = list ( base . refs )
# we may need to append items
refs = { }
for ref in base . refs... |
def dragMoveEvent ( self , event ) :
"""Reimplement Qt method""" | index = self . indexAt ( event . pos ( ) )
if index :
dst = self . get_filename ( index )
if osp . isdir ( dst ) :
event . acceptProposedAction ( )
else :
event . ignore ( )
else :
event . ignore ( ) |
def _tar_and_copy ( src_dir , target_dir ) :
"""Tar and gzip src _ dir and copy to GCS target _ dir .""" | src_dir = src_dir . rstrip ( "/" )
target_dir = target_dir . rstrip ( "/" )
tmp_dir = tempfile . gettempdir ( ) . rstrip ( "/" )
src_base = os . path . basename ( src_dir )
shell_run ( "tar --exclude=.git -zcf {tmp_dir}/{src_base}.tar.gz -C {src_dir} ." , src_dir = src_dir , src_base = src_base , tmp_dir = tmp_dir )
fi... |
def tabulate_filetypes_rest ( attrnames = None , header = None , flag_wrap_description = True , description_width = 40 , flag_leaf = True ) :
"""Generates a reST multirow table
Args :
attrnames : list of attribute names ( keys of FILE _ TYPE _ INFO _ ATTRS ) .
Defaults to all attributes
header : list of str... | infos = get_filetypes_info ( editor_quote = "``" , flag_leaf = flag_leaf )
rows , header = filetypes_info_to_rows_header ( infos , attrnames , header , flag_wrap_description , description_width )
ret = a99 . rest_table ( rows , header )
return ret |
def get_remote_user ( request ) :
"""Parse basic HTTP _ AUTHORIZATION and return user name""" | if 'HTTP_AUTHORIZATION' not in request . environ :
return
authorization = request . environ [ 'HTTP_AUTHORIZATION' ]
try :
authmeth , auth = authorization . split ( ' ' , 1 )
except ValueError : # not enough values to unpack
return
if authmeth . lower ( ) != 'basic' :
return
try :
auth = base64 . b6... |
async def send_message ( self , event = None ) :
"""Sends a message . Does nothing if the client is not connected .""" | if not self . cl . is_connected ( ) :
return
# The user needs to configure a chat where the message should be sent .
# If the chat ID does not exist , it was not valid and the user must
# configure one ; hint them by changing the background to red .
if not self . chat_id :
self . chat . configure ( bg = 'red' )... |
def create_o3d_asset ( self , manip = None , small_ov_set = None , large_ov_set = None , display_name = '' , description = '' ) :
"""stub""" | if manip and not isinstance ( manip , ABCDataInputStream ) :
raise InvalidArgument ( 'Manipulatable object must be an ' + 'osid.transport.DataInputStream object' )
if small_ov_set and not isinstance ( small_ov_set , ABCDataInputStream ) :
raise InvalidArgument ( 'Small OV Set object must be an ' + 'osid.transpo... |
def msvc9_query_vcvarsall ( ver , arch = 'x86' , * args , ** kwargs ) :
"""Patched " distutils . msvc9compiler . query _ vcvarsall " for support extra
compilers .
Set environment without use of " vcvarsall . bat " .
Known supported compilers
Microsoft Visual C + + 9.0:
Microsoft Visual C + + Compiler for ... | # Try to get environement from vcvarsall . bat ( Classical way )
try :
orig = get_unpatched ( msvc9_query_vcvarsall )
return orig ( ver , arch , * args , ** kwargs )
except distutils . errors . DistutilsPlatformError : # Pass error if Vcvarsall . bat is missing
pass
except ValueError : # Pass error if envir... |
def from_ip ( cls , ip ) :
"""Retrieve webacc id associated to a webacc ip""" | result = cls . list ( { 'items_per_page' : 500 } )
webaccs = { }
for webacc in result :
for server in webacc [ 'servers' ] :
webaccs [ server [ 'ip' ] ] = webacc [ 'id' ]
return webaccs . get ( ip ) |
def _take_bits ( buf , count ) :
"""Return the booleans that were packed into bytes .""" | # TODO : Verify output
bytes_count = ( count + 7 ) // 8
bytes_mod = count % 8
data = _unpack_from ( buf , 'B' , bytes_count )
values = [ ]
for i , byte in enumerate ( data ) :
for _ in range ( 8 if i != bytes_count - 1 else bytes_mod ) : # TODO : Convert to True / False
values . append ( byte & 0b10000000 )... |
def build ( self ) :
"""todo : Docstring for build
: return :
: rtype :""" | self . _cmd_parser . add_argument ( 'install' , type = str , default = None , nargs = "+" , help = ( "" ) , )
self . _cmd_parser . add_argument ( '-l' , '--location' , default = None , help = ( "Specify the installation location. " ) )
return super ( Cmd , self ) . build ( ) |
def _get_limits_spot ( self ) :
"""Return a dict of limits for spot requests only .
This method should only be used internally by
: py : meth : ~ . get _ limits ` .
: rtype : dict""" | limits = { }
limits [ 'Max spot instance requests per region' ] = AwsLimit ( 'Max spot instance requests per region' , self , 20 , self . warning_threshold , self . critical_threshold , limit_type = 'Spot instance requests' )
limits [ 'Max active spot fleets per region' ] = AwsLimit ( 'Max active spot fleets per region... |
def main ( ) :
"""Parse options and process text to Microsoft Translate""" | # Parse arguments
parser = OptionParser ( )
parser . add_option ( '-n' , '--subscription_key' , dest = 'subscription_key' , help = 'subscription_key for authentication' )
parser . add_option ( '-t' , '--text' , dest = 'text' , help = 'text to synthesize' )
parser . add_option ( '-l' , '--language' , dest = 'language' ,... |
def ip2network ( ip ) :
"""Convert a dotted - quad ip to base network number .
This differs from : func : ` ip2long ` in that partial addresses as treated as
all network instead of network plus host ( eg . ' 127.1 ' expands to
'127.1.0.0 ' )
: param ip : dotted - quad ip address ( eg . ‘ 127.0.0.1 ’ ) .
:... | if not validate_ip ( ip ) :
return None
quads = ip . split ( '.' )
netw = 0
for i in range ( 4 ) :
netw = ( netw << 8 ) | int ( len ( quads ) > i and quads [ i ] or 0 )
return netw |
def _collection_html_response ( resources , start = 0 , stop = 20 ) :
"""Return the HTML representation of the collection * resources * .
: param list resources : list of : class : ` sandman . model . Model ` s to render
: rtype : : class : ` flask . Response `""" | return make_response ( render_template ( 'collection.html' , resources = resources [ start : stop ] ) ) |
def define_batch_env ( constructor , num_agents , env_processes ) :
"""Create environments and apply all desired wrappers .
Args :
constructor : Constructor of an OpenAI gym environment .
num _ agents : Number of environments to combine in the batch .
env _ processes : Whether to step environment in externa... | with tf . variable_scope ( 'environments' ) :
if env_processes :
envs = [ tools . wrappers . ExternalProcess ( constructor ) for _ in range ( num_agents ) ]
else :
envs = [ constructor ( ) for _ in range ( num_agents ) ]
batch_env = tools . BatchEnv ( envs , blocking = not env_processes )
... |
def colourise ( __text : str , * args , ** kwargs ) -> str :
"""Colourise text using click ’ s style function .
Returns text untouched if colour output is not enabled , or ` ` stdout ` ` is
not a tty .
See : func : ` click . style ` for parameters
Args :
_ _ text : Text to colourise
Returns :
Colouris... | if sys . stdout . isatty ( ) :
__text = style ( __text , * args , ** kwargs )
return __text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.