signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get ( expr , key , default = None ) :
"""Return the mapped value for this key , or the default
if the key does not exist
Parameters
key : any
default : any""" | return ops . MapValueOrDefaultForKey ( expr , key , default ) . to_expr ( ) |
def start ( self ) :
'''Startup the zmq consumer .''' | zmq_uri = '{protocol}://{address}:{port}' . format ( protocol = self . protocol , address = self . address , port = self . port ) if self . port else '{protocol}://{address}' . format ( # noqa
protocol = self . protocol , address = self . address )
log . debug ( 'ZMQ URI: %s' , zmq_uri )
self . ctx = zmq . Context ( )
... |
def discrete_index ( self , indices ) :
"""get elements by discrete indices
: param indices : list
discrete indices
: return : elements""" | elements = [ ]
for i in indices :
elements . append ( self [ i ] )
return elements |
def from_json_dict ( cls , json_dict # type : Dict [ str , Any ]
) : # type : ( . . . ) - > IntegerSpec
"""Make a IntegerSpec object from a dictionary containing its
properties .
: param dict json _ dict : This dictionary may contain
` ' minimum ' ` and ` ' maximum ' ` keys . In addition , it must
contain a... | # noinspection PyCompatibility
result = cast ( IntegerSpec , # For Mypy .
super ( ) . from_json_dict ( json_dict ) )
format_ = json_dict [ 'format' ]
result . minimum = format_ . get ( 'minimum' )
result . maximum = format_ . get ( 'maximum' )
return result |
def signal ( signal = None ) :
'''Signals nginx to start , reload , reopen or stop .
CLI Example :
. . code - block : : bash
salt ' * ' nginx . signal reload''' | valid_signals = ( 'start' , 'reopen' , 'stop' , 'quit' , 'reload' )
if signal not in valid_signals :
return
# Make sure you use the right arguments
if signal == "start" :
arguments = ''
else :
arguments = ' -s {0}' . format ( signal )
cmd = __detect_os ( ) + arguments
out = __salt__ [ 'cmd.run_all' ] ( cmd ... |
def verify_is_none ( self , expr , msg = None ) :
"""Soft assert for whether the expr is None
: params want : the object to compare against
: params second : the object to compare with
: params msg : ( Optional ) msg explaining the difference""" | try :
self . assert_is_none ( expr , msg )
except AssertionError , e :
if msg :
m = "%s:\n%s" % ( msg , str ( e ) )
else :
m = str ( e )
self . verification_erorrs . append ( m ) |
def get_proof_generator ( self , tx_id , chain = Chain . bitcoin_mainnet ) :
"""Returns a generator ( 1 - time iterator ) of proofs in insertion order .
: param tx _ id : blockchain transaction id
: return :""" | root = ensure_string ( self . tree . get_merkle_root ( ) )
node_count = len ( self . tree . leaves )
for index in range ( 0 , node_count ) :
proof = self . tree . get_proof ( index )
proof2 = [ ]
for p in proof :
dict2 = dict ( )
for key , value in p . items ( ) :
dict2 [ key ] =... |
def format ( self ) :
"""Crop and resize the supplied image . Return the image and the crop _ box used .
If the input format is JPEG and in EXIF there is information about rotation , use it and rotate resulting image .""" | if hasattr ( self . image , '_getexif' ) :
self . rotate_exif ( )
crop_box = self . crop_to_ratio ( )
self . resize ( )
return self . image , crop_box |
def read ( self , size ) :
"""Read raw bytes from the instrument .
: param size : amount of bytes to be sent to the instrument
: type size : integer
: return : received bytes
: return type : bytes""" | raw_read = super ( USBRawDevice , self ) . read
received = bytearray ( )
while not len ( received ) >= size :
resp = raw_read ( self . RECV_CHUNK )
received . extend ( resp )
return bytes ( received ) |
def pt_rotate ( pt = ( 0.0 , 0.0 ) , angle = [ 0.0 ] , center = ( 0.0 , 0.0 ) ) :
'''Return given point rotated around a center point in N dimensions .
Angle is list of rotation in radians for each pair of axis .''' | assert isinstance ( pt , tuple )
l_pt = len ( pt )
assert l_pt > 1
for i in pt :
assert isinstance ( i , float )
assert isinstance ( angle , list )
l_angle = len ( angle )
assert l_angle == l_pt - 1
for i in angle :
assert isinstance ( i , float )
assert abs ( i ) <= 2 * pi
assert isinstance ( center , tupl... |
def to_networkx_graph ( H ) :
"""Returns a NetworkX Graph object that is the graph decomposition of
the given H .
See " to _ graph _ decomposition ( ) " for more details .
: param H : the H to decompose into a graph .
: returns : nx . Graph - - NetworkX Graph object representing the
decomposed H .
: rai... | import networkx as nx
if not isinstance ( H , UndirectedHypergraph ) :
raise TypeError ( "Transformation only applicable to \
undirected Hs" )
G = to_graph_decomposition ( H )
nx_graph = nx . Graph ( )
for node in G . node_iterator ( ) :
nx_graph . add_node ( node , G . get_node_attribut... |
def red ( self , value ) :
"""gets / sets the red value""" | if value != self . _red and isinstance ( value , int ) :
self . _red = value |
def login_oauth2 ( self , username , password , mfa_code = None ) :
'''Login using username and password''' | data = { "grant_type" : "password" , "scope" : "internal" , "client_id" : CLIENT_ID , "expires_in" : 86400 , "password" : password , "username" : username }
if mfa_code is not None :
data [ 'mfa_code' ] = mfa_code
url = "https://api.robinhood.com/oauth2/token/"
res = self . post ( url , payload = data , retry = Fal... |
def _no_access ( basedir ) :
'''Return True if the given base dir is not accessible or writeable''' | import os
return not os . access ( basedir , os . W_OK | os . X_OK ) |
def is_valid_int_param ( param ) :
"""Verifica se o parâmetro é um valor inteiro válido .
: param param : Valor para ser validado .
: return : True se o parâmetro tem um valor inteiro válido , ou False , caso contrário .""" | if param is None :
return False
try :
param = int ( param )
if param < 0 :
return False
except ( TypeError , ValueError ) :
return False
return True |
def cover ( self , minAcc , maxAcc , groupBy = None , new_reg_fields = None , cover_type = "normal" ) :
"""* Wrapper of * ` ` COVER ` `
COVER is a GMQL operator that takes as input a dataset ( of usually ,
but not necessarily , multiple samples ) and returns another dataset
( with a single sample , if no grou... | if isinstance ( cover_type , str ) :
coverFlag = self . opmng . getCoverTypes ( cover_type )
else :
raise TypeError ( "type must be a string. " "{} was provided" . format ( type ( cover_type ) ) )
if isinstance ( minAcc , str ) :
minAccParam = self . opmng . getCoverParam ( minAcc . lower ( ) )
elif isinsta... |
def unindent ( self ) :
"""Un - indents text at cursor position .""" | _logger ( ) . debug ( 'unindent' )
cursor = self . editor . textCursor ( )
_logger ( ) . debug ( 'cursor has selection %r' , cursor . hasSelection ( ) )
if cursor . hasSelection ( ) :
cursor . beginEditBlock ( )
self . unindent_selection ( cursor )
cursor . endEditBlock ( )
self . editor . setTextCursor... |
def setup ( self , universe ) :
"""Setup Security with universe . Speeds up future runs .
Args :
* universe ( DataFrame ) : DataFrame of prices with security ' s name as
one of the columns .""" | # if we already have all the prices , we will store them to speed up
# future updates
try :
prices = universe [ self . name ]
except KeyError :
prices = None
# setup internal data
if prices is not None :
self . _prices = prices
self . data = pd . DataFrame ( index = universe . index , columns = [ 'value... |
def _create_dir ( path ) :
'''Creates necessary directories for the given path or does nothing
if the directories already exist .''' | try :
os . makedirs ( path )
except OSError , exc :
if exc . errno == errno . EEXIST :
pass
else :
raise |
def rates_for_location ( self , postal_code , location_deets = None ) :
"""Shows the sales tax rates for a given location .""" | request = self . _get ( "rates/" + postal_code , location_deets )
return self . responder ( request ) |
def close ( self ) :
"""Called to clean all possible tmp files created during the process .""" | if self . read_option ( 'save_pointer' ) :
self . _update_last_pointer ( )
super ( S3Writer , self ) . close ( ) |
def _set_interface_hello_padding ( self , v , load = False ) :
"""Setter method for interface _ hello _ padding , mapped from YANG variable / routing _ system / interface / ve / intf _ isis / interface _ isis / interface _ hello / interface _ hello _ padding ( container )
If this variable is read - only ( config ... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = interface_hello_padding . interface_hello_padding , is_container = 'container' , presence = False , yang_name = "interface-hello-padding" , rest_name = "padding" , parent = self , path_helper = self . _path_helper , extmethod... |
def make_parameter_dict ( pdict , fixed_par = False , rescale = True , update_bounds = False ) :
"""Update a parameter dictionary . This function will automatically
set the parameter scale and bounds if they are not defined .
Bounds are also adjusted to ensure that they encompass the
parameter value .""" | o = copy . deepcopy ( pdict )
o . setdefault ( 'scale' , 1.0 )
if rescale :
value , scale = utils . scale_parameter ( o [ 'value' ] * o [ 'scale' ] )
o [ 'value' ] = np . abs ( value ) * np . sign ( o [ 'value' ] )
o [ 'scale' ] = np . abs ( scale ) * np . sign ( o [ 'scale' ] )
if 'error' in o :
... |
def validate_bam ( self , input_bam ) :
"""Wrapper for Picard ' s ValidateSamFile .
: param str input _ bam : Path to file to validate .
: return str : Command to run for the validation .""" | cmd = self . tools . java + " -Xmx" + self . pm . javamem
cmd += " -jar " + self . tools . picard + " ValidateSamFile"
cmd += " INPUT=" + input_bam
return cmd |
def update_cluster ( cluster_dict , datacenter = None , cluster = None , service_instance = None ) :
'''Updates a cluster .
config _ dict
Dictionary with the config values of the new cluster .
datacenter
Name of datacenter containing the cluster .
Ignored if already contained by proxy details .
Default ... | # Validate cluster dictionary
schema = ESXClusterConfigSchema . serialize ( )
try :
jsonschema . validate ( cluster_dict , schema )
except jsonschema . exceptions . ValidationError as exc :
raise InvalidConfigError ( exc )
# Get required details from the proxy
proxy_type = get_proxy_type ( )
if proxy_type == 'e... |
def get_service ( raw_xml ) :
"""Set a service object based on the XML metadata
< dct : references scheme = " OGC : WMS " > http : / / ngamaps . geointapps . org / arcgis
/ services / RIO / Rio _ Foundation _ Transportation / MapServer / WMSServer
< / dct : references >
: param instance :
: return : Layer... | from pycsw . core . etree import etree
parsed = etree . fromstring ( raw_xml , etree . XMLParser ( resolve_entities = False ) )
# < dc : format > OGC : WMS < / dc : format >
source_tag = parsed . find ( "{http://purl.org/dc/elements/1.1/}source" )
# < dc : source >
# http : / / ngamaps . geointapps . org / arcgis / ser... |
def replant_tree ( self , config = None , exclude = None ) :
'''Replant the tree with a different config setup
Parameters :
config ( str ) :
The config name to reload
exclude ( list ) :
A list of environment variables to exclude
from forced updates''' | # reinitialize a new Tree with a new config
self . __init__ ( key = self . key , config = config , update = True , exclude = exclude ) |
def get_login_password ( site_name = "github.com" , netrc_file = "~/.netrc" , git_credential_file = "~/.git-credentials" ) :
"""Read a . netrc file and return login / password for LWN .""" | try :
n = netrc . netrc ( os . path . expanduser ( netrc_file ) )
except OSError :
pass
else :
if site_name in n . hosts :
return n . hosts [ site_name ] [ 0 ] , n . hosts [ site_name ] [ 2 ]
try :
with open ( os . path . expanduser ( git_credential_file ) ) as f :
for line in f :
... |
def subdir_path ( directory , relative ) :
"""Returns a file path relative to another path .""" | item_bits = directory . split ( os . sep )
relative_bits = relative . split ( os . sep )
for i , _item in enumerate ( item_bits ) :
if i == len ( relative_bits ) - 1 :
return os . sep . join ( item_bits [ i : ] )
else :
if item_bits [ i ] != relative_bits [ i ] :
return None
return N... |
def list_operations ( self , name , filter_ , page_size = 0 , options = None ) :
"""Lists operations that match the specified filter in the request . If the
server doesn ' t support this method , it returns ` ` UNIMPLEMENTED ` ` .
NOTE : the ` ` name ` ` binding below allows API services to override the binding... | # Create the request object .
request = operations_pb2 . ListOperationsRequest ( name = name , filter = filter_ , page_size = page_size )
return self . _list_operations ( request , options ) |
def release ( self ) :
"""Release file and thread locks . If in ' degraded ' mode , close the
stream to reduce contention until the log files can be rotated .""" | try :
if self . _rotateFailed :
self . _close ( )
except Exception :
self . handleError ( NullLogRecord ( ) )
finally :
try :
if self . stream_lock and not self . stream_lock . closed :
unlock ( self . stream_lock )
except Exception :
self . handleError ( NullLogRecor... |
async def _find_trigger ( self , request : Request , origin : Optional [ Text ] = None , internal : bool = False ) -> Tuple [ Optional [ BaseTrigger ] , Optional [ Type [ BaseState ] ] , Optional [ bool ] , ] :
"""Find the best trigger for this request , or go away .""" | reg = request . register
if not origin :
origin = reg . get ( Register . STATE )
logger . debug ( 'From state: %s' , origin )
results = await asyncio . gather ( * ( x . rank ( request , origin ) for x in self . transitions if x . internal == internal ) )
if len ( results ) :
score , trigger , state , dnr = ... |
def update ( self , table , values , identifier ) :
"""Updates a table row with specified data by given identifier .
: param table : the expression of the table to update quoted or unquoted
: param values : a dictionary containing column - value pairs
: param identifier : the update criteria ; a dictionary co... | with self . locked ( ) as conn :
return conn . update ( table , values , identifier ) |
def get ( self , position ) :
"""Gets value at index
: param position : index
: return : value at position""" | counter = 0
current_node = self . head
while current_node is not None and counter <= position :
if counter == position :
return current_node . val
current_node = current_node . next_node
counter += 1
return None |
def load_model ( model_name , epoch_num , data_shapes , label_shapes , label_names , gpus = '' ) :
"""Returns a module loaded with the provided model .
Parameters
model _ name : str
Prefix of the MXNet model name as stored on the local directory .
epoch _ num : int
Epoch number of model we would like to l... | sym , arg_params , aux_params = mx . model . load_checkpoint ( model_name , epoch_num )
mod = create_module ( sym , data_shapes , label_shapes , label_names , gpus )
mod . set_params ( arg_params = arg_params , aux_params = aux_params , allow_missing = True )
return mod |
def model_action_q_dist ( self ) :
"""Action values for selected actions in the rollout""" | q = self . get ( 'model:q_dist' )
actions = self . get ( 'rollout:actions' )
return q [ range ( q . size ( 0 ) ) , actions ] |
def set_attribute_string_array ( target , name , string_list ) :
"""Sets an attribute to an array of string on a Dataset or Group .
If the attribute ` name ` doesn ' t exist yet , it is created . If it
already exists , it is overwritten with the list of string
` string _ list ` ( they will be vlen strings ) .... | s_list = [ convert_to_str ( s ) for s in string_list ]
if sys . hexversion >= 0x03000000 :
target . attrs . create ( name , s_list , dtype = h5py . special_dtype ( vlen = str ) )
else :
target . attrs . create ( name , s_list , dtype = h5py . special_dtype ( vlen = unicode ) ) |
def remove ( self , builder , model ) :
"""Remove the scope from a given query builder .
: param builder : The query builder
: type builder : eloquent . orm . builder . Builder
: param model : The model
: type model : eloquent . orm . Model""" | column = model . get_qualified_deleted_at_column ( )
query = builder . get_query ( )
wheres = [ ]
for where in query . wheres : # If the where clause is a soft delete date constraint ,
# we will remove it from the query and reset the keys
# on the wheres . This allows the developer to include
# deleted model in a relat... |
def list_entries ( self , projects = None , filter_ = None , order_by = None , page_size = None , page_token = None , ) :
"""Return a page of log entries .
See
https : / / cloud . google . com / logging / docs / reference / v2 / rest / v2 / entries / list
: type projects : list of strings
: param projects :... | log_filter = "logName=%s" % ( self . full_name , )
if filter_ is not None :
filter_ = "%s AND %s" % ( filter_ , log_filter )
else :
filter_ = log_filter
return self . client . list_entries ( projects = projects , filter_ = filter_ , order_by = order_by , page_size = page_size , page_token = page_token , ) |
def file_list ( blockchain_id , config_path = CONFIG_PATH , wallet_keys = None ) :
"""List all files uploaded to a particular blockchain ID
Return { ' status ' : True , ' listing ' : list } on success
Return { ' error ' : . . . } on error""" | config_dir = os . path . dirname ( config_path )
client_config_path = os . path . join ( config_dir , blockstack_client . CONFIG_FILENAME )
proxy = blockstack_client . get_default_proxy ( config_path = client_config_path )
res = blockstack_client . data_list ( blockchain_id , wallet_keys = wallet_keys , proxy = proxy )... |
def set_item_class_name_on_custom_generator_class ( cls ) :
"""Set the attribute ` cls . _ _ tohu _ items _ name _ _ ` to a string which defines the name
of the namedtuple class which will be used to produce items for the custom
generator .
By default this will be the first part of the class name ( before ' .... | if '__tohu__items__name__' in cls . __dict__ :
logger . debug ( f"Using item class name '{cls.__tohu_items_name__}' (derived from attribute '__tohu_items_name__')" )
else :
m = re . match ( '^(.*)Generator$' , cls . __name__ )
if m is not None :
cls . __tohu_items_name__ = m . group ( 1 )
lo... |
def ValidateTimezone ( timezone , column_name = None , problems = None ) :
"""Validates a non - required timezone string value using IsValidTimezone ( ) :
- if invalid adds InvalidValue error ( if problems accumulator is provided )
- an empty timezone string is regarded as valid ! Otherwise we might end up
wi... | if IsEmpty ( timezone ) or IsValidTimezone ( timezone ) :
return True
else :
if problems : # if we get here pytz has already been imported successfully in
# IsValidTimezone ( ) . So a try - except block is not needed here .
import pytz
problems . InvalidValue ( column_name , timezone , '"%s"... |
def addTile ( self , value = None , choices = None ) :
"""add a random tile in an empty cell
value : value of the tile to add .
choices : a list of possible choices for the value of the tile . if
` ` None ` ` ( the default ) , it uses
` ` [ 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 2 , 4 ] ` ` .""" | if choices is None :
choices = [ 2 ] * 9 + [ 4 ]
if value :
choices = [ value ]
v = random . choice ( choices )
empty = self . getEmptyCells ( )
if empty :
x , y = random . choice ( empty )
self . setCell ( x , y , v ) |
def parse_header ( filename ) :
'''Returns a list of : attr : ` VariableSpec ` , : attr : ` FunctionSpec ` ,
: attr : ` StructSpec ` , : attr : ` EnumSpec ` , : attr : ` EnumMemberSpec ` , and
: attr : ` TypeDef ` instances representing the c header file .''' | with open ( filename , 'rb' ) as fh :
content = '\n' . join ( fh . read ( ) . splitlines ( ) )
content = sub ( '\t' , ' ' , content )
content = strip_comments ( content )
# first get the functions
content = split ( func_pat_short , content )
for i , s in enumerate ( content ) :
if i % 2 and content [ i ] . stri... |
def authenticationAndCipheringReject ( ) :
"""AUTHENTICATION AND CIPHERING REJECT Section 9.4.11""" | a = TpPd ( pd = 0x3 )
b = MessageType ( mesType = 0x14 )
# 00010100
packet = a / b
return packet |
def connection ( self ) :
"""identify the remote connection parameters""" | self . getPorts ( )
# acquire if necessary
self . getIPaddresses ( )
# acquire if necessary
return ( self . ipAddress , self . ports ) |
def update ( self , f ) :
"""Copy another files properties into this one .""" | for p in self . __mapper__ . attrs :
if p . key == 'oid' :
continue
try :
setattr ( self , p . key , getattr ( f , p . key ) )
except AttributeError : # The dict ( ) method copies data property values into the main dict ,
# and these don ' t have associated class properties .
con... |
def autobuild_documentation ( tile ) :
"""Generate documentation for this module using a combination of sphinx and breathe""" | docdir = os . path . join ( '#doc' )
docfile = os . path . join ( docdir , 'conf.py' )
outdir = os . path . join ( 'build' , 'output' , 'doc' , tile . unique_id )
outfile = os . path . join ( outdir , '%s.timestamp' % tile . unique_id )
env = Environment ( ENV = os . environ , tools = [ ] )
# Only build doxygen documen... |
def staged_rewards ( self ) :
"""Helper function to return staged rewards based on current physical states .
Returns :
r _ reach ( float ) : reward for reaching and grasping
r _ lift ( float ) : reward for lifting and aligning
r _ stack ( float ) : reward for stacking""" | # reaching is successful when the gripper site is close to
# the center of the cube
cubeA_pos = self . sim . data . body_xpos [ self . cubeA_body_id ]
cubeB_pos = self . sim . data . body_xpos [ self . cubeB_body_id ]
gripper_site_pos = self . sim . data . site_xpos [ self . eef_site_id ]
dist = np . linalg . norm ( gr... |
def export_users ( path_prefix = '/' , region = None , key = None , keyid = None , profile = None ) :
'''Get all IAM user details . Produces results that can be used to create an
sls file .
. . versionadded : : 2016.3.0
CLI Example :
salt - call boto _ iam . export _ users - - out = txt | sed " s / local : ... | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if not conn :
return None
results = odict . OrderedDict ( )
users = get_all_users ( path_prefix , region , key , keyid , profile )
for user in users :
name = user . user_name
_policies = conn . get_all_user_policies ( name ... |
def get_settings ( profile , section , store = 'local' ) :
'''Get the firewall property from the specified profile in the specified store
as returned by ` ` netsh advfirewall ` ` .
. . versionadded : : 2018.3.4
. . versionadded : : 2019.2.0
Args :
profile ( str ) :
The firewall profile to query . Valid ... | return salt . utils . win_lgpo_netsh . get_settings ( profile = profile , section = section , store = store ) |
def add_link ( self ) :
"Create a new internal link" | n = len ( self . links ) + 1
self . links [ n ] = ( 0 , 0 )
return n |
def search_titles ( self , title ) :
"""Search for titles matching the ` title ` .
: param str title : the title to search for .
: return : found titles .
: rtype : dict""" | # make the query
logger . info ( 'Searching title %r' , title )
r = self . session . get ( self . server_url + 'legenda/sugestao/{}' . format ( title ) , timeout = 10 )
r . raise_for_status ( )
results = json . loads ( r . text )
# loop over results
titles = { }
for result in results :
source = result [ '_source' ]... |
def _container_candidates ( self ) :
"""Generate container candidate list
Returns :
tuple list : [ ( width1 , height1 ) , ( width2 , height2 ) , . . . ]""" | if not self . _rectangles :
return [ ]
if self . _rotation :
sides = sorted ( side for rect in self . _rectangles for side in rect )
max_height = sum ( max ( r [ 0 ] , r [ 1 ] ) for r in self . _rectangles )
min_width = max ( min ( r [ 0 ] , r [ 1 ] ) for r in self . _rectangles )
max_width = max_he... |
def make_ring_dicts ( ** kwargs ) :
"""Build and return the information about the Galprop rings""" | library_yamlfile = kwargs . get ( 'library' , 'models/library.yaml' )
gmm = kwargs . get ( 'GalpropMapManager' , GalpropMapManager ( ** kwargs ) )
if library_yamlfile is None or library_yamlfile == 'None' :
return gmm
diffuse_comps = DiffuseModelManager . read_diffuse_component_yaml ( library_yamlfile )
for diffuse... |
def add_task ( self , task ) :
"""Schedule a task to run later , after the loop has started .
Different from asyncio . ensure _ future in that it does not
also return a future , and the actual ensure _ future call
is delayed until before server start .
: param task : future , couroutine or awaitable""" | try :
if callable ( task ) :
try :
self . loop . create_task ( task ( self ) )
except TypeError :
self . loop . create_task ( task ( ) )
else :
self . loop . create_task ( task )
except SanicException :
@ self . listener ( "before_server_start" )
def run (... |
def teletex_search_function ( name ) :
"""Search function for teletex codec that is passed to codecs . register ( )""" | if name != 'teletex' :
return None
return codecs . CodecInfo ( name = 'teletex' , encode = TeletexCodec ( ) . encode , decode = TeletexCodec ( ) . decode , incrementalencoder = TeletexIncrementalEncoder , incrementaldecoder = TeletexIncrementalDecoder , streamreader = TeletexStreamReader , streamwriter = TeletexStr... |
def dagger ( self , inv_dict = None , suffix = "-INV" ) :
"""Creates the conjugate transpose of the Quil program . The program must not
contain any irreversible actions ( measurement , control flow , qubit allocation ) .
: return : The Quil program ' s inverse
: rtype : Program""" | if not self . is_protoquil ( ) :
raise ValueError ( "Program must be valid Protoquil" )
daggered = Program ( )
for gate in self . _defined_gates :
if inv_dict is None or gate . name not in inv_dict :
if gate . parameters :
raise TypeError ( "Cannot auto define daggered version of parameteriz... |
def tokenize_argument ( text ) :
"""Process both optional and required arguments .
: param Buffer text : iterator over line , with current position""" | for delim in ARG_TOKENS :
if text . startswith ( delim ) :
return text . forward ( len ( delim ) ) |
def service_per_endpoint ( self , context = None ) :
"""List all endpoint this entity publishes and which service and binding
that are behind the endpoint
: param context : Type of entity
: return : Dictionary with endpoint url as key and a tuple of
service and binding as value""" | endps = self . getattr ( "endpoints" , context )
res = { }
for service , specs in endps . items ( ) :
for endp , binding in specs :
res [ endp ] = ( service , binding )
return res |
def get ( cls , dbname = "perfdump" ) :
"""Returns the singleton connection to the SQLite3 database .
: param dbname : The database name
: type dbname : str""" | try :
return cls . connection
except :
cls . connect ( dbname )
return cls . connection |
def set_size ( self , name : str , size : int ) :
"""Set the size of a resource in the RSTB .""" | if self . _needs_to_be_in_name_map ( name ) :
if len ( name ) >= 128 :
raise ValueError ( "Name is too long" )
self . name_map [ name ] = size
else :
crc32 = binascii . crc32 ( name . encode ( ) )
self . crc32_map [ crc32 ] = size |
def getMoviesFromJSON ( jsonURL ) :
"""Main function for this library
Returns list of Movie classes from apple . com / trailers json URL
such as : http : / / trailers . apple . com / trailers / home / feeds / just _ added . json
The Movie classes use lazy loading mechanisms so that data not
directly availab... | response = urllib . request . urlopen ( jsonURL )
jsonData = response . read ( ) . decode ( 'utf-8' )
objects = json . loads ( jsonData )
# make it work for search urls
if jsonURL . find ( 'quickfind' ) != - 1 :
objects = objects [ 'results' ]
optionalInfo = [ 'actors' , 'directors' , 'rating' , 'genre' , 'studio' ... |
def sanitize_type ( raw_type ) :
"""Sanitize the raw type string .""" | cleaned = get_printable ( raw_type ) . strip ( )
for bad in [ r'__drv_aliasesMem' , r'__drv_freesMem' , r'__drv_strictTypeMatch\(\w+\)' , r'__out_data_source\(\w+\)' , r'_In_NLS_string_\(\w+\)' , r'_Frees_ptr_' , r'_Frees_ptr_opt_' , r'opt_' , r'\(Mem\) ' ] :
cleaned = re . sub ( bad , '' , cleaned ) . strip ( )
if... |
def accuracy ( y , z ) :
"""Classification accuracy ` ( tp + tn ) / ( tp + tn + fp + fn ) `""" | tp , tn , fp , fn = contingency_table ( y , z )
return ( tp + tn ) / ( tp + tn + fp + fn ) |
def get_unread_topics ( self , topics , user ) :
"""Returns a list of unread topics for the given user from a given set of topics .""" | unread_topics = [ ]
# A user which is not authenticated will never see a topic as unread .
# If there are no topics to consider , we stop here .
if not user . is_authenticated or topics is None or not len ( topics ) :
return unread_topics
# A topic can be unread if a track for itself exists with a mark time that
# ... |
def _load_generic ( packname , package , section , target ) :
"""Loads the settings for generic options that take FQDN and a boolean value
(1 or 0 ) .
Args :
packname ( str ) : name of the package to get config settings for .
package : actual package object .""" | from acorn . config import settings
spack = settings ( packname )
if spack . has_section ( section ) :
secitems = dict ( spack . items ( section ) )
for fqdn , active in secitems . items ( ) :
target [ fqdn ] = active == "1" |
def remember ( self , key , minutes , callback ) :
"""Get an item from the cache , or store the default value .
: param key : The cache key
: type key : str
: param minutes : The lifetime in minutes of the cached value
: type minutes : int or datetime
: param callback : The default function
: type callb... | # If the item exists in the cache we will just return this immediately
# otherwise we will execute the given callback and cache the result
# of that execution for the given number of minutes in storage .
val = self . get ( key )
if val is not None :
return val
val = value ( callback )
self . put ( key , val , minut... |
def fit_freq_std_dev ( self , training_signal ) :
"""Defines a spectral mask based on training data using the standard deviation values of
each frequency component
Args :
training _ signal : Training data""" | window_length = len ( self . window )
window_weight = sum ( self . window )
num_of_windows = len ( training_signal ) - window_length - 1
mean = np . zeros ( int ( window_length / 2 ) + 1 )
pow = np . zeros ( int ( window_length / 2 ) + 1 )
temp = np . zeros ( int ( window_length / 2 ) + 1 )
rfft = np . fft . rfft ( tra... |
def get_template_name ( self , template_name ) :
"""Returns template path , either from a shortcut built - in template
name ( ` form _ as _ p ` ) or a template path ( ` my _ sitegate / my _ tpl . html ` ) .
Note that template path can include one ` % s ` placeholder . In that case
it will be replaced with flo... | if template_name is None : # Build default template path .
template_name = self . default_form_template
if '.html' not in template_name : # Shortcut , e . g . : .
template_name = '%s%s.html' % ( 'sitegate/%s/' , template_name )
if '%s' in template_name : # Fill in the flow type placeholder .
template_name =... |
def _get_query ( self , query , params ) :
"""Submit a GET request to the VT API
: param query : The query ( see https : / / www . virustotal . com / en / documentation / private - api / for types of queries )
: param params : parameters of the query
: return : JSON formatted response from the API""" | if "apikey" not in params :
params [ "apikey" ] = self . api_key
response = requests . get ( query , params = params )
return response . json ( ) |
def blogurl ( parser , token ) :
"""Compatibility tag to allow django - fluent - blogs to operate stand - alone .
Either the app can be hooked in the URLconf directly , or it can be added as a pagetype of django - fluent - pages .
For the former , URL resolving works via the normal ' { % url " viewname " arg1 a... | if HAS_APP_URLS :
from fluent_pages . templatetags . appurl_tags import appurl
return appurl ( parser , token )
else :
from django . template . defaulttags import url
return url ( parser , token ) |
def get_label_cls ( self , labels , label_cls : Callable = None , label_delim : str = None , ** kwargs ) :
"Return ` label _ cls ` or guess one from the first element of ` labels ` ." | if label_cls is not None :
return label_cls
if self . label_cls is not None :
return self . label_cls
if label_delim is not None :
return MultiCategoryList
it = index_row ( labels , 0 )
if isinstance ( it , ( float , np . float32 ) ) :
return FloatList
if isinstance ( try_int ( it ) , ( str , Integral )... |
def merge_vertices ( self , digits = None ) :
"""Merges vertices which are identical and replace references .
Parameters
digits : None , or int
How many digits to consider when merging vertices
Alters
self . entities : entity . points re - referenced
self . vertices : duplicates removed""" | if len ( self . vertices ) == 0 :
return
if digits is None :
digits = util . decimal_to_digits ( tol . merge * self . scale , min_digits = 1 )
unique , inverse = grouping . unique_rows ( self . vertices , digits = digits )
self . vertices = self . vertices [ unique ]
entities_ok = np . ones ( len ( self . entit... |
def get_any_nt_unit_rule ( g ) :
"""Returns a non - terminal unit rule from ' g ' , or None if there is none .""" | for rule in g . rules :
if len ( rule . rhs ) == 1 and isinstance ( rule . rhs [ 0 ] , NT ) :
return rule
return None |
def _construct_nx_tree ( self , thisTree , thatTree = None ) :
"""A function for creating networkx instances that can be used
more efficiently for graph manipulation than the MergeTree
class .
@ In , thisTree , a MergeTree instance for which we will
construct a networkx graph
@ In , thatTree , a MergeTree... | if self . debug :
sys . stdout . write ( "Networkx Tree construction: " )
start = time . clock ( )
nxTree = nx . DiGraph ( )
nxTree . add_edges_from ( thisTree . edges )
nodesOfThatTree = [ ]
if thatTree is not None :
nodesOfThatTree = thatTree . nodes . keys ( )
# Fully or partially augment the join tree
f... |
def check_thresholds ( self , service = None , use_ta = True ) :
"""Check all limits and current usage against their specified thresholds ;
return all : py : class : ` ~ . AwsLimit ` instances that have crossed
one or more of their thresholds .
If ` ` service ` ` is specified , the returned dict has one eleme... | res = { }
to_get = self . services
if service is not None :
to_get = dict ( ( each , self . services [ each ] ) for each in service )
if use_ta :
self . ta . update_limits ( )
for sname , cls in to_get . items ( ) :
if hasattr ( cls , '_update_limits_from_api' ) :
cls . _update_limits_from_api ( )
... |
def _get_files_config ( src_dir , files_list ) :
"""Construct ` FileConfig ` object and return a list .
: param src _ dir : A string containing the source directory .
: param files _ list : A list of dicts containing the src / dst mapping of files
to overlay .
: return : list""" | FilesConfig = collections . namedtuple ( 'FilesConfig' , [ 'src' , 'dst' , 'post_commands' ] )
return [ FilesConfig ( ** d ) for d in _get_files_generator ( src_dir , files_list ) ] |
def index ( config , date = None , directory = None , concurrency = 5 , accounts = None , tag = None , verbose = False ) :
"""index traildbs directly from s3 for multiple accounts .
context : assumes a daily traildb file in s3 with dated key path""" | logging . basicConfig ( level = ( verbose and logging . DEBUG or logging . INFO ) )
logging . getLogger ( 'botocore' ) . setLevel ( logging . WARNING )
logging . getLogger ( 'elasticsearch' ) . setLevel ( logging . WARNING )
logging . getLogger ( 'urllib3' ) . setLevel ( logging . WARNING )
logging . getLogger ( 'reque... |
def bus_line_names ( self ) :
"""Append bus injection and line flow names to ` varname `""" | if self . system . tds . config . compute_flows :
self . system . Bus . _varname_inj ( )
self . system . Line . _varname_flow ( )
self . system . Area . _varname_inter ( ) |
def _execute_sql_query ( self ) :
"""* execute sql query using the sdss API *
* * Key Arguments : * *
* * Return : * *
- None
. . todo : :""" | self . log . info ( 'starting the ``_execute_sql_query`` method' )
# generate the api call url
params = urllib . urlencode ( { 'cmd' : self . sqlQuery , 'format' : "json" } )
# grab the results
results = urllib . urlopen ( self . sdssUrl + '?%s' % params )
# report any errors
ofp = sys . stdout
results = results . read... |
def format_values ( self ) :
"""Returns a string with all args and settings and where they came from
( eg . commandline , config file , enviroment variable or default )""" | source_key_to_display_value_map = { _COMMAND_LINE_SOURCE_KEY : "Command Line Args: " , _ENV_VAR_SOURCE_KEY : "Environment Variables:\n" , _CONFIG_FILE_SOURCE_KEY : "Config File (%s):\n" , _DEFAULTS_SOURCE_KEY : "Defaults:\n" }
r = StringIO ( )
for source , settings in self . _source_to_settings . items ( ) :
source... |
def preferences ( self , section = None ) :
"""Return a list of all registered preferences
or a list of preferences registered for a given section
: param section : The section name under which the preference is registered
: type section : str .
: return : a list of : py : class : ` prefs . BasePreference `... | if section is None :
return [ self [ section ] [ name ] for section in self for name in self [ section ] ]
else :
return [ self [ section ] [ name ] for name in self [ section ] ] |
def trade_history ( self , from_ = None , count = None , from_id = None , end_id = None , order = None , since = None , end = None , pair = None ) :
"""Returns trade history .
To use this method you need a privilege of the info key .
: param int or None from _ : trade ID , from which the display starts ( defaul... | return self . _trade_api_call ( 'TradeHistory' , from_ = from_ , count = count , from_id = from_id , end_id = end_id , order = order , since = since , end = end , pair = pair ) |
def get_all_domains ( self , max_domains = None , next_token = None ) :
"""Returns a : py : class : ` boto . resultset . ResultSet ` containing
all : py : class : ` boto . sdb . domain . Domain ` objects associated with
this connection ' s Access Key ID .
: keyword int max _ domains : Limit the returned
: p... | params = { }
if max_domains :
params [ 'MaxNumberOfDomains' ] = max_domains
if next_token :
params [ 'NextToken' ] = next_token
return self . get_list ( 'ListDomains' , params , [ ( 'DomainName' , Domain ) ] ) |
def _build ( self , memory , query , memory_mask = None ) :
"""Perform a differentiable read .
Args :
memory : [ batch _ size , memory _ size , memory _ word _ size ] - shaped Tensor of
dtype float32 . This represents , for each example and memory slot , a
single embedding to attend over .
query : [ batch... | if len ( memory . get_shape ( ) ) != 3 :
raise base . IncompatibleShapeError ( "memory must have shape [batch_size, memory_size, memory_word_size]." )
if len ( query . get_shape ( ) ) != 2 :
raise base . IncompatibleShapeError ( "query must have shape [batch_size, query_word_size]." )
if memory_mask is not None... |
def submit_file_content ( self , method , url , data , headers , params , halt_on_error = True ) :
"""Submit File Content for Documents and Reports to ThreatConnect API .
Args :
method ( str ) : The HTTP method for the request ( POST , PUT ) .
url ( str ) : The URL for the request .
data ( str ; bytes ; fil... | r = None
try :
r = self . tcex . session . request ( method , url , data = data , headers = headers , params = params )
except Exception as e :
self . tcex . handle_error ( 580 , [ e ] , halt_on_error )
return r |
def _validate_x ( self , x , z ) :
"""Validates x ( column ) , raising error if invalid .""" | if ( x < 0 ) or ( x > ( ( 2 ** z ) - 1 ) ) :
raise InvalidColumnError ( "{} is not a valid value for x (column)" . format ( x ) )
return x |
def set_url ( self , url ) :
"""Set the URL referring to a robots . txt file .""" | self . url = url
self . host , self . path = urlparse . urlparse ( url ) [ 1 : 3 ] |
def permission_update ( self , token , id , ** kwargs ) :
"""To update an existing permission .
https : / / www . keycloak . org / docs / latest / authorization _ services / index . html # _ service _ authorization _ uma _ policy _ api
: param str token : client access token
: param str id : permission id
:... | return self . _realm . client . put ( '{}/{}' . format ( self . well_known [ 'policy_endpoint' ] , id ) , data = self . _dumps ( kwargs ) , headers = self . get_headers ( token ) ) |
def MakePmfFromHist ( hist , name = None ) :
"""Makes a normalized PMF from a Hist object .
Args :
hist : Hist object
name : string name
Returns :
Pmf object""" | if name is None :
name = hist . name
# make a copy of the dictionary
d = dict ( hist . GetDict ( ) )
pmf = Pmf ( d , name )
pmf . Normalize ( )
return pmf |
def command_ls ( self ) :
"""List names""" | self . parser = argparse . ArgumentParser ( description = "List names of available objects" )
self . options_select ( )
self . options_utils ( )
self . options = self . parser . parse_args ( self . arguments [ 2 : ] )
self . show ( brief = True ) |
def finalize ( self ) :
"""Connects the wires .""" | self . _check_finalized ( )
self . _final = True
for dest_w , values in self . dest_instrs_info . items ( ) :
mux_vals = dict ( zip ( self . instructions , values ) )
dest_w <<= sparse_mux ( self . signal_wire , mux_vals ) |
def get_file_results ( self ) :
"""Print the result and return the overall count for this file .""" | self . _deferred_print . sort ( )
for line_number , offset , code , text , doc in self . _deferred_print :
print ( self . _fmt % { 'path' : self . filename , 'row' : self . line_offset + line_number , 'col' : offset + 1 , 'code' : code , 'text' : text , } )
if self . _show_source :
if line_number > len ... |
def _check_status ( func , read_exception , * args , ** kwargs ) :
"""Checks the status of a single component by
calling the func with the args . The func is expected to
return a dict with at least an ` available = < bool > ` key
value pair
: param func func : The function to call
: param read _ exception... | try :
return func ( * args , ** kwargs )
except Exception as e :
_LOG . exception ( e )
message = str ( e ) if read_exception else 'An error occurred while checking the status'
return dict ( message = message , available = False ) |
def printlet ( flatten = False , ** kwargs ) :
"""Print chunks of data from a chain
: param flatten : whether to flatten data chunks
: param kwargs : keyword arguments as for : py : func : ` print `
If ` ` flatten ` ` is : py : const : ` True ` , every chunk received is unpacked .
This is useful when passin... | chunk = yield
if flatten :
while True :
print ( * chunk , ** kwargs )
chunk = yield chunk
else :
while True :
print ( chunk , ** kwargs )
chunk = yield chunk |
def Parse ( self , value ) :
"""Parse a ' Value ' declaration .
Args :
value : String line from a template file , must begin with ' Value ' .
Raises :
TextFSMTemplateError : Value declaration contains an error .""" | value_line = value . split ( ' ' )
if len ( value_line ) < 3 :
raise TextFSMTemplateError ( 'Expect at least 3 tokens on line.' )
if not value_line [ 2 ] . startswith ( '(' ) : # Options are present
options = value_line [ 1 ]
for option in options . split ( ',' ) :
self . _AddOption ( option )
#... |
def _getPWMFrequency ( self , device , message ) :
"""Get the PWM frequency stored on the hardware device .
: Parameters :
device : ` int `
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol .
message : ` bool `
If set to ` True ` a text message will be... | result = self . _getConfig ( self . PWM_PARAM , device )
freq , msg = self . _CONFIG_PWM . get ( result , ( result , 'Invalid Frequency' ) )
if message :
result = msg
else :
result = freq
return result |
def as_dict ( self ) :
"""Json - serializable dict representation .""" | structure = self . final_structure
d = { "has_gaussian_completed" : self . properly_terminated , "nsites" : len ( structure ) }
comp = structure . composition
d [ "unit_cell_formula" ] = comp . as_dict ( )
d [ "reduced_cell_formula" ] = Composition ( comp . reduced_formula ) . as_dict ( )
d [ "pretty_formula" ] = comp ... |
def ordered_uniqify ( sequence ) :
"""Uniqifies the given hashable sequence while preserving its order .
: param sequence : Sequence .
: type sequence : object
: return : Uniqified sequence .
: rtype : list""" | items = set ( )
return [ key for key in sequence if key not in items and not items . add ( key ) ] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.