signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def filter_properties_target ( namespaces_iter , resource_types , properties_target ) :
"""Filter metadata namespaces .
Filtering is done based ongiven resource types and a properties target .
: param namespaces _ iter : Metadata namespaces iterable .
: param resource _ types : List of resource type names .
... | def filter_namespace ( namespace ) :
for asn in namespace . get ( 'resource_type_associations' ) :
if ( asn . get ( 'name' ) in resource_types and asn . get ( 'properties_target' ) == properties_target ) :
return True
return False
return filter ( filter_namespace , namespaces_iter ) |
def data_directory ( self ) :
"""The absolute pathname of the directory where pip - accel ' s data files are stored ( a string ) .
- Environment variable : ` ` $ PIP _ ACCEL _ CACHE ` `
- Configuration option : ` ` data - directory ` `
- Default : ` ` / var / cache / pip - accel ` ` if running as ` ` root ` `... | return expand_path ( self . get ( property_name = 'data_directory' , environment_variable = 'PIP_ACCEL_CACHE' , configuration_option = 'data-directory' , default = '/var/cache/pip-accel' if is_root ( ) else '~/.pip-accel' ) ) |
def get_remoteci_configuration ( topic_id , remoteci_id , db_conn = None ) :
"""Get a remoteci configuration . This will iterate over each
configuration in a round robin manner depending on the last
rconfiguration used by the remoteci .""" | db_conn = db_conn or flask . g . db_conn
last_rconfiguration_id = get_last_rconfiguration_id ( topic_id , remoteci_id , db_conn = db_conn )
_RCONFIGURATIONS = models . REMOTECIS_RCONFIGURATIONS
_J_RCONFIGURATIONS = models . JOIN_REMOTECIS_RCONFIGURATIONS
query = sql . select ( [ _RCONFIGURATIONS ] ) . select_from ( _J_... |
def production_variant ( model_name , instance_type , initial_instance_count = 1 , variant_name = 'AllTraffic' , initial_weight = 1 , accelerator_type = None ) :
"""Create a production variant description suitable for use in a ` ` ProductionVariant ` ` list as part of a
` ` CreateEndpointConfig ` ` request .
Ar... | production_variant_configuration = { 'ModelName' : model_name , 'InstanceType' : instance_type , 'InitialInstanceCount' : initial_instance_count , 'VariantName' : variant_name , 'InitialVariantWeight' : initial_weight }
if accelerator_type :
production_variant_configuration [ 'AcceleratorType' ] = accelerator_type
... |
def _parse_ranking ( self , field , boxscore ) :
"""Parse each team ' s rank if applicable .
Retrieve the team ' s rank according to the rankings published each week .
The ranking for the week is only located in the scores section at
the top of the page and not in the actual boxscore information . The
rank ... | ranking = None
index = BOXSCORE_ELEMENT_INDEX [ field ]
teams_boxscore = boxscore ( BOXSCORE_SCHEME [ field ] )
# Occasionally , the list of boxscores for the day won ' t be saved on the
# page . If that ' s the case , return the default ranking .
if str ( teams_boxscore ) == '' :
return ranking
team = pq ( teams_b... |
def _packet_ack ( self , packet , sequence ) :
"""Check packet for ack .""" | if packet [ "sequence" ] == sequence :
if packet [ "payloadtype" ] == PayloadType . SETCOLOR : # notify about colour change
self . _color_callback ( packet [ "target" ] , packet [ "hue" ] , packet [ "sat" ] , packet [ "bri" ] , packet [ "kel" ] )
elif packet [ "payloadtype" ] == PayloadType . SETPOWER2 ... |
def plot_implied_timescales ( ITS , ax = None , outfile = None , show_mle = True , show_mean = True , xlog = False , ylog = True , confidence = 0.95 , refs = None , nits = - 1 , process = None , units = 'steps' , dt = 1. , ** kwargs ) :
r"""Implied timescale plot
Parameters
ITS : implied timescales object .
O... | import matplotlib . pyplot as _plt
# check input
if ax is None :
ax = _plt . gca ( )
colors = [ 'blue' , 'red' , 'green' , 'cyan' , 'purple' , 'orange' , 'violet' ]
lags = ITS . lagtimes
xmax = _np . max ( lags )
srt = _np . argsort ( lags )
# Check the processes to be shown
if process is not None :
if nits != ... |
def handle_message ( self , response , ignore_subscribe_messages = False ) :
"""Parses a pub / sub message . If the channel or pattern was subscribed to
with a message handler , the handler is invoked instead of a parsed
message being returned .""" | message_type = nativestr ( response [ 0 ] )
if message_type == 'pmessage' :
message = { 'type' : message_type , 'pattern' : response [ 1 ] , 'channel' : response [ 2 ] , 'data' : response [ 3 ] }
elif message_type == 'pong' :
message = { 'type' : message_type , 'pattern' : None , 'channel' : None , 'data' : res... |
def putvarcol ( self , columnname , value , startrow = 0 , nrow = - 1 , rowincr = 1 ) :
"""Put an entire column or part of it .
It is similar to putcol , but the shapes of the arrays in the column
can vary . The value has to be a dict of numpy arrays .
The column can be sliced by giving a start row ( default ... | self . _putvarcol ( columnname , startrow , nrow , rowincr , value ) |
def put ( self , value ) :
"""Puts an item into the queue .
Returns a Future that resolves to None once the value has been
accepted by the queue .""" | io_loop = IOLoop . current ( )
new_hole = Future ( )
new_put = Future ( )
new_put . set_result ( new_hole )
with self . _lock :
self . _put , put = new_put , self . _put
answer = Future ( )
def _on_put ( future ) :
if future . exception ( ) : # pragma : no cover ( never happens )
return answer . set_exc... |
def save_model ( self , file_name = 'model.cx' ) :
"""Save the assembled CX network in a file .
Parameters
file _ name : Optional [ str ]
The name of the file to save the CX network to . Default : model . cx""" | with open ( file_name , 'wt' ) as fh :
cx_str = self . print_cx ( )
fh . write ( cx_str ) |
def _compute ( self ) :
"""Compute x / y min and max and x / y scale and set labels""" | if self . xvals :
xmin = min ( self . xvals )
xmax = max ( self . xvals )
xrng = ( xmax - xmin )
else :
xrng = None
if self . yvals :
ymin = min ( min ( self . yvals ) , self . zero )
ymax = max ( max ( self . yvals ) , self . zero )
yrng = ( ymax - ymin )
else :
yrng = None
for serie in... |
def sync_sources ( self ) :
"""Syncs data sources between Elements , which draw data
from the same object .""" | get_sources = lambda x : ( id ( x . current_frame . data ) , x )
filter_fn = lambda x : ( x . shared_datasource and x . current_frame is not None and not isinstance ( x . current_frame . data , np . ndarray ) and 'source' in x . handles )
data_sources = self . traverse ( get_sources , [ filter_fn ] )
grouped_sources = ... |
def handle_lock_expired ( payment_state : InitiatorPaymentState , state_change : ReceiveLockExpired , channelidentifiers_to_channels : ChannelMap , block_number : BlockNumber , ) -> TransitionResult [ InitiatorPaymentState ] :
"""Initiator also needs to handle LockExpired messages when refund transfers are involved... | initiator_state = payment_state . initiator_transfers . get ( state_change . secrethash )
if not initiator_state :
return TransitionResult ( payment_state , list ( ) )
channel_identifier = initiator_state . channel_identifier
channel_state = channelidentifiers_to_channels . get ( channel_identifier )
if not channel... |
def write_register ( self , registeraddress , value , numberOfDecimals = 0 , functioncode = 16 , signed = False ) :
"""Write an integer to one 16 - bit register in the slave , possibly scaling it .
The slave register can hold integer values in the range 0 to 65535 ( " Unsigned INT16 " ) .
Args :
* registeradd... | _checkFunctioncode ( functioncode , [ 6 , 16 ] )
_checkInt ( numberOfDecimals , minvalue = 0 , maxvalue = 10 , description = 'number of decimals' )
_checkBool ( signed , description = 'signed' )
_checkNumerical ( value , description = 'input value' )
self . _genericCommand ( functioncode , registeraddress , value , num... |
def shell_cmd ( self , command = "" ) :
"""Execute a shell command .
Purpose : Used to send a shell command to the connected device .
| This uses the self . _ shell instance , which should be a
| paramiko . Channel object , instead of a SSHClient .
| This is because we cannot send shell commands to the
| ... | if not command :
raise InvalidCommandError ( "Parameter 'command' must not be empty." )
command = command . strip ( ) + '\n'
self . _shell . send ( command )
time . sleep ( 2 )
out = ''
while self . _shell . recv_ready ( ) :
out += self . _shell . recv ( 999999 )
time . sleep ( .75 )
# take off the command ... |
def tag_arxiv ( line ) :
"""Tag arxiv report numbers
We handle arXiv in 2 ways :
* starting with arXiv : 1022.1111
* this format exactly 9999.9999
We also format the output to the standard arxiv notation :
* arXiv : 2007.12.1111
* arXiv : 2007.12.1111v2""" | def tagger ( match ) :
groups = match . groupdict ( )
if match . group ( 'suffix' ) :
groups [ 'suffix' ] = ' ' + groups [ 'suffix' ]
else :
groups [ 'suffix' ] = ''
return u'<cds.REPORTNUMBER>arXiv:%(year)s' u'%(month)s.%(num)s%(suffix)s' u'</cds.REPORTNUMBER>' % groups
line = re_arxiv_... |
def leaves ( self ) :
"""Retrieve a list of windows that delineate from the currently
selected container . Only lists client windows , no intermediate
containers .
: rtype : List of : class : ` Con ` .""" | leaves = [ ]
for c in self :
if not c . nodes and c . type == "con" and c . parent . type != "dockarea" :
leaves . append ( c )
return leaves |
def deterministic_crowding ( self , parents , offspring , X_parents , X_offspring ) :
"""deterministic crowding implementation ( for non - steady state ) .
offspring compete against the parent they are most similar to , here defined as
the parent they are most correlated with .
the offspring only replace thei... | # get children locations produced from crossover
cross_children = [ i for i , o in enumerate ( offspring ) if len ( o . parentid ) > 1 ]
# order offspring so that they are lined up with their most similar parent
for c1 , c2 in zip ( cross_children [ : : 2 ] , cross_children [ 1 : : 2 ] ) : # get parent locations
p_... |
def _make_renderer ( self , at_paths , at_encoding , ** kwargs ) :
""": param at _ paths : Template search paths
: param at _ encoding : Template encoding
: param kwargs : Keyword arguments passed to the template engine to
render templates with specific features enabled .""" | for eopt in ( "file_encoding" , "string_encoding" ) :
default = self . _roptions . get ( eopt , at_encoding . lower ( ) )
self . _roptions [ eopt ] = kwargs . get ( eopt , default )
pkey = "search_dirs"
paths = kwargs . get ( pkey , [ ] ) + self . _roptions . get ( pkey , [ ] )
if at_paths is not None :
pat... |
def temporary_dir ( root_dir = None , cleanup = True , suffix = '' , permissions = None , prefix = tempfile . template ) :
"""A with - context that creates a temporary directory .
: API : public
You may specify the following keyword args :
: param string root _ dir : The parent directory to create the tempora... | path = tempfile . mkdtemp ( dir = root_dir , suffix = suffix , prefix = prefix )
try :
if permissions is not None :
os . chmod ( path , permissions )
yield path
finally :
if cleanup :
shutil . rmtree ( path , ignore_errors = True ) |
def wait_until_page_loaded ( page_obj_class , webdriver = None , timeout = WTF_TIMEOUT_MANAGER . NORMAL , sleep = 0.5 , bad_page_classes = [ ] , message = None , ** kwargs ) :
"""Waits until the page is loaded .
Args :
page _ obj _ class ( Class ) : PageObject class
Kwargs :
webdriver ( Webdriver ) : Seleni... | if not webdriver :
webdriver = WTF_WEBDRIVER_MANAGER . get_driver ( )
# convert this param to list if not already .
if type ( bad_page_classes ) != list :
bad_page_classes = [ bad_page_classes ]
end_time = datetime . now ( ) + timedelta ( seconds = timeout )
last_exception = None
while datetime . now ( ) < end_... |
def add_string ( self , data ) :
"""Process some data splitting it into complete lines and buffering the rest
Args :
data : A ` str ` in Python 2 or ` bytes ` in Python 3
Returns :
list of complete lines ending with a carriage return ( eg . a progress
bar ) or a newline .""" | lines = [ ]
while data :
match = self . _line_end_re . search ( data )
if match is None :
chunk = data
else :
chunk = data [ : match . end ( ) ]
data = data [ len ( chunk ) : ]
if self . _buf and self . _buf [ - 1 ] . endswith ( b ( '\r' ) ) and not chunk . startswith ( b ( '\n' ) ) ... |
def file_is_seekable ( f ) :
'''Returns True if file ` f ` is seekable , and False if not
Useful to determine , for example , if ` f ` is STDOUT to
a pipe .''' | try :
f . tell ( )
logger . info ( "File is seekable!" )
except IOError , e :
if e . errno == errno . ESPIPE :
return False
else :
raise
return True |
def query ( self , listdelimiter = "+" , safe = "" , ** kwargs ) :
"""Url queries
: param listdelimiter : Specifies what list delimiter should be
: param safe : string that includes all the characters that should not be ignored
Kwargs ( Since its a dictionary ) are not ordered . You must call the
method aga... | safe = safe if safe else self . safe
for arg in list ( kwargs . keys ( ) ) :
if ( isinstance ( kwargs [ arg ] , list ) or isinstance ( kwargs [ arg ] , tuple ) or isinstance ( kwargs [ arg ] , set ) ) :
items = [ quote_plus ( str ( x ) , safe = safe ) for x in kwargs [ arg ] ]
self . __query__ . upd... |
def rollback ( self ) :
"""Implementation of NAPALM method rollback .""" | commands = [ ]
commands . append ( 'configure replace flash:rollback-0' )
commands . append ( 'write memory' )
self . device . run_commands ( commands ) |
def _set_npb ( self , v , load = False ) :
"""Setter method for npb , mapped from YANG variable / interface / port _ channel / npb ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ npb is considered as a private
method . Backends looking to populate this v... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = npb . npb , is_container = 'container' , presence = False , yang_name = "npb" , rest_name = "npb" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { ... |
def generator_by_digest ( family , digest_size ) :
"""Return generator by hash generator family name and digest size
: param family : name of hash - generator family
: return : WHashGeneratorProto class""" | for generator_name in WHash . available_generators ( family = family ) :
generator = WHash . generator ( generator_name )
if generator . generator_digest_size ( ) == digest_size :
return generator
raise ValueError ( 'Hash generator is not available' ) |
def pdf ( self , mu ) :
"""PDF for Cauchy prior
Parameters
mu : float
Latent variable for which the prior is being formed over
Returns
- p ( mu )""" | return ss . cauchy . pdf ( mu , self . loc0 , self . scale0 ) |
def mkdir_p ( path : str ) -> None :
"""Makes a directory , and any intermediate ( parent ) directories if required .
This is the UNIX ` ` mkdir - p DIRECTORY ` ` command ; of course , we use
: func : ` os . makedirs ` instead , for portability .""" | log . debug ( "mkdir -p " + path )
os . makedirs ( path , exist_ok = True ) |
def GetSubFileEntryByName ( self , name , case_sensitive = True ) :
"""Retrieves a sub file entry by name .
Args :
name ( str ) : name of the file entry .
case _ sensitive ( Optional [ bool ] ) : True if the name is case sensitive .
Returns :
FileEntry : a file entry or None if not available .""" | name_lower = name . lower ( )
matching_sub_file_entry = None
for sub_file_entry in self . sub_file_entries :
if sub_file_entry . name == name :
return sub_file_entry
if not case_sensitive and sub_file_entry . name . lower ( ) == name_lower :
if not matching_sub_file_entry :
matching_... |
def get_resource_or_collection ( cls , request_args , id = None ) :
r"""Deprecated for version 1.1.0 . Please use get _ resource or get _ collection .
This function has multiple behaviors .
With id specified : Used to fetch a single resource object with the given id in response to a GET request . \
get _ reso... | if id :
try :
r = cls . get_resource ( request_args )
except DoesNotExist :
r = application_codes . error_response ( [ application_codes . RESOURCE_NOT_FOUND ] )
else :
try :
r = cls . get_collection ( request_args )
except Exception as e :
r = application_codes . error_r... |
def request ( self , request ) :
"""Perform an HTTP request through the context
Args :
request : A v20 . request . Request object
Returns :
A v20 . response . Response object""" | url = "{}{}" . format ( self . _base_url , request . path )
timeout = self . poll_timeout
if request . stream is True :
timeout = self . stream_timeout
try :
http_response = self . _session . request ( request . method , url , headers = self . _headers , params = request . params , data = request . body , strea... |
def get_cached ( location , ** kwargs ) :
"""Simple wrapper that adds Django caching support to ' geocoder . get ( ) ' .""" | result = cache . get ( location )
# Result is not cached or wrong
if not result or not result . ok :
result = geocoder . get ( location , ** kwargs )
if result . ok :
cache . set ( location , result )
return result |
def replace_anc ( dataset , parent_dataset ) :
"""Replace * dataset * the * parent _ dataset * ' s ` ancillary _ variables ` field .""" | if parent_dataset is None :
return
current_dsid = DatasetID . from_dict ( dataset . attrs )
for idx , ds in enumerate ( parent_dataset . attrs [ 'ancillary_variables' ] ) :
if current_dsid == DatasetID . from_dict ( ds . attrs ) :
parent_dataset . attrs [ 'ancillary_variables' ] [ idx ] = dataset
... |
def publish_server_heartbeat_succeeded ( self , connection_id , duration , reply ) :
"""Publish a ServerHeartbeatSucceededEvent to all server heartbeat
listeners .
: Parameters :
- ` connection _ id ` : The address ( host / port pair ) of the connection .
- ` duration ` : The execution time of the event in ... | event = ServerHeartbeatSucceededEvent ( duration , reply , connection_id )
for subscriber in self . __server_heartbeat_listeners :
try :
subscriber . succeeded ( event )
except Exception :
_handle_exception ( ) |
def add_altitude ( self , altitude , precision = 100 ) :
"""Add altitude ( pre is the precision ) .""" | ref = 0 if altitude > 0 else 1
self . _ef [ "GPS" ] [ piexif . GPSIFD . GPSAltitude ] = ( int ( abs ( altitude ) * precision ) , precision )
self . _ef [ "GPS" ] [ piexif . GPSIFD . GPSAltitudeRef ] = ref |
def get ( self , identity ) :
"""Constructs a SyncListPermissionContext
: param identity : Identity of the user to whom the Sync List Permission applies .
: returns : twilio . rest . sync . v1 . service . sync _ list . sync _ list _ permission . SyncListPermissionContext
: rtype : twilio . rest . sync . v1 . ... | return SyncListPermissionContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , list_sid = self . _solution [ 'list_sid' ] , identity = identity , ) |
def _default_return_columns ( self ) :
"""Return a list of the model elements that does not include lookup functions
or other functions that take parameters .""" | return_columns = [ ]
parsed_expr = [ ]
for key , value in self . components . _namespace . items ( ) :
if hasattr ( self . components , value ) :
sig = signature ( getattr ( self . components , value ) )
# The ` * args ` reference handles the py2.7 decorator .
if len ( set ( sig . parameters... |
def start_check ( aggregate , out ) :
"""Start checking in background and write encoded output to out .""" | # check in background
t = threading . Thread ( target = director . check_urls , args = ( aggregate , ) )
t . start ( )
# time to wait for new data
sleep_seconds = 2
# current running time
run_seconds = 0
while not aggregate . is_finished ( ) :
yield out . get_data ( )
time . sleep ( sleep_seconds )
run_seco... |
def build_extension ( self , ext ) :
"""build _ extension .
: raises BuildFailed : cythonize impossible""" | try :
build_ext . build_ext . build_extension ( self , ext )
except ( distutils . errors . CCompilerError , distutils . errors . DistutilsExecError , distutils . errors . DistutilsPlatformError , ValueError , ) :
raise BuildFailed ( ) |
def _execute ( self , ifile , process ) :
"""Execution loop
: param ifile : Input file object . Unused .
: type ifile : file
: return : ` None ` .""" | if self . _protocol_version == 2 :
result = self . _read_chunk ( ifile )
if not result :
return
metadata , body = result
action = getattr ( metadata , 'action' , None )
if action != 'execute' :
raise RuntimeError ( 'Expected execute action, not {}' . format ( action ) )
self . _recor... |
def mask ( self ) :
"""Returns mask associated with this layer .
: return : : py : class : ` ~ psd _ tools . api . mask . Mask ` or ` None `""" | if not hasattr ( self , "_mask" ) :
self . _mask = Mask ( self ) if self . has_mask ( ) else None
return self . _mask |
async def ws_handler ( self , protocol , path ) :
"""This is the main handler function for the ' websockets ' implementation
to call into . We just wait for close then return , and instead allow
' send ' and ' receive ' events to drive the flow .""" | self . handshake_completed_event . set ( )
await self . closed_event . wait ( ) |
def warped_gp_cubic_sine ( max_iters = 100 ) :
"""A test replicating the cubic sine regression problem from
Snelson ' s paper .""" | X = ( 2 * np . pi ) * np . random . random ( 151 ) - np . pi
Y = np . sin ( X ) + np . random . normal ( 0 , 0.2 , 151 )
Y = np . array ( [ np . power ( abs ( y ) , float ( 1 ) / 3 ) * ( 1 , - 1 ) [ y < 0 ] for y in Y ] )
X = X [ : , None ]
Y = Y [ : , None ]
warp_k = GPy . kern . RBF ( 1 )
warp_f = GPy . util . warpin... |
def collect ( self ) :
"""Overrides the Collector . collect method""" | if psutil is None :
self . log . error ( 'Unable to import module psutil' )
return { }
for port_name , port_cfg in self . ports . iteritems ( ) :
port = int ( port_cfg [ 'number' ] )
stats = get_port_stats ( port )
for stat_name , stat_value in stats . iteritems ( ) :
metric_name = '%s.%s' %... |
def _plot_connectivity ( self , A , data = None , lims = [ None , None ] ) :
"""A debug function used to plot the adjacency / connectivity matrix .
This is really just a light wrapper around _ plot _ connectivity _ helper""" | if data is None :
data = self . data
B = A . tocoo ( )
self . _plot_connectivity_helper ( B . col , B . row , B . data , data , lims ) |
def output ( data , ** kwargs ) : # pylint : disable = unused - argument
'''Output the data in lines , very nice for running commands''' | ret = ''
if hasattr ( data , 'keys' ) :
for key in data :
value = data [ key ]
# Don ' t blow up on non - strings
try :
for line in value . splitlines ( ) :
ret += '{0}: {1}\n' . format ( key , line )
except AttributeError :
ret += '{0}: {1}\n'... |
def setup_logging ( level ) :
"""Setup logger .""" | logging . root . setLevel ( level )
logging . root . addHandler ( STREAM_HANDLER ) |
def decode ( self , probs , sizes = None ) :
"""Returns the argmax decoding given the probability matrix . Removes
repeated elements in the sequence , as well as blanks .
Arguments :
probs : Tensor of character probabilities from the network . Expected shape of seq _ length x batch x output _ dim
sizes ( op... | _ , max_probs = torch . max ( probs . transpose ( 0 , 1 ) , 2 )
strings = self . convert_to_strings ( max_probs . view ( max_probs . size ( 0 ) , max_probs . size ( 1 ) ) , sizes )
return self . process_strings ( strings , remove_repetitions = True ) |
def get_yaml_config ( config_path ) :
"""Load yaml config file and return dictionary .
Todo :
* This will need refactoring similar to the test search .""" | config_path = os . path . expanduser ( config_path )
if not os . path . isfile ( config_path ) :
raise IpaUtilsException ( 'Config file not found: %s' % config_path )
with open ( config_path , 'r' ) as f :
config = yaml . safe_load ( f )
return config |
def _get_data ( self , url , config , send_sc = True ) :
"""Hit a given URL and return the parsed json""" | # Load basic authentication configuration , if available .
if config . username and config . password :
auth = ( config . username , config . password )
else :
auth = None
# Load SSL configuration , if available .
# ssl _ verify can be a bool or a string
# ( http : / / docs . python - requests . org / en / late... |
def set_data ( self , image ) :
"""Set the data
Parameters
image : array - like
The image data .""" | data = np . asarray ( image )
if self . _data is None or self . _data . shape != data . shape :
self . _need_vertex_update = True
self . _data = data
self . _need_texture_upload = True |
async def _bind_key_to_queue ( self , routing_key : AnyStr , queue_name : AnyStr ) -> None :
"""Bind to queue with specified routing key .
: param routing _ key : Routing key to bind with .
: param queue _ name : Name of the queue
: return : Does not return anything""" | logger . info ( "Binding key='%s'" , routing_key )
result = await self . _channel . queue_bind ( exchange_name = self . _exchange_name , queue_name = queue_name , routing_key = routing_key , )
return result |
def random_bytes ( n ) :
"""Returns n random bytes generated with given seed
tags :
- Dynamic data
parameters :
- in : path
name : n
type : int
produces :
- application / octet - stream
responses :
200:
description : Bytes .""" | n = min ( n , 100 * 1024 )
# set 100KB limit
params = CaseInsensitiveDict ( request . args . items ( ) )
if "seed" in params :
random . seed ( int ( params [ "seed" ] ) )
response = make_response ( )
# Note : can ' t just use os . urandom here because it ignores the seed
response . data = bytearray ( random . randi... |
def p_base_type ( self , p ) : # noqa
'''base _ type : BOOL annotations
| BYTE annotations
| I8 annotations
| I16 annotations
| I32 annotations
| I64 annotations
| DOUBLE annotations
| STRING annotations
| BINARY annotations''' | name = p [ 1 ]
if name == 'i8' :
name = 'byte'
p [ 0 ] = ast . PrimitiveType ( name , p [ 2 ] ) |
def printflush ( s : str , end : str = '\n' ) -> None :
"""Prints a given string to the standard output and immediately flushes .""" | print ( s , end = end )
sys . stdout . flush ( ) |
def new_message_from_message_type ( message_type ) :
"""Given an OpenFlow Message Type , return an empty message of that type .
Args :
messageType ( : class : ` ~ pyof . v0x01 . common . header . Type ` ) :
Python - openflow message .
Returns :
Empty OpenFlow message of the requested message type .
Rais... | message_type = str ( message_type )
if message_type not in MESSAGE_TYPES :
raise ValueError ( '"{}" is not known.' . format ( message_type ) )
message_class = MESSAGE_TYPES . get ( message_type )
message_instance = message_class ( )
return message_instance |
def gell_mann_basis ( dim ) :
"""Returns a : class : ` ~ qinfer . tomography . TomographyBasis ` on dim dimensions
using the generalized Gell - Mann matrices .
This implementation is based on a MATLAB - language implementation
provided by Carlos Riofrío , Seth Merkel and Andrew Silberfarb .
Used with permi... | # Start by making an empty array of the right shape to
# hold the matrices that we construct .
basis = np . zeros ( ( dim ** 2 , dim , dim ) , dtype = complex )
# The first matrix should be the identity .
basis [ 0 , : , : ] = np . eye ( dim ) / np . sqrt ( dim )
# The next dim basis elements should be diagonal ,
# wit... |
def _bin ( g ) :
"""Applies the BIN rule to ' g ' ( see top comment ) .""" | new_rules = [ ]
for rule in g . rules :
if len ( rule . rhs ) > 2 :
new_rules += _split ( rule )
else :
new_rules . append ( rule )
return Grammar ( new_rules ) |
def is_defined ( self , obj , force_import = False ) :
"""Return True if object is defined in current namespace""" | from spyder_kernels . utils . dochelpers import isdefined
ns = self . _get_current_namespace ( with_magics = True )
return isdefined ( obj , force_import = force_import , namespace = ns ) |
def get_response_for_url ( self , url ) :
"""Accepts a fully - qualified url .
Returns an HttpResponse , passing through all headers and the status code .""" | if not url or "//" not in url :
raise ValueError ( "Missing or invalid url: %s" % url )
render_url = self . BASE_URL + url
headers = { 'X-Prerender-Token' : self . token , }
r = self . session . get ( render_url , headers = headers , allow_redirects = False )
assert r . status_code < 500
return self . build_django_... |
def random_hex ( length ) :
"""Generates a random hex string""" | return escape . to_unicode ( binascii . hexlify ( os . urandom ( length ) ) [ length : ] ) |
def prepare_full_example_2 ( lastdate = '1996-01-05' ) -> ( hydpytools . HydPy , hydpy . pub , testtools . TestIO ) :
"""Prepare the complete ` LahnH ` project for testing .
| prepare _ full _ example _ 2 | calls | prepare _ full _ example _ 1 | , but also
returns a readily prepared | HydPy | instance , as well... | prepare_full_example_1 ( )
with testtools . TestIO ( ) :
hp = hydpytools . HydPy ( 'LahnH' )
hydpy . pub . timegrids = '1996-01-01' , lastdate , '1d'
hp . prepare_everything ( )
return hp , hydpy . pub , testtools . TestIO |
def date ( self , value = None ) :
"""Get or set the document ' s date from / in the metadata .
No arguments : Get the document ' s date from metadata
Argument : Set the document ' s date in metadata""" | if not ( value is None ) :
if ( self . metadatatype == "native" ) :
self . metadata [ 'date' ] = value
else :
self . _date = value
if ( self . metadatatype == "native" ) :
if 'date' in self . metadata :
return self . metadata [ 'date' ]
else :
return None
else :
retur... |
def get_current_word ( self , completion = False ) :
"""Return current word , i . e . word at cursor position""" | ret = self . get_current_word_and_position ( completion )
if ret is not None :
return ret [ 0 ] |
def _check_keypair ( self , name , public_key_path , private_key_path ) :
"""First checks if the keypair is valid , then checks if the keypair
is registered with on the cloud . If not the keypair is added to the
users ssh keys .
: param str name : name of the ssh key
: param str public _ key _ path : path t... | connection = self . _connect ( )
keypairs = connection . get_all_key_pairs ( )
keypairs = dict ( ( k . name , k ) for k in keypairs )
# decide if dsa or rsa key is provided
pkey = None
is_dsa_key = False
try :
pkey = DSSKey . from_private_key_file ( private_key_path )
is_dsa_key = True
except PasswordRequiredEx... |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | # extract dictionaries of coefficients specific to required
# intensity measure type
C = self . COEFFS [ imt ]
imean = ( self . _get_magnitude_scaling_term ( C , rup . mag ) + self . _get_distance_scaling_term ( C , dists . rjb , rup . mag ) )
# convert from cm / s * * 2 to g for SA and from cm / s * * 2 to g for PGA (... |
def p_function_call ( p ) :
'''function _ call : namespace _ name LPAREN function _ call _ parameter _ list RPAREN
| NS _ SEPARATOR namespace _ name LPAREN function _ call _ parameter _ list RPAREN
| NAMESPACE NS _ SEPARATOR namespace _ name LPAREN function _ call _ parameter _ list RPAREN''' | if len ( p ) == 5 :
p [ 0 ] = ast . FunctionCall ( p [ 1 ] , p [ 3 ] , lineno = p . lineno ( 2 ) )
elif len ( p ) == 6 :
p [ 0 ] = ast . FunctionCall ( p [ 1 ] + p [ 2 ] , p [ 4 ] , lineno = p . lineno ( 1 ) )
else :
p [ 0 ] = ast . FunctionCall ( p [ 1 ] + p [ 2 ] + p [ 3 ] , p [ 5 ] , lineno = p . lineno ... |
def process ( self , chunk ) :
"""computes the hash of all of the trigrams in the chunk using a window
of length 5""" | self . _digest = None
if isinstance ( chunk , text_type ) :
chunk = chunk . encode ( 'utf-8' )
# chunk is a byte string
for char in chunk :
self . num_char += 1
if PY3 : # In Python 3 , iterating over bytes yields integers
c = char
else :
c = ord ( char )
if len ( self . window ) > 1... |
def _write_temp ( content , suffix ) :
'''write ` content ` to a temporary XXX ` suffix ` file and return the filename .
It is user ' s responsibility to delete when done .''' | with NamedTemporaryFile ( mode = 'w' , suffix = suffix , delete = False ) as out :
out . write ( content )
return out . name |
def run ( * args , ** kwargs ) :
"""Please dont use . Instead use ` luigi ` binary .
Run from cmdline using argparse .
: param use _ dynamic _ argparse : Deprecated and ignored""" | luigi_run_result = _run ( * args , ** kwargs )
return luigi_run_result if kwargs . get ( 'detailed_summary' ) else luigi_run_result . scheduling_succeeded |
def sortby ( listoflists , sortcols ) :
"""Sorts a list of lists on the column ( s ) specified in the sequence
sortcols .
Usage : sortby ( listoflists , sortcols )
Returns : sorted list , unchanged column ordering""" | newlist = abut ( colex ( listoflists , sortcols ) , listoflists )
newlist . sort ( )
try :
numcols = len ( sortcols )
except TypeError :
numcols = 1
crit = '[' + str ( numcols ) + ':]'
newlist = colex ( newlist , crit )
return newlist |
def patents ( query = None , concept_tags = None , limit = None ) :
'''HTTP REQUEST
GET https : / / api . nasa . gov / patents
QUERY PARAMETERS
ParameterTypeDefaultDescription
querystringNoneSearch text to filter results
concept _ tagsboolFalseReturn an ordered dictionary of concepts from the patent abstr... | base_url = "https://api.nasa.gov/patents/content?"
if not query :
raise ValueError ( "search query is missing, which is mandatory." )
elif not isinstance ( query , str ) :
try :
query = str ( query )
except :
raise ValueError ( "query has to be type of string" )
else :
base_url += "query... |
def flatten_choices_dict ( choices ) :
"""Convert a group choices dict into a flat dict of choices .
flatten _ choices ( { 1 : ' 1st ' , 2 : ' 2nd ' } ) - > { 1 : ' 1st ' , 2 : ' 2nd ' }
flatten _ choices ( { ' Group ' : { 1 : ' 1st ' , 2 : ' 2nd ' } } ) - > { 1 : ' 1st ' , 2 : ' 2nd ' }""" | ret = OrderedDict ( )
for key , value in choices . items ( ) :
if isinstance ( value , dict ) : # grouped choices ( category , sub choices )
for sub_key , sub_value in value . items ( ) :
ret [ sub_key ] = sub_value
else : # choice ( key , display value )
ret [ key ] = value
return r... |
def substring_search ( word , collection ) :
"""Find all matches in the ` collection ` for the specified ` word ` .
If ` word ` is empty , returns all items in ` collection ` .
: type word : str
: param word : The substring to search for .
: type collection : collection , usually a list
: param collection... | return [ item for item in sorted ( collection ) if item . startswith ( word ) ] |
def positive_directional_index ( close_data , high_data , low_data , period ) :
"""Positive Directional Index ( + DI ) .
Formula :
+ DI = 100 * SMMA ( + DM ) / ATR""" | catch_errors . check_for_input_len_diff ( close_data , high_data , low_data )
pdi = ( 100 * smma ( positive_directional_movement ( high_data , low_data ) , period ) / atr ( close_data , period ) )
return pdi |
def parameter_from_json ( dictionary , bundle = None ) :
"""Load a single parameter from a JSON dictionary .
: parameter dict dictionary : the dictionary containing the parameter
information
: parameter bundle : ( optional )
: return : instantiated : class : ` Parameter ` object""" | if isinstance ( dictionary , str ) :
dictionary = json . loads ( dictionary , object_pairs_hook = parse_json )
classname = dictionary . pop ( 'Class' )
if classname not in _parameter_class_that_require_bundle :
bundle = None
# now let ' s do some dirty magic and get the actual classitself
# from THIS module . _... |
def get_layout_as_dict ( layout ) :
"""Take a dict or string and return a dict if the data is json - encoded .
The string will json parsed to check for json validity . In order to deal
with strings which have been json encoded multiple times , keep json decoding
until a dict is retrieved or until a non - json... | if isinstance ( layout , dict ) :
return layout
if ( isinstance ( layout , six . string_types ) ) :
try :
return get_layout_as_dict ( json . loads ( layout ) )
except :
return layout |
def version ( ruby = None , runas = None , gem_bin = None ) :
'''Print out the version of gem
: param gem _ bin : string : None
Full path to ` ` gem ` ` binary to use .
: param ruby : string : None
If RVM or rbenv are installed , the ruby version and gemset to use .
Ignored if ` ` gem _ bin ` ` is specifi... | cmd = [ '--version' ]
stdout = _gem ( cmd , ruby , gem_bin = gem_bin , runas = runas )
ret = { }
for line in salt . utils . itertools . split ( stdout , '\n' ) :
match = re . match ( r'[.0-9]+' , line )
if match :
ret = line
break
return ret |
def _get_entity_by_name ( self , entity_name ) :
"""Fetch Entity record with an Entity name""" | if entity_name in self . _registry :
return self . _registry [ entity_name ]
else :
return self . _find_entity_in_records_by_class_name ( entity_name ) |
def run ( pipeline , input_gen , options = { } ) :
"""Run a pipeline over a input generator
> > > # if we have a simple component
> > > from reliure . pipeline import Composable
> > > @ Composable
. . . def print _ each ( letters ) :
. . . for letter in letters :
. . . print ( letter )
. . . yield let... | logger = logging . getLogger ( "reliure.run" )
t0 = time ( )
res = [ output for output in pipeline ( input_gen , ** options ) ]
logger . info ( "Pipeline executed in %1.3f sec" % ( time ( ) - t0 ) )
return res |
def _column_type ( values , has_invisible = True ) :
"""The least generic type all column values are convertible to .
> > > _ column _ type ( [ " 1 " , " 2 " ] ) is _ int _ type
True
> > > _ column _ type ( [ " 1 " , " 2.3 " ] ) is _ float _ type
True
> > > _ column _ type ( [ " 1 " , " 2.3 " , " four " ]... | return reduce ( _more_generic , [ type ( v ) for v in values ] , int ) |
def p_expression_subsetlist ( self , p ) :
'''expression : expression SUBSET lexp''' | _LOGGER . debug ( "expresion -> expresion SUBSET lexp" )
if p [ 1 ] . type != TypedClass . LIST :
raise TypeError ( "lists expected for SUBSET operator" )
if p [ 3 ] . type != TypedClass . LIST :
raise TypeError ( "lists expected for SUBSET operator" )
retval = True
for vl in p [ 1 ] . value :
found = False... |
def _round_robin_write ( writers , generator ) :
"""Write records from generator round - robin across writers .""" | for i , example in enumerate ( utils . tqdm ( generator , unit = " examples" , leave = False ) ) :
writers [ i % len ( writers ) ] . write ( example ) |
def update_parameters ( self , ** kwargs ) :
"""You can add or update rapid namelist parameters by using the name of
the variable in the rapid namelist file ( this is case sensitive ) .
Parameters
* * kwargs : str , optional
Keyword arguments matching the input parameters
in the RAPID namelist .
Example... | # set arguments based off of user input
for key , value in list ( kwargs . items ( ) ) :
if key in dir ( self ) and not key . startswith ( '_' ) :
setattr ( self , key , value )
else :
log ( "Invalid RAPID parameter %s." % key , "ERROR" ) |
def Pause ( self ) :
"""Pauses the hunt ( removes Foreman rules , does not touch expiry time ) .""" | if not self . IsHuntStarted ( ) :
return
self . _RemoveForemanRule ( )
self . hunt_obj . Set ( self . hunt_obj . Schema . STATE ( "PAUSED" ) )
self . hunt_obj . Flush ( )
self . _CreateAuditEvent ( "HUNT_PAUSED" ) |
def titles ( self , unique = False ) :
"""Return a list of all available spreadsheet titles .
Args :
unique ( bool ) : drop duplicates
Returns :
list : list of title / name strings""" | if unique :
return tools . uniqued ( title for _ , title in self . iterfiles ( ) )
return [ title for _ , title in self . iterfiles ( ) ] |
def get_tempo ( artist , title ) :
"gets the tempo for a song" | results = song . search ( artist = artist , title = title , results = 1 , buckets = [ 'audio_summary' ] )
if len ( results ) > 0 :
return results [ 0 ] . audio_summary [ 'tempo' ]
else :
return None |
def documents ( self ) :
"""Access the documents
: returns : twilio . rest . sync . v1 . service . document . DocumentList
: rtype : twilio . rest . sync . v1 . service . document . DocumentList""" | if self . _documents is None :
self . _documents = DocumentList ( self . _version , service_sid = self . _solution [ 'sid' ] , )
return self . _documents |
def getScreen ( self ) :
"""Returns an instance of the ` ` Screen ` ` object this Location is inside .
Returns None if the Location isn ' t positioned in any screen .""" | from . RegionMatching import PlatformManager , Screen
screens = PlatformManager . getScreenDetails ( )
for screen in screens :
s_x , s_y , s_w , s_h = screen [ "rect" ]
if ( self . x >= s_x ) and ( self . x < s_x + s_w ) and ( self . y >= s_y ) and ( self . y < s_y + s_h ) : # Top left corner is inside screen r... |
def mapping_delete ( index , doc_type , hosts = None , profile = None ) :
'''Delete a mapping ( type ) along with its data . As of Elasticsearch 5.0 this is no longer available .
index
Index for the mapping
doc _ type
Name of the document type
CLI example : :
salt myminion elasticsearch . mapping _ dele... | es = _get_instance ( hosts , profile )
try :
result = es . indices . delete_mapping ( index = index , doc_type = doc_type )
return result . get ( 'acknowledged' , False )
except elasticsearch . exceptions . NotFoundError :
return True
except elasticsearch . TransportError as e :
raise CommandExecutionEr... |
def get_script_module ( script_information , package = 'pylabcontrol' , verbose = False ) :
"""wrapper to get the module for a script
Args :
script _ information : information of the script . This can be
- a dictionary
- a Script instance
- name of Script class
package ( optional ) : name of the package... | module , _ , _ , _ , _ , _ , _ = Script . get_script_information ( script_information = script_information , package = package , verbose = verbose )
return module |
def can_set_locale ( lc , lc_var = locale . LC_ALL ) :
"""Check to see if we can set a locale , and subsequently get the locale ,
without raising an Exception .
Parameters
lc : str
The locale to attempt to set .
lc _ var : int , default ` locale . LC _ ALL `
The category of the locale being set .
Retu... | try :
with set_locale ( lc , lc_var = lc_var ) :
pass
except ( ValueError , locale . Error ) : # horrible name for a Exception subclass
return False
else :
return True |
def run ( * args ) :
'''Run the normal shovel functionality''' | import os
import sys
import argparse
import pkg_resources
# First off , read the arguments
parser = argparse . ArgumentParser ( prog = 'shovel' , description = 'Rake, for Python' )
parser . add_argument ( 'method' , help = 'The task to run' )
parser . add_argument ( '--verbose' , dest = 'verbose' , action = 'store_true... |
def now ( self ) :
"""fetch the chart identified by this chart ' s now _ id attribute
if the now _ id is either null or not present for this chart return None
returns the new chart instance on sucess""" | try :
if self . now_id :
return Chart ( self . now_id )
else :
log . debug ( 'attempted to get current chart, but none was found' )
return
except AttributeError : # chart does not implement next pointer
log . debug ( 'attempted to get current ("now") chart from a chart without a now ... |
def download_run_and_upload ( job , master_ip , inputs , spark_on_toil ) :
"""Monolithic job that calls data download , conversion , transform , upload .
Previously , this was not monolithic ; change came in due to # 126 / # 134.""" | master_ip = MasterAddress ( master_ip )
bam_name = inputs . sample . split ( '://' ) [ - 1 ] . split ( '/' ) [ - 1 ]
sample_name = "." . join ( os . path . splitext ( bam_name ) [ : - 1 ] )
hdfs_subdir = sample_name + "-dir"
if inputs . run_local :
inputs . local_dir = job . fileStore . getLocalTempDir ( )
if i... |
def get_weekly_charts ( self , chart_kind , from_date = None , to_date = None ) :
"""Returns the weekly charts for the week starting from the
from _ date value to the to _ date value .
chart _ kind should be one of " album " , " artist " or " track " """ | method = ".getWeekly" + chart_kind . title ( ) + "Chart"
chart_type = eval ( chart_kind . title ( ) )
# string to type
params = self . _get_params ( )
if from_date and to_date :
params [ "from" ] = from_date
params [ "to" ] = to_date
doc = self . _request ( self . ws_prefix + method , True , params )
seq = [ ]
... |
def _validate_doc_refs ( self ) :
"""Validates that all the documentation references across every docstring
in every spec are formatted properly , have valid values , and make
references to valid symbols .""" | for namespace in self . api . namespaces . values ( ) :
env = self . _get_or_create_env ( namespace . name )
# Validate the doc refs of each api entity that has a doc
for data_type in namespace . data_types :
if data_type . doc :
self . _validate_doc_refs_helper ( env , data_type . doc ,... |
def urlnext ( parser , token ) :
"""{ % url % } copied from Django 1.7.""" | bits = token . split_contents ( )
if len ( bits ) < 2 :
raise template . TemplateSyntaxError ( "'%s' takes at least one argument" " (path to a view)" % bits [ 0 ] )
viewname = parser . compile_filter ( bits [ 1 ] )
args = [ ]
kwargs = { }
asvar = None
bits = bits [ 2 : ]
if len ( bits ) >= 2 and bits [ - 2 ] == "as... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.