signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def cli ( env , limit , closed = False , get_all = False ) :
"""Invoices and all that mess""" | manager = AccountManager ( env . client )
invoices = manager . get_invoices ( limit , closed , get_all )
table = formatting . Table ( [ "Id" , "Created" , "Type" , "Status" , "Starting Balance" , "Ending Balance" , "Invoice Amount" , "Items" ] )
table . align [ 'Starting Balance' ] = 'l'
table . align [ 'Ending Balance... |
def add_node_element ( self , node ) :
"""Add a ( syntax category ) < node > to the document graph .
Parameters
node : etree . Element
etree representation of a < node > element
A < node > describes an element of a syntax tree .
The root < node > element does not have a parent attribute ,
while non - ro... | node_id = self . get_element_id ( node )
if 'parent' in node . attrib :
parent_id = self . get_parent_id ( node )
else : # < node > is the root of the syntax tree of a sentence ,
# but it might be embedded in a < edu > or < edu - range > .
# we want to attach it directly to the < sentence > element
parent_id = ... |
def randpos ( self ) :
'''random initial position''' | self . setpos ( gen_settings . home_lat , gen_settings . home_lon )
self . move ( random . uniform ( 0 , 360 ) , random . uniform ( 0 , gen_settings . region_width ) ) |
def barycentric_coords ( coords , simplex ) :
"""Converts a list of coordinates to barycentric coordinates , given a
simplex with d + 1 points . Only works for d > = 2.
Args :
coords : list of n coords to transform , shape should be ( n , d )
simplex : list of coordinates that form the simplex , shape shoul... | coords = np . atleast_2d ( coords )
t = np . transpose ( simplex [ : - 1 , : ] ) - np . transpose ( simplex [ - 1 , : ] ) [ : , None ]
all_but_one = np . transpose ( np . linalg . solve ( t , np . transpose ( coords - simplex [ - 1 ] ) ) )
last_coord = 1 - np . sum ( all_but_one , axis = - 1 ) [ : , None ]
return np . ... |
def users ( self ) :
""": class : ` ~ zhmcclient . UserManager ` : Access to the : term : ` Users < User > ` in
this Console .""" | # We do here some lazy loading .
if not self . _users :
self . _users = UserManager ( self )
return self . _users |
async def create_vm ( self , preset_name , image , flavor , security_groups = None , userdata = None , key_name = None , availability_zone = None , subnets = None ) :
'''Create VM
: arg preset _ name : string
: arg image : string image id
: arg flavor : string flavor id
: arg security _ groups : list
: ar... | image_id = self . images_map . inv . get ( image )
flavor_id = self . flavors_map . inv . get ( flavor )
spec = { "name" : preset_name , "flavorRef" : flavor_id , "imageRef" : image_id , "security_groups" : [ { "name" : group } for group in security_groups ] , "user_data" : userdata }
if availability_zone is not None :... |
def contains_vasp_input ( dir_name ) :
"""Checks if a directory contains valid VASP input .
Args :
dir _ name :
Directory name to check .
Returns :
True if directory contains all four VASP input files ( INCAR , POSCAR ,
KPOINTS and POTCAR ) .""" | for f in [ "INCAR" , "POSCAR" , "POTCAR" , "KPOINTS" ] :
if not os . path . exists ( os . path . join ( dir_name , f ) ) and not os . path . exists ( os . path . join ( dir_name , f + ".orig" ) ) :
return False
return True |
def setEditor ( self , name ) :
"""Sets the editor class for this Stimulus""" | editor = get_stimulus_editor ( name )
self . editor = editor
self . _stim . setStimType ( name ) |
def get_suffixes ( arr ) :
"""Returns all possible suffixes of an array ( lazy evaluated )
Args :
arr : input array
Returns :
Array of all possible suffixes ( as tuples )""" | arr = tuple ( arr )
return [ arr ]
return ( arr [ i : ] for i in range ( len ( arr ) ) ) |
def replace_filehandler ( logname , new_file , level = None , frmt = None ) :
"""This utility function will remove a previous Logger FileHandler , if one
exists , and add a new filehandler .
Parameters :
logname
The name of the log to reconfigure , ' openaccess _ epub ' for example
new _ file
The file l... | # Call up the Logger to get reconfigured
log = logging . getLogger ( logname )
# Set up defaults and whether explicit for level
if level is not None :
level = get_level ( level )
explicit_level = True
else :
level = logging . DEBUG
explicit_level = False
# Set up defaults and whether explicit for frmt
i... |
def add_file ( self , file_grp , content = None , ** kwargs ) :
"""Add an output file . Creates an : class : ` OcrdFile ` to pass around and adds that to the
OcrdMets OUTPUT section .""" | log . debug ( 'outputfile file_grp=%s local_filename=%s content=%s' , file_grp , kwargs . get ( 'local_filename' ) , content is not None )
if content is not None and 'local_filename' not in kwargs :
raise Exception ( "'content' was set but no 'local_filename'" )
oldpwd = os . getcwd ( )
try :
os . chdir ( self ... |
def scan ( self , t , dt = None , aggfunc = None ) :
"""Returns the spectrum from a specific time .
Parameters
t : float
dt : float""" | idx = ( np . abs ( self . index - t ) ) . argmin ( )
if dt is None : # only take the spectra at the nearest time
mz_abn = self . values [ idx , : ] . copy ( )
else : # sum up all the spectra over a range
en_idx = ( np . abs ( self . index - t - dt ) ) . argmin ( )
idx , en_idx = min ( idx , en_idx ) , max (... |
def update_layers_geonode_wm ( service , num_layers = None ) :
"""Update layers for a WorldMap instance .
Sample endpoint : http : / / localhost : 8000/""" | wm_api_url = urlparse . urljoin ( service . url , 'worldmap/api/2.8/layer/?format=json' )
if num_layers :
total = num_layers
else :
response = requests . get ( wm_api_url )
data = json . loads ( response . content )
total = data [ 'meta' ] [ 'total_count' ]
# set srs
# WorldMap supports only 4326 , 9009... |
def each_step ( graph ) :
"""Returns an iterator that yields each step and it ' s direct
dependencies .""" | steps = graph . topological_sort ( )
steps . reverse ( )
for step in steps :
deps = graph . downstream ( step . name )
yield ( step , deps ) |
def charmap ( prefixed_name ) :
"""Return the character map used for a given font .
Returns
return _ value : dict
The dictionary mapping the icon names to the corresponding unicode character .""" | prefix , name = prefixed_name . split ( '.' )
return _instance ( ) . charmap [ prefix ] [ name ] |
def invalid_type_error ( method_name , arg_name , got_value , expected_type , version = '0.13.0' ) :
"""Raise a CompilationException when an adapter method available to macros
has changed .""" | got_type = type ( got_value )
msg = ( "As of {version}, 'adapter.{method_name}' expects argument " "'{arg_name}' to be of type '{expected_type}', instead got " "{got_value} ({got_type})" )
raise_compiler_error ( msg . format ( version = version , method_name = method_name , arg_name = arg_name , expected_type = expecte... |
def check_password_readable ( self , section , fields ) :
"""Check if there is a readable configuration file and print a warning .""" | if not fields :
return
# The information which of the configuration files
# included which option is not available . To avoid false positives ,
# a warning is only printed if exactly one file has been read .
if len ( self . read_ok ) != 1 :
return
fn = self . read_ok [ 0 ]
if fileutil . is_accessable_by_others ... |
def migrate_abci_chain ( self ) :
"""Generate and record a new ABCI chain ID . New blocks are not
accepted until we receive an InitChain ABCI request with
the matching chain ID and validator set .
Chain ID is generated based on the current chain and height .
` chain - X ` = > ` chain - X - migrated - at - h... | latest_chain = self . get_latest_abci_chain ( )
if latest_chain is None :
return
block = self . get_latest_block ( )
suffix = '-migrated-at-height-'
chain_id = latest_chain [ 'chain_id' ]
block_height_str = str ( block [ 'height' ] )
new_chain_id = chain_id . split ( suffix ) [ 0 ] + suffix + block_height_str
self ... |
def ex_varassign ( name , expr ) :
"""Assign an expression into a single variable . The expression may
either be an ` ast . expr ` object or a value to be used as a literal .""" | if not isinstance ( expr , ast . expr ) :
expr = ex_literal ( expr )
return ast . Assign ( [ ex_lvalue ( name ) ] , expr ) |
def _set_contn_src_dst ( self , v , load = False ) :
"""Setter method for contn _ src _ dst , mapped from YANG variable / overlay _ class _ map / cmap _ seq / match / contn _ src _ dst ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ contn _ src _ dst is co... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = contn_src_dst . contn_src_dst , is_container = 'container' , presence = False , yang_name = "contn-src-dst" , rest_name = "" , parent = self , choice = ( u'overlay-match-ip' , u'case-overlay-ip-src-dest' ) , path_helper = sel... |
def _get_resources ( self , args , params ) :
"""Finds the list of resources from the keyword parameters and pops
them out of the params dictionary .""" | resources = [ ]
disabled = [ ]
for resource in [ 'holoviews' ] + list ( Store . renderers . keys ( ) ) :
if resource in args :
resources . append ( resource )
if resource in params :
setting = params . pop ( resource )
if setting is True and resource != 'matplotlib' :
if reso... |
def load_metadata_csv_single_user ( csv_in , header , tags_idx ) :
"""Return the metadata as requested for a single user .
: param csv _ in : This field is the csv file to return metadata from .
: param header : This field contains the headers in the csv file
: param tags _ idx : This field contains the index... | metadata = { }
n_headers = len ( header )
for index , row in enumerate ( csv_in , 2 ) :
if row [ 0 ] == "" :
raise ValueError ( 'Error: In row number ' + str ( index ) + ':' + ' "filename" must not be empty.' )
if row [ 0 ] == 'None' and [ x == 'NA' for x in row [ 1 : ] ] :
break
if len ( ro... |
def _get_pasteas_data ( self , dim , obj ) :
"""Returns list of lists of obj than has dimensionality dim
Parameters
dim : Integer
\t Dimensionality of obj
obj : Object
\t Iterable object of dimensionality dim""" | if dim == 0 :
return [ [ repr ( obj ) ] ]
elif dim == 1 :
return [ [ repr ( o ) ] for o in obj ]
elif dim == 2 :
return [ map ( repr , o ) for o in obj ] |
def get_desc2nts ( self , ** kws_usr ) :
"""Return grouped , sorted namedtuples in either format : flat , sections .""" | # desc2nts contains : ( sections hdrgo _ prt sortobj ) or ( flat hdrgo _ prt sortobj )
# keys _ nts : hdrgo _ prt section _ prt top _ n use _ sections
kws_nts = { k : v for k , v in kws_usr . items ( ) if k in self . keys_nts }
return self . get_desc2nts_fnc ( ** kws_nts ) |
def prepare_encoder ( inputs , hparams , attention_type = "local_1d" ) :
"""Prepare encoder for images .""" | x = prepare_image ( inputs , hparams , name = "enc_channels" )
# Add position signals .
x = add_pos_signals ( x , hparams , "enc_pos" )
x_shape = common_layers . shape_list ( x )
if attention_type == "local_1d" :
x = tf . reshape ( x , [ x_shape [ 0 ] , x_shape [ 1 ] * x_shape [ 2 ] , hparams . hidden_size ] )
... |
def _ge_from_lt ( self , other ) :
"""Return a > = b . Computed by @ total _ ordering from ( not a < b ) .""" | op_result = self . __lt__ ( other )
if op_result is NotImplemented :
return NotImplemented
return not op_result |
def modify_dict ( data , key , value , create_if_missing = False ) :
"""Change ( or add ) a json key / value pair .
Args :
data ( dict ) : The original data . This will not be modified .
key ( list ) : A list of keys and subkeys specifing the key to change ( list can be one )
value ( str ) : The value to ch... | data_copy = copy . deepcopy ( data )
key_copy = copy . deepcopy ( key )
delver = data_copy
current_key = key_copy
last_key = "Root"
# Dig through the json , setting delver to the dict that contains the last key in " key "
while len ( current_key ) > 1 :
if current_key [ 0 ] not in delver :
raise KeyError ( ... |
def validate_and_copy_one_submission ( self , submission_path ) :
"""Validates one submission and copies it to target directory .
Args :
submission _ path : path in Google Cloud Storage of the submission file""" | if os . path . exists ( self . download_dir ) :
shutil . rmtree ( self . download_dir )
os . makedirs ( self . download_dir )
if os . path . exists ( self . validate_dir ) :
shutil . rmtree ( self . validate_dir )
os . makedirs ( self . validate_dir )
logging . info ( '\n' + ( '#' * 80 ) + '\n# Processing submi... |
def get_subject ( self , identifier ) :
"""Build a Subject XML block for a SAML 1.1
AuthenticationStatement or AttributeStatement .""" | subject = etree . Element ( 'Subject' )
name = etree . SubElement ( subject , 'NameIdentifier' )
name . text = identifier
subject_confirmation = etree . SubElement ( subject , 'SubjectConfirmation' )
method = etree . SubElement ( subject_confirmation , 'ConfirmationMethod' )
method . text = self . confirmation_method
r... |
def has_colors ( fp ) :
"""Test if given file is an ANSI color enabled tty .""" | # The is _ tty ( ) function ensures that we do not colorize
# redirected streams , as this is almost never what we want
if not is_tty ( fp ) :
return False
if os . name == 'nt' :
return True
elif has_curses :
import curses
try :
curses . setupterm ( os . environ . get ( "TERM" ) , fp . fileno ( ... |
def display_annotations ( self ) :
"""Mark all the bookmarks / events , on top of first plot .""" | for item in self . idx_annot :
self . scene . removeItem ( item )
self . idx_annot = [ ]
for item in self . idx_annot_labels :
self . scene . removeItem ( item )
self . idx_annot_labels = [ ]
self . highlight = None
window_start = self . parent . value ( 'window_start' )
window_length = self . parent . value ( ... |
def _write_to_cache ( self , expr , res ) :
"""Store the cached result without indentation , and without the
keyname""" | res = dedent ( res )
super ( ) . _write_to_cache ( expr , res ) |
def allow_access_to_instance ( self , _ , ip_address ) :
'''Allow access to instance .''' | if not self . connect_to_aws_rds ( ) :
return False
try :
conn = boto . ec2 . connect_to_region ( self . region , aws_access_key_id = self . aws_access_key_id , aws_secret_access_key = self . aws_secret_access_key )
sgs = conn . get_all_security_groups ( 'default' )
default_sg = sgs [ 0 ]
default_sg... |
def json ( self ) :
"""Return a JSON - serializable representation of this result .
The output of this function can be converted to a serialized string
with : any : ` json . dumps ` .""" | def _json_or_none ( obj ) :
return None if obj is None else obj . json ( )
data = { "segment_models" : [ _json_or_none ( m ) for m in self . segment_models ] , "model_lookup" : { key : _json_or_none ( val ) for key , val in self . model_lookup . items ( ) } , "prediction_segment_type" : self . prediction_segment_ty... |
def dephasing_operators ( p ) :
"""Return the phase damping Kraus operators""" | k0 = np . eye ( 2 ) * np . sqrt ( 1 - p / 2 )
k1 = np . sqrt ( p / 2 ) * Z
return k0 , k1 |
def get_tags_of_port ( self , port ) :
"""Get all tags related to a given port .
This is the inverse of what is stored in self . cluster _ tags ) .""" | return ( sorted ( [ tag for tag in self . cluster_tags if port in self . cluster_tags [ tag ] ] ) ) |
def loadTargetPatterns ( self , filename , cols = None , everyNrows = 1 , delim = ' ' , checkEven = 1 ) :
"""Loads targets as patterns from file .""" | self . loadTargetPatternssFromFile ( filename , cols , everyNrows , delim , checkEven ) |
def _is_non_public_numeric_address ( host ) :
"""returns True if ' host ' is not public""" | # for numeric hostnames , skip RFC1918 addresses , since no Tor exit
# node will be able to reach those . Likewise ignore IPv6 addresses .
try :
a = ipaddress . ip_address ( six . text_type ( host ) )
except ValueError :
return False
# non - numeric , let Tor try it
if a . is_loopback or a . is_multicast or... |
def add_vectors ( vec_a , vec_b , periodic ) :
'''Returns the sum of the points vec _ a - vec _ b subject
to the periodic boundary conditions .''' | moved = noperiodic ( np . array ( [ vec_a , vec_b ] ) , periodic )
return vec_a + vec_b |
def close ( self ) :
"""Close the stream . This performs a proper stream shutdown , except if the
stream is currently performing a TLS handshake . In that case , calling
: meth : ` close ` is equivalent to calling : meth : ` abort ` .
Otherwise , the transport waits until all buffers are transmitted .""" | if self . _state == _State . CLOSED :
self . _invalid_state ( "close() called" )
return
if self . _state == _State . TLS_HANDSHAKING : # hard - close
self . _force_close ( None )
elif self . _state == _State . TLS_SHUTTING_DOWN : # shut down in progress , nothing to do
pass
elif self . _buffer : # there... |
def is_nested_list_like ( obj ) :
"""Check if the object is list - like , and that all of its elements
are also list - like .
. . versionadded : : 0.20.0
Parameters
obj : The object to check
Returns
is _ list _ like : bool
Whether ` obj ` has list - like properties .
Examples
> > > is _ nested _ l... | return ( is_list_like ( obj ) and hasattr ( obj , '__len__' ) and len ( obj ) > 0 and all ( is_list_like ( item ) for item in obj ) ) |
def run_step ( context ) :
"""Run command , program or executable .
Context is a dictionary or dictionary - like .
Context must contain the following keys :
cmd : < < cmd string > > ( command + args to execute . )
OR , as a dict
cmd :
run : str . mandatory . < < cmd string > > command + args to execute ... | logger . debug ( "started" )
pypyr . steps . cmd . run_step ( context )
logger . debug ( "done" ) |
def bandnames ( self , names ) :
"""set the names of the raster bands
Parameters
names : list of str
the names to be set ; must be of same length as the number of bands
Returns""" | if not isinstance ( names , list ) :
raise TypeError ( 'the names to be set must be of type list' )
if len ( names ) != self . bands :
raise ValueError ( 'length mismatch of names to be set ({}) and number of bands ({})' . format ( len ( names ) , self . bands ) )
self . __bandnames = names |
def gaussian ( h , Xi , x ) :
"""Gaussian Kernel for continuous variables
Parameters
h : 1 - D ndarray , shape ( K , )
The bandwidths used to estimate the value of the kernel function .
Xi : 1 - D ndarray , shape ( K , )
The value of the training set .
x : 1 - D ndarray , shape ( K , )
The value at wh... | return ( 1. / np . sqrt ( 2 * np . pi ) ) * np . exp ( - ( Xi - x ) ** 2 / ( h ** 2 * 2. ) ) |
def get_substructure ( data , path ) :
"""Tries to retrieve a sub - structure within some data . If the path does not
match any sub - structure , returns None .
> > > data = { ' a ' : 5 , ' b ' : { ' c ' : [ 1 , 2 , [ { ' f ' : [ 57 ] } ] , 4 ] , ' d ' : ' test ' } }
> > > get _ substructure ( island , " bc "... | if not len ( path ) :
return data
try :
return get_substructure ( data [ path [ 0 ] ] , path [ 1 : ] )
except ( TypeError , IndexError , KeyError ) :
return None |
def combine_quantities ( data , units = 'units' , magnitude = 'magnitude' , list_of_dicts = False ) :
"""combine < unit , magnitude > pairs into pint . Quantity objects
Parameters
data : dict
units : str
name of units key
magnitude : str
name of magnitude key
list _ of _ dicts : bool
treat list of d... | # noqa : E501
try :
from pint import UnitRegistry
ureg = UnitRegistry ( )
except ImportError :
raise ImportError ( 'please install pint to use this module' )
list_of_dicts = '__list__' if list_of_dicts else None
data_flatten2d = flatten2d ( data , list_of_dicts = list_of_dicts )
new_dict = { }
for key , val... |
def draw_rect ( self , x , y , width , height , string , fg = Ellipsis , bg = Ellipsis ) :
"""Draws a rectangle starting from x and y and extending to width and height .
If width or height are None then it will extend to the edge of the console .
Args :
x ( int ) : x - coordinate for the top side of the rect ... | x , y , width , height = self . _normalizeRect ( x , y , width , height )
fg , bg = _format_color ( fg , self . _fg ) , _format_color ( bg , self . _bg )
char = _format_char ( string )
# use itertools to make an x , y grid
# using ctypes here reduces type converstions later
# grid = _ itertools . product ( ( _ ctypes .... |
def member_create ( self , params , member_id ) :
"""start new mongod instances as part of replica set
Args :
params - member params
member _ id - member index
return member config""" | member_config = params . get ( 'rsParams' , { } )
server_id = params . pop ( 'server_id' , None )
version = params . pop ( 'version' , self . _version )
proc_params = { 'replSet' : self . repl_id }
proc_params . update ( params . get ( 'procParams' , { } ) )
if self . enable_ipv6 :
enable_ipv6_single ( proc_params ... |
def to_yaml ( obj , stream = None , dumper_cls = yaml . Dumper , default_flow_style = False , ** kwargs ) :
"""Serialize a Python object into a YAML stream with OrderedDict and
default _ flow _ style defaulted to False .
If stream is None , return the produced string instead .
OrderedDict reference : http : /... | class OrderedDumper ( dumper_cls ) :
pass
def dict_representer ( dumper , data ) :
return dumper . represent_mapping ( yaml . resolver . BaseResolver . DEFAULT_MAPPING_TAG , data . items ( ) )
OrderedDumper . add_representer ( OrderedDict , dict_representer )
obj_dict = to_dict ( obj , ** kwargs )
return yaml .... |
def run ( self , batch : mx . io . DataBatch ) -> List [ mx . nd . NDArray ] :
"""Runs the forward pass and returns the outputs .
: param batch : The batch to run .
: return : The grouped symbol ( probs and target dists ) and lists containing the data names and label names .""" | self . module . forward ( batch , is_train = False )
return self . module . get_outputs ( ) |
def get_is_property ( value , is_bytes = False ) :
"""Get shortcut for ` SC ` or ` Binary ` property .""" | if value . startswith ( '^' ) :
prefix = value [ 1 : 3 ]
temp = value [ 3 : ]
negate = '^'
else :
prefix = value [ : 2 ]
temp = value [ 2 : ]
negate = ''
if prefix != 'is' :
raise ValueError ( "Does not start with 'is'!" )
script_obj = unidata . ascii_script_extensions if is_bytes else unida... |
def append ( self , item ) :
"""Add an item to the end of the list""" | with self . lock :
with self . _closeable_cursor ( ) as cursor :
cursor . execute ( '''INSERT INTO list (list_index, value) VALUES ((SELECT MAX(list_index) FROM list) + 1, ?)''' , ( self . _coder ( item ) , ) )
self . _do_write ( ) |
def get_account_config ( self , id_or_name ) :
"""Return a dictionary of account configuration for the account with the
specified ID or name .
: param id _ or _ name : ID or name of account
: type id _ or _ name : str
: return : configuration for specified account
: rtype : dict""" | if id_or_name in self . _config :
return self . _config [ id_or_name ]
if id_or_name in self . _acct_name_to_id :
return self . _config [ self . _acct_name_to_id [ id_or_name ] ]
raise RuntimeError ( 'ERROR: Unknown account ID or name' ) |
def inverse ( self ) :
"""Inverse of this operator .
For example , if A and B are operators : :
[ [ A , 0 ] ,
[0 , B ] ]
The inverse is given by : :
[ [ A ^ - 1 , 0 ] ,
[0 , B ^ - 1 ] ]
This is only well defined if each sub - operator has an inverse
Returns
inverse : ` DiagonalOperator `
The inv... | inverses = [ op . inverse for op in self . operators ]
return DiagonalOperator ( * inverses , domain = self . range , range = self . domain ) |
def _build_torrent ( self , row ) :
"""Builds and returns a Torrent object for the given parsed row .""" | # Scrape , strip and build ! ! !
cols = row . findall ( './/td' )
# split the row into it ' s columns
# this column contains the categories
[ category , sub_category ] = [ c . text for c in cols [ 0 ] . findall ( './/a' ) ]
# this column with all important info
links = cols [ 1 ] . findall ( './/a' )
# get 4 a tags fro... |
def inits_t ( wrap ) :
"""Transformation for Sequence . inits
: param wrap : wrap children values with this
: return : transformation""" | return Transformation ( 'inits' , lambda sequence : [ wrap ( sequence [ : i ] ) for i in reversed ( range ( len ( sequence ) + 1 ) ) ] , { ExecutionStrategies . PRE_COMPUTE } ) |
def addresses ( self , fields = None ) :
"""List of addresses associated with the postcode .
Addresses are dict objects which look like the following : :
" uprn " : " 10033544614 " ,
" organisation _ name " : " BUCKINGHAM PALACE " ,
" department _ name " : " " ,
" po _ box _ number " : " " ,
" building ... | if fields is None :
fields = ',' . join ( DEFAULT_ADDRESS_FIELDS )
if getattr ( self , '_addresses' , None ) is None :
self . _addresses = self . _client . _query_api ( 'addresses/' , postcode = self . normalised , fields = fields )
return self . _addresses |
def l2traceroute_input_protocolType_IP_src_ip ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
l2traceroute = ET . Element ( "l2traceroute" )
config = l2traceroute
input = ET . SubElement ( l2traceroute , "input" )
protocolType = ET . SubElement ( input , "protocolType" )
IP = ET . SubElement ( protocolType , "IP" )
src_ip = ET . SubElement ( IP , "src-ip" )
src_ip . text = kwa... |
def _resource_prefix ( self , resource = None ) :
"""Get elastic prefix for given resource .
Resource can specify ` ` elastic _ prefix ` ` which behaves same like ` ` mongo _ prefix ` ` .""" | px = 'ELASTICSEARCH'
if resource and config . DOMAIN [ resource ] . get ( 'elastic_prefix' ) :
px = config . DOMAIN [ resource ] . get ( 'elastic_prefix' )
return px |
async def create_payment_address ( seed : str = None ) -> str :
"""Creates a payment address inside the wallet .
: param seed : String
Example :
address = await Wallet . create _ payment _ address ( ' 000001234567 ' )
: return : String""" | logger = logging . getLogger ( __name__ )
if not hasattr ( Wallet . create_payment_address , "cb" ) :
logger . debug ( "vcx_wallet_create_payment_address: Creating callback" )
Wallet . create_payment_address . cb = create_cb ( CFUNCTYPE ( None , c_uint32 , c_uint32 , c_char_p ) )
if seed :
c_seed = c_char_p... |
def _learn ( # mutated args
permanences , rng , # activity
activeCells , activeInput , growthCandidateInput , # configuration
sampleSize , initialPermanence , permanenceIncrement , permanenceDecrement , connectedPermanence ) :
"""For each active cell , reinforce active synapses , punish inactive synapses ,
and gr... | permanences . incrementNonZerosOnOuter ( activeCells , activeInput , permanenceIncrement )
permanences . incrementNonZerosOnRowsExcludingCols ( activeCells , activeInput , - permanenceDecrement )
permanences . clipRowsBelowAndAbove ( activeCells , 0.0 , 1.0 )
if sampleSize == - 1 :
permanences . setZerosOnOuter ( a... |
def set_last_row_idx ( self , last_row_idx ) :
'''Parameters
param last _ row _ idx : int
number of rows''' | assert last_row_idx >= self . _max_row
self . _max_row = last_row_idx
return self |
def get_psms ( self ) :
"""Creates iterator to write to new tsv . Contains input tsv
lines plus quant data for these .""" | self . header = actions . create_header ( self . oldheader , self . spectracol )
self . psms = actions . generate_psms_spectradata ( self . lookup , self . fn , self . oldheader ) |
def accpro_results ( self ) :
"""Parse the ACCpro output file and return a dict of secondary structure compositions .""" | return ssbio . protein . sequence . utils . fasta . load_fasta_file_as_dict_of_seqs ( self . out_accpro ) |
def check_for_message_exception ( cls , message_result ) :
"""Makes sure there isn ' t an error when sending the message .
Kafka will silently catch exceptions and not bubble them up .
Parameters
message _ result : FutureRecordMetadata""" | exception = message_result . exception
if isinstance ( exception , BaseException ) :
raise exception |
def _translate_src_mode_to_dst_mode ( self , src_mode ) : # type : ( SyncCopy , blobxfer . models . azure . StorageModes ) - > bool
"""Translate the source mode into the destination mode
: param SyncCopy self : this
: param blobxfer . models . azure . StorageModes src _ mode : source mode
: rtype : blobxfer .... | if ( self . _spec . options . dest_mode == blobxfer . models . azure . StorageModes . Auto ) :
return src_mode
else :
return self . _spec . options . dest_mode |
def toposort ( data ) :
"""Dependencies are expressed as a dictionary whose keys are items and
whose values are a set of dependent items . Output is a list of sets in
topological order . The first set consists of items with no dependences ,
each subsequent set consists of items that depend upon items in the
... | # Ignore self dependencies .
for k , v in iteritems ( data ) :
v . discard ( k )
# Find all items that don ' t depend on anything .
extra_items_in_deps = reduce ( set . union , itervalues ( data ) ) - set ( data . keys ( ) )
# Add empty dependences where needed
data . update ( { item : set ( ) for item in extra_ite... |
def name_targets ( func ) :
"""Wrap a function such that returning ` ` ' a ' , ' b ' , ' c ' , [ 1 , 2 , 3 ] ` ` transforms
the value into ` ` dict ( a = 1 , b = 2 , c = 3 ) ` ` .
This is useful in the case where the last parameter is an SCons command .""" | def wrap ( * a , ** kw ) :
ret = func ( * a , ** kw )
return dict ( zip ( ret [ : - 1 ] , ret [ - 1 ] ) )
return wrap |
def load ( self , rawdata ) :
"""Load cookies from a string ( presumably HTTP _ COOKIE ) or
from a dictionary . Loading cookies from a dictionary ' d '
is equivalent to calling :
map ( Cookie . _ _ setitem _ _ , d . keys ( ) , d . values ( ) )""" | if isinstance ( rawdata , str ) :
self . __parse_string ( rawdata )
else : # self . update ( ) wouldn ' t call our custom _ _ setitem _ _
for key , value in rawdata . items ( ) :
self [ key ] = value
return |
def build_machine ( lines ) :
"""Build machine from list of lines .""" | if lines == [ ] :
raise SyntaxError ( 'Empty file' )
else :
machine = Machine ( lines [ 0 ] . split ( ) )
for line in lines [ 1 : ] :
if line . strip ( ) != '' :
machine . add_state ( line )
machine . check ( )
return machine |
def Start ( self ) :
"""This starts the worker threads .""" | if not self . started :
self . started = True
for _ in range ( self . min_threads ) :
self . _AddWorker ( ) |
def tags ( self ) :
"""Returns a dictionary that lists all available tags that can be used
for further filtering""" | ret = { }
for typ in _meta_fields_twig :
if typ in [ 'uniqueid' , 'plugin' , 'feedback' , 'fitting' , 'history' , 'twig' , 'uniquetwig' ] :
continue
k = '{}s' . format ( typ )
ret [ k ] = getattr ( self , k )
return ret |
def get_torrent ( self , torrent_id ) :
"""Gets the ` . torrent ` data for the given ` torrent _ id ` .
: param torrent _ id : the ID of the torrent to download
: raises TorrentNotFoundError : if the torrent does not exist
: returns : : class : ` Torrent ` of the associated torrent""" | params = { 'page' : 'download' , 'tid' : torrent_id , }
r = requests . get ( self . base_url , params = params )
if r . headers . get ( 'content-type' ) != 'application/x-bittorrent' :
raise TorrentNotFoundError ( TORRENT_NOT_FOUND_TEXT )
torrent_data = r . content
return Torrent ( torrent_id , torrent_data ) |
def add_origin_info ( self , packet ) :
"""Add optional Origin headers to message""" | packet . add_header ( 'Origin-Machine-Name' , platform . node ( ) )
packet . add_header ( 'Origin-Software-Name' , 'gntp.py' )
packet . add_header ( 'Origin-Software-Version' , __version__ )
packet . add_header ( 'Origin-Platform-Name' , platform . system ( ) )
packet . add_header ( 'Origin-Platform-Version' , platform... |
def linsrgb_to_srgb ( linsrgb ) :
"""Convert physically linear RGB values into sRGB ones . The transform is
uniform in the components , so * linsrgb * can be of any shape .
* linsrgb * values should range between 0 and 1 , inclusively .""" | # From Wikipedia , but easy analogue to the above .
gamma = 1.055 * linsrgb ** ( 1. / 2.4 ) - 0.055
scale = linsrgb * 12.92
return np . where ( linsrgb > 0.0031308 , gamma , scale ) |
def extract_component_doi ( tag , nodenames ) :
"""Used to get component DOI from a tag and confirm it is actually for that tag
and it is not for one of its children in the list of nodenames""" | component_doi = None
if ( tag . name == "sub-article" ) :
component_doi = doi_uri_to_doi ( node_text ( first ( raw_parser . article_id ( tag , pub_id_type = "doi" ) ) ) )
else :
object_id_tag = first ( raw_parser . object_id ( tag , pub_id_type = "doi" ) )
# Tweak : if it is media and has no object _ id _ t... |
def get_table ( self , tablename ) :
""": param str tablename : Name of table to find .
: return : A : py : class : ` xltable . Table ` instance from the table name .""" | table , ( _row , _col ) = self . __tables [ tablename ]
return table |
def clear_sessions ( hyperstream , inactive_only = True , clear_history = False ) :
"""Clear all ( inactive ) sessions and ( optionally ) their history
: param hyperstream : The hyperstream object
: param inactive _ only : Whether to only clear inactive sessions ( active sessions may be owned by another process... | query = dict ( )
if inactive_only :
query [ 'active' ] = False
if hyperstream . current_session is not None :
query [ 'session_id__ne' ] = hyperstream . current_session . session_id
with switch_db ( SessionModel , "hyperstream" ) :
for s in SessionModel . objects ( ** query ) :
if clear_history :
... |
def isrchi ( value , ndim , array ) :
"""Search for a given value within an integer array . Return
the index of the first matching array entry , or - 1 if the key
value was not found .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / isrchi _ c . html
: param value : Key value... | value = ctypes . c_int ( value )
ndim = ctypes . c_int ( ndim )
array = stypes . toIntVector ( array )
return libspice . isrchi_c ( value , ndim , array ) |
def bus_inspector ( self , bus , message ) :
"""Inspect the bus for screensaver messages of interest""" | # We only care about stuff on this interface . We did filter
# for it above , but even so we still hear from ourselves
# ( hamster messages ) .
if message . get_interface ( ) != self . screensaver_uri :
return True
member = message . get_member ( )
if member in ( "SessionIdleChanged" , "ActiveChanged" ) :
logge... |
def ReadCodonAlignment ( fastafile , checknewickvalid ) :
"""Reads codon alignment from file .
* fastafile * is the name of an existing FASTA file .
* checknewickvalid * : if * True * , we require that names are unique and do
* * not * * contain spaces , commas , colons , semicolons , parentheses , square
b... | codonmatch = re . compile ( '^[ATCG]{3}$' )
gapmatch = re . compile ( '^-+^' )
seqs = [ ( seq . description . strip ( ) , str ( seq . seq ) . upper ( ) ) for seq in Bio . SeqIO . parse ( fastafile , 'fasta' ) ]
assert seqs , "{0} failed to specify any sequences" . format ( fastafile )
seqlen = len ( seqs [ 0 ] [ 1 ] )
... |
def get_multiple ( self , fields = list ( ) , limit = None , order_by = list ( ) , offset = None ) :
"""Wrapper method that takes whatever was returned by the _ all _ inner ( ) generators and chains it in one result
The response can be sorted by passing a list of fields to order _ by .
Example :
get _ multipl... | return itertools . chain . from_iterable ( self . _all_inner ( fields , limit , order_by , offset ) ) |
def _choose_width_fn ( has_invisible , enable_widechars , is_multiline ) :
"""Return a function to calculate visible cell width .""" | if has_invisible :
line_width_fn = _visible_width
elif enable_widechars : # optional wide - character support if available
line_width_fn = wcwidth . wcswidth
else :
line_width_fn = len
if is_multiline :
def width_fn ( s ) :
return _multiline_width ( s , line_width_fn )
else :
width_fn = line... |
def build_index ( self , filename , indexfile ) :
"""Recipe from Brad Chapman ' s blog
< http : / / bcbio . wordpress . com / 2009/07/26 / sorting - genomic - alignments - using - python / >""" | indexes = interval_index_file . Indexes ( )
in_handle = open ( filename )
reader = maf . Reader ( in_handle )
while True :
pos = reader . file . tell ( )
rec = next ( reader )
if rec is None :
break
for c in rec . components :
indexes . add ( c . src , c . forward_strand_start , c . forw... |
def check ( self ) :
"""Checks values""" | status = True
g = get_root ( self ) . globals
if self . mag . ok ( ) :
self . mag . config ( bg = g . COL [ 'main' ] )
else :
self . mag . config ( bg = g . COL [ 'warn' ] )
status = False
if self . airmass . ok ( ) :
self . airmass . config ( bg = g . COL [ 'main' ] )
else :
self . airmass . config... |
def mark_job_as_failed ( self , job_id , exception , traceback ) :
"""Mark the job as failed , and record the traceback and exception .
Args :
job _ id : The job _ id of the job that failed .
exception : The exception object thrown by the job .
traceback : The traceback , if any . Note ( aron ) : Not implem... | session = self . sessionmaker ( )
job , orm_job = self . _update_job_state ( job_id , State . FAILED , session = session )
# Note ( aron ) : looks like SQLAlchemy doesn ' t automatically
# save any pickletype fields even if we re - set ( orm _ job . obj = job ) that
# field . My hunch is that it ' s tracking the id of ... |
def c32checkEncode ( version , data ) :
"""> > > c32checkEncode ( 22 , ' a46ff88886c2ef9762d970b4d2c63678835bd39d ' )
' P2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7'
> > > c32checkEncode ( 0 , ' a46ff88886c2ef9762d970b4d2c63678835bd39d ' )
'02J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKPVKG2CE '
> > > c32checkEncode ( 31 , ... | if version < 0 or version >= len ( C32 ) :
raise ValueError ( 'Invalid version -- must be between 0 and {}' . format ( len ( C32 ) - 1 ) )
if not re . match ( r'^[0-9a-fA-F]*$' , data ) :
raise ValueError ( 'Invalid data -- must be hex' )
data = data . lower ( )
if len ( data ) % 2 != 0 :
data = '0{}' . for... |
def decode_to_shape ( inputs , shape , scope ) :
"""Encode the given tensor to given image shape .""" | with tf . variable_scope ( scope , reuse = tf . AUTO_REUSE ) :
x = inputs
x = tfl . flatten ( x )
x = tfl . dense ( x , shape [ 2 ] , activation = None , name = "dec_dense" )
x = tf . expand_dims ( x , axis = 1 )
return x |
def runExperiment ( ) :
"""Experiment 1 : Calculate error rate as a function of training sequence numbers
: return :""" | trainSeqN = [ 5 , 10 , 20 , 50 , 100 , 200 ]
rptPerCondition = 5
correctRateAll = np . zeros ( ( len ( trainSeqN ) , rptPerCondition ) )
missRateAll = np . zeros ( ( len ( trainSeqN ) , rptPerCondition ) )
fpRateAll = np . zeros ( ( len ( trainSeqN ) , rptPerCondition ) )
for i in xrange ( len ( trainSeqN ) ) :
for... |
def encode_as_simple ( name , value ) :
"""Creates an etree element following the simple field convention . Values
are assumed to be strs , unicodes , ints , floats , or Decimals :
> > > element = encode _ as _ simple ( ' foo ' , ' 5 ' )
> > > element . tag = = ' foo '
True
> > > element . text = = ' 5'
... | if isinstance ( value , objectify . ObjectifiedDataElement ) :
return encode_as_simple ( name , unicode ( value ) )
if type ( value ) in _stringable_types :
value = str ( value )
return elements . field ( name , value ) |
def agg_single_func ( values , agg_field , agg_func , group_by = None ) :
"""Aggregates single function
: param values : list of objects ( dict )
: param agg _ field : target field to calculate aggregate
: param agg _ func : aggregate function
: param group _ by : field used to determine group
: return : ... | if len ( values ) == 0 :
return None
else :
if group_by :
group_aggs = pd . DataFrame ( values ) . groupby ( group_by ) . agg ( { agg_field : [ agg_func ] } )
res = { }
for row in group_aggs . itertuples ( ) :
res . update ( { row [ 0 ] : row [ 1 ] } )
return res
... |
def dry_run ( func ) :
"""Dry run : simulate sql execution .""" | @ wraps ( func )
def inner ( dry_run , * args , ** kwargs ) :
ret = func ( dry_run = dry_run , * args , ** kwargs )
if not dry_run :
db . session . commit ( )
else :
db . session . rollback ( )
return ret
return inner |
def bucket ( things , key ) :
"""Return a map of key - > list of things .""" | ret = defaultdict ( list )
for thing in things :
ret [ key ( thing ) ] . append ( thing )
return ret |
def outgoing_connections ( self ) :
"""Returns a list of all outgoing connections for this peer .""" | # Outgoing connections are on the right
return list ( dropwhile ( lambda c : c . direction != OUTGOING , self . connections ) ) |
def from_json ( cls , data , result = None ) :
"""Create new Node element from JSON data
: param data : Element data from JSON
: type data : Dict
: param result : The result this element belongs to
: type result : overpy . Result
: return : New instance of Node
: rtype : overpy . Node
: raises overpy ... | if data . get ( "type" ) != cls . _type_value :
raise exception . ElementDataWrongType ( type_expected = cls . _type_value , type_provided = data . get ( "type" ) )
tags = data . get ( "tags" , { } )
node_id = data . get ( "id" )
lat = data . get ( "lat" )
lon = data . get ( "lon" )
attributes = { }
ignore = [ "typ... |
def _get_file_list ( orig_files , out_file , regions , ref_file , config ) :
"""Create file with region sorted list of non - empty VCFs for concatenating .""" | sorted_files = _sort_by_region ( orig_files , regions , ref_file , config )
exist_files = [ ( c , x ) for c , x in sorted_files if os . path . exists ( x ) and vcf_has_variants ( x ) ]
if len ( exist_files ) == 0 : # no non - empty inputs , merge the empty ones
exist_files = [ x for c , x in sorted_files if os . pa... |
def default_downloader ( directory , urls , filenames , url_prefix = None , clear = False ) :
"""Downloads or clears files from URLs and filenames .
Parameters
directory : str
The directory in which downloaded files are saved .
urls : list
A list of URLs to download .
filenames : list
A list of file n... | # Parse file names from URL if not provided
for i , url in enumerate ( urls ) :
filename = filenames [ i ]
if not filename :
filename = filename_from_url ( url )
if not filename :
raise ValueError ( "no filename available for URL '{}'" . format ( url ) )
filenames [ i ] = filename
files ... |
def launch_minecraft ( port , installdir = "MalmoPlatform" , replaceable = False ) :
"""Launch Minecraft listening for malmoenv connections .
Args :
port : the TCP port to listen on .
installdir : the install dir name . Defaults to MalmoPlatform .
Must be same as given ( or defaulted ) in download call if u... | launch_script = './launchClient.sh'
if os . name == 'nt' :
launch_script = 'launchClient.bat'
cwd = os . getcwd ( )
os . chdir ( installdir )
os . chdir ( "Minecraft" )
try :
cmd = [ launch_script , '-port' , str ( port ) , '-env' ]
if replaceable :
cmd . append ( '-replaceable' )
subprocess . c... |
def initialize_library ( self , library , lib_type = VERSION_STORE , ** kwargs ) :
"""Create an Arctic Library or a particular type .
Parameters
library : ` str `
The name of the library . e . g . ' library ' or ' user . library '
lib _ type : ` str `
The type of the library . e . g . arctic . VERSION _ S... | lib = ArcticLibraryBinding ( self , library )
# check that we don ' t create too many namespaces
# can be disabled check _ library _ count = False
check_library_count = kwargs . pop ( 'check_library_count' , True )
if len ( self . _conn [ lib . database_name ] . list_collection_names ( ) ) > 5000 and check_library_coun... |
def scan ( self ) :
"""Start a thread for each registered scan function to scan proxy lists""" | self . logger . info ( '{0} registered scan functions, starting {0} threads ' 'to scan candidate proxy lists...' . format ( len ( self . scan_funcs ) ) )
for i in range ( len ( self . scan_funcs ) ) :
t = threading . Thread ( name = self . scan_funcs [ i ] . __name__ , target = self . scan_funcs [ i ] , kwargs = se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.