signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def paste_to_current_cell ( self , tl_key , data , freq = None ) :
"""Pastes data into grid from top left cell tl _ key
Parameters
ul _ key : Tuple
\key of top left cell of paste area
data : iterable of iterables where inner iterable returns string
\t The outer iterable represents rows
freq : Integer , ... | self . pasting = True
grid_rows , grid_cols , __ = self . grid . code_array . shape
self . need_abort = False
tl_row , tl_col , tl_tab = self . _get_full_key ( tl_key )
row_overflow = False
col_overflow = False
no_pasted_cells = 0
for src_row , row_data in enumerate ( data ) :
target_row = tl_row + src_row
if s... |
def draw ( self , writer , idx , offset ) :
"""Draw the current page view to ` ` writer ` ` .
: param writer : callable writes to output stream , receiving unicode .
: type writer : callable
: param idx : current page index .
: type idx : int
: param offset : scrolling region offset of current page .
: ... | # as our screen can be resized while we ' re mid - calculation ,
# our self . dirty flag can become re - toggled ; because we are
# not re - flowing our pagination , we must begin over again .
while self . dirty :
self . draw_heading ( writer )
self . dirty = self . STATE_CLEAN
( idx , offset ) , data = sel... |
def whichEncoding ( self ) :
"""How should I be encoded ?
@ returns : one of ENCODE _ URL , ENCODE _ HTML _ FORM , or ENCODE _ KVFORM .
@ change : 2.1.0 added the ENCODE _ HTML _ FORM response .""" | if self . request . mode in BROWSER_REQUEST_MODES :
if self . fields . getOpenIDNamespace ( ) == OPENID2_NS and len ( self . encodeToURL ( ) ) > OPENID1_URL_LIMIT :
return ENCODE_HTML_FORM
else :
return ENCODE_URL
else :
return ENCODE_KVFORM |
def get_instance ( self , payload ) :
"""Build an instance of WorkersCumulativeStatisticsInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . taskrouter . v1 . workspace . worker . workers _ cumulative _ statistics . WorkersCumulativeStatisticsInstance
: rtype : twilio . r... | return WorkersCumulativeStatisticsInstance ( self . _version , payload , workspace_sid = self . _solution [ 'workspace_sid' ] , ) |
def write ( self , data ) :
"""Writes data to the device .
: param data : data to write
: type data : string
: returns : number of bytes sent
: raises : : py : class : ` ~ alarmdecoder . util . CommError `""" | data_sent = None
try :
if isinstance ( data , str ) :
data = data . encode ( 'utf-8' )
data_sent = self . _device . send ( data )
if data_sent == 0 :
raise CommError ( 'Error writing to device.' )
self . on_write ( data = data )
except ( SSL . Error , socket . error ) as err :
raise ... |
def _disks_equal ( disk1 , disk2 ) :
'''Test if two disk elements should be considered like the same device''' | target1 = disk1 . find ( 'target' )
target2 = disk2 . find ( 'target' )
source1 = ElementTree . tostring ( disk1 . find ( 'source' ) ) if disk1 . find ( 'source' ) is not None else None
source2 = ElementTree . tostring ( disk2 . find ( 'source' ) ) if disk2 . find ( 'source' ) is not None else None
return source1 == so... |
def create_from_cellranger ( indir : str , outdir : str = None , genome : str = None ) -> str :
"""Create a . loom file from 10X Genomics cellranger output
Args :
indir ( str ) : path to the cellranger output folder ( the one that contains ' outs ' )
outdir ( str ) : output folder wher the new loom file shoul... | if outdir is None :
outdir = indir
sampleid = os . path . split ( os . path . abspath ( indir ) ) [ - 1 ]
matrix_folder = os . path . join ( indir , 'outs' , 'filtered_gene_bc_matrices' )
if os . path . exists ( matrix_folder ) :
if genome is None :
genome = [ f for f in os . listdir ( matrix_folder ) i... |
def cancel_order ( self , order_param ) :
"""Cancel an open order .
Parameters
order _ param : str or Order
The order _ id or order object to cancel .""" | order_id = order_param
if isinstance ( order_param , zipline . protocol . Order ) :
order_id = order_param . id
self . blotter . cancel ( order_id ) |
def fix_tour ( self , tour ) :
"""Test each scaffold if dropping does not decrease LMS .""" | scaffolds , oos = zip ( * tour )
keep = set ( )
for mlg in self . linkage_groups :
lg = mlg . lg
for s , o in tour :
i = scaffolds . index ( s )
L = [ self . get_series ( lg , x , xo ) for x , xo in tour [ : i ] ]
U = [ self . get_series ( lg , x , xo ) for x , xo in tour [ i + 1 : ] ]
... |
def to_pandas ( self ) :
"""Returns the dataset as two pandas objects : X and y .
Returns
X : DataFrame with shape ( n _ instances , n _ features )
A pandas DataFrame containing feature data and named columns .
y : Series with shape ( n _ instances , )
A pandas Series containing target data and an index t... | # Ensure the metadata is valid before continuing
if self . meta is None :
raise DatasetsError ( ( "the downloaded dataset was improperly packaged without meta.json " "- please report this bug to the Yellowbrick maintainers!" ) )
if "features" not in self . meta or "target" not in self . meta :
raise DatasetsErr... |
def snapshotToMovie ( snap , filename , * args , ** kwargs ) :
"""NAME :
snapshotToMovie
PURPOSE :
turn a list of snapshots into a movie
INPUT :
snap - the snapshots ( list )
filename - name of the file to save the movie to
framerate = in fps
bitrate = ?
thumbnail = False : create thumbnail image ... | if kwargs . has_key ( 'tmpdir' ) :
tmpdir = kwargs [ 'tmpdir' ]
kwargs . pop ( 'tmpdir' )
else :
tmpdir = '/tmp'
if kwargs . has_key ( 'framerate' ) :
framerate = kwargs [ 'framerate' ]
kwargs . pop ( 'framerate' )
else :
framerate = 25
if kwargs . has_key ( 'bitrate' ) :
bitrate = kwargs [ ... |
def secret_from_transfer_task ( transfer_task : Optional [ TransferTask ] , secrethash : SecretHash , ) -> Optional [ Secret ] :
"""Return the secret for the transfer , None on EMPTY _ SECRET .""" | assert isinstance ( transfer_task , InitiatorTask )
transfer_state = transfer_task . manager_state . initiator_transfers [ secrethash ]
if transfer_state is None :
return None
return transfer_state . transfer_description . secret |
def assemble ( self , module , * modules , ** kwargs ) : # type : ( AbstractModule , * AbstractModule , * * Any ) - > SeqRecord
"""Assemble the provided modules into the vector .
Arguments :
module ( ` ~ moclo . base . modules . AbstractModule ` ) : a module to insert
in the vector .
modules ( ` ~ moclo . b... | mgr = AssemblyManager ( vector = self , modules = [ module ] + list ( modules ) , name = kwargs . get ( "name" , "assembly" ) , id_ = kwargs . get ( "id" , "assembly" ) , )
return mgr . assemble ( ) |
def run_ut_py3_qemu ( ) :
"""Run unit tests in the emulator and copy the results back to the host through the mounted
volume in / mxnet""" | from vmcontrol import VM
with VM ( ) as vm :
qemu_provision ( vm . ssh_port )
logging . info ( "execute tests" )
qemu_ssh ( vm . ssh_port , "./runtime_functions.py" , "run_ut_python3_qemu_internal" )
qemu_rsync_to_host ( vm . ssh_port , "*.xml" , "mxnet" )
logging . info ( "copied to host" )
log... |
def _sparse_mux ( sel , vals ) :
"""Mux that avoids instantiating unnecessary mux _ 2s when possible .
: param WireVector sel : Select wire , determines what is selected on a given cycle
: param { int : WireVector } vals : dictionary to store the values that are
: return : Wirevector that signifies the change... | items = list ( vals . values ( ) )
if len ( vals ) <= 1 :
if len ( vals ) == 0 :
raise pyrtl . PyrtlError ( "Needs at least one parameter for val" )
return items [ 0 ]
if len ( sel ) == 1 :
try :
false_result = vals [ 0 ]
true_result = vals [ 1 ]
except KeyError :
raise p... |
def from_coo ( cls , obj , vartype = None ) :
"""Deserialize a binary quadratic model from a COOrdinate _ format encoding .
. . _ COOrdinate : https : / / en . wikipedia . org / wiki / Sparse _ matrix # Coordinate _ list _ ( COO )
Args :
obj : ( str / file ) :
Either a string or a ` . read ( ) ` - supportin... | import dimod . serialization . coo as coo
if isinstance ( obj , str ) :
return coo . loads ( obj , cls = cls , vartype = vartype )
return coo . load ( obj , cls = cls , vartype = vartype ) |
def save ( self , filename , strip_prefix = '' ) :
"""Save parameters to file .
Parameters
filename : str
Path to parameter file .
strip _ prefix : str , default ' '
Strip prefix from parameter names before saving .""" | arg_dict = { }
for param in self . values ( ) :
weight = param . _reduce ( )
if not param . name . startswith ( strip_prefix ) :
raise ValueError ( "Prefix '%s' is to be striped before saving, but Parameter's " "name '%s' does not start with '%s'. " "this may be due to your Block shares parameters from ... |
def sendTo ( self , dest , chunkSize ) :
"""Send this difference to the dest Store .""" | vol = self . toVol
paths = self . sink . getPaths ( vol )
if self . sink == dest :
logger . info ( "Keep: %s" , self )
self . sink . keep ( self )
else : # Log , but don ' t skip yet , so we can log more detailed skipped actions later
skipDryRun ( logger , dest . dryrun , 'INFO' ) ( "Xfer: %s" , self )
... |
def _surfdens ( self , R , z , phi = 0. , t = 0. ) :
"""NAME :
_ surfdens
PURPOSE :
evaluate the surface density for this potential
INPUT :
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT :
the density
HISTORY :
2018-08-04 - Written - Bovy ( UofT )""" | if R > self . a :
return 0.
h = nu . sqrt ( self . a2 - R ** 2 )
if z < h :
return 0.
else :
return 1. / ( 2. * nu . pi * self . a * h ) |
def get_class ( name , config_key , module ) :
"""Get the class by its name as a string .""" | clsmembers = inspect . getmembers ( module , inspect . isclass )
for string_name , act_class in clsmembers :
if string_name == name :
return act_class
# Check if the user has specified a plugin and if the class is in there
cfg = get_project_configuration ( )
if config_key in cfg :
modname = os . path . ... |
def get_pval_uncorr ( self , study , log = sys . stdout ) :
"""Calculate the uncorrected pvalues for study items .""" | results = [ ]
study_in_pop = self . pop . intersection ( study )
# " 99 % 378 of 382 study items found in population "
go2studyitems = get_terms ( "study" , study_in_pop , self . assoc , self . obo_dag , log )
pop_n , study_n = self . pop_n , len ( study_in_pop )
allterms = set ( go2studyitems ) . union ( set ( self . ... |
def add_value ( self , value , row , col ) :
"""Adds a single value ( cell ) to a worksheet at ( row , col ) .
Return the ( row , col ) where the value has been put .
: param value : Value to write to the sheet .
: param row : Row where the value should be written .
: param col : Column where the value shou... | self . __values [ ( row , col ) ] = value |
def execute ( desktop_file , files = None , return_cmd = False , background = False ) :
'''Execute a . desktop file .
Executes a given . desktop file path properly .
Args :
desktop _ file ( str ) : The path to the . desktop file .
files ( list ) : Any files to be launched by the . desktop . Defaults to empt... | # Attempt to manually parse and execute
desktop_file_exec = parse ( desktop_file ) [ 'Exec' ]
for i in desktop_file_exec . split ( ) :
if i . startswith ( '%' ) :
desktop_file_exec = desktop_file_exec . replace ( i , '' )
desktop_file_exec = desktop_file_exec . replace ( r'%F' , '' )
desktop_file_exec = des... |
def main ( args = None ) :
"""Phablet command line user interface
This function implements the phablet command line tool""" | parser = argparse . ArgumentParser ( description = _ ( "Run a command on Ubuntu Phablet" ) , epilog = """
This tool will start ssh on your connected Ubuntu Touch device, forward
a local port to the device, copy your ssh id down to the device (so you
can log in without a password), and then ssh i... |
def sizes ( x ) :
"""Get a structure of sizes for a structure of nested arrays .""" | def size ( x ) :
try :
return x . size
except Exception : # pylint : disable = broad - except
return 0
return nested_map ( x , size ) |
def query ( self , q , data = None , union = True , limit = None ) :
"""Query your database with a raw string .
Parameters
q : str
Query string to execute
data : list , dict
Optional argument for handlebars - queries . Data will be passed to the
template and rendered using handlebars .
union : bool
... | if data :
q = self . _apply_handlebars ( q , data , union )
if limit :
q = self . _assign_limit ( q , limit )
return pd . read_sql ( q , self . con ) |
def list_functions ( region = None , key = None , keyid = None , profile = None ) :
'''List all Lambda functions visible in the current scope .
CLI Example :
. . code - block : : bash
salt myminion boto _ lambda . list _ functions''' | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
ret = [ ]
for funcs in __utils__ [ 'boto3.paged_call' ] ( conn . list_functions ) :
ret += funcs [ 'Functions' ]
return ret |
def expand_matrix_in_orthogonal_basis ( m : np . ndarray , basis : Dict [ str , np . ndarray ] , ) -> value . LinearDict [ str ] :
"""Computes coefficients of expansion of m in basis .
We require that basis be orthogonal w . r . t . the Hilbert - Schmidt inner
product . We do not require that basis be orthonorm... | return value . LinearDict ( { name : ( hilbert_schmidt_inner_product ( b , m ) / hilbert_schmidt_inner_product ( b , b ) ) for name , b in basis . items ( ) } ) |
def get_padding_bias ( x ) :
"""Calculate bias tensor from padding values in tensor .
Bias tensor that is added to the pre - softmax multi - headed attention logits ,
which has shape [ batch _ size , num _ heads , length , length ] . The tensor is zero at
non - padding locations , and - 1e9 ( negative infinit... | with tf . name_scope ( "attention_bias" ) :
padding = get_padding ( x )
attention_bias = padding * _NEG_INF
attention_bias = tf . expand_dims ( tf . expand_dims ( attention_bias , axis = 1 ) , axis = 1 )
return attention_bias |
def circ_axial ( alpha , n ) :
"""Transforms n - axial data to a common scale .
Parameters
alpha : array
Sample of angles in radians
n : int
Number of modes
Returns
alpha : float
Transformed angles
Notes
Tranform data with multiple modes ( known as axial data ) to a unimodal
sample , for the p... | alpha = np . array ( alpha )
return np . remainder ( alpha * n , 2 * np . pi ) |
async def _start ( self , app : web . Application ) -> None :
"""Start sirbot""" | logger . info ( 'Starting Sir Bot-a-lot ...' )
await self . _start_plugins ( )
logger . info ( 'Sir Bot-a-lot fully started' ) |
def parse_date ( datestring , default_timezone = UTC ) :
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string . However it is quite common to
have dates without a timezone ( not strictly correct ) . In this case the
default timezone specified in default _ timezone is used... | if not isinstance ( datestring , basestring ) :
raise ParseError ( "Expecting a string %r" % datestring )
m = ISO8601_REGEX . match ( datestring )
if not m :
raise ParseError ( "Unable to parse date string %r" % datestring )
groups = m . groupdict ( )
tz = parse_timezone ( groups [ "timezone" ] , default_timezo... |
def cachedproperty ( func ) :
"""A memoize decorator for class properties .""" | key = '_' + func . __name__
@ wraps ( func )
def get ( self ) :
try :
return getattr ( self , key )
except AttributeError :
val = func ( self )
setattr ( self , key , val )
return val
return property ( get ) |
def bulk_modify ( self , * filters_or_records , ** kwargs ) :
"""Shortcut to bulk modify records
. . versionadded : : 2.17.0
Args :
* filters _ or _ records ( tuple ) or ( Record ) : Either a list of Records , or a list of filters .
Keyword Args :
values ( dict ) : Dictionary of one or more ' field _ name... | values = kwargs . pop ( 'values' , None )
if kwargs :
raise ValueError ( 'Unexpected arguments: {}' . format ( kwargs ) )
if not values :
raise ValueError ( 'Must provide "values" as keyword argument' )
if not isinstance ( values , dict ) :
raise ValueError ( "values parameter must be dict of {'field_name':... |
def verify_response_time ( self , expected_below ) :
"""Verify that response time ( time span between request - response ) is reasonable .
: param expected _ below : integer
: return : Nothing
: raises : ValueError if timedelta > expected time""" | if self . timedelta > expected_below :
raise ValueError ( "Response time is more (%f) than expected (%f)!" % ( self . timedelta , expected_below ) ) |
def load_config_file ( self , location ) :
"""Load a rotation scheme and other options from a configuration file .
: param location : Any value accepted by : func : ` coerce _ location ( ) ` .
: returns : The configured or given : class : ` Location ` object .""" | location = coerce_location ( location )
for configured_location , rotation_scheme , options in load_config_file ( self . config_file , expand = False ) :
if configured_location . match ( location ) :
logger . verbose ( "Loading configuration for %s .." , location )
if rotation_scheme :
s... |
def _parse_byte_data ( self , byte_data ) :
"""Extract the values from byte string .""" | self . length , self . data_type = unpack ( '<ii' , byte_data [ : self . size ] ) |
def maintainer ( self ) :
"""> > > package = yarg . get ( ' yarg ' )
> > > package . maintainer
Maintainer ( name = u ' Kura ' , email = u ' kura @ kura . io ' )""" | maintainer = namedtuple ( 'Maintainer' , 'name email' )
return maintainer ( name = self . _package [ 'maintainer' ] , email = self . _package [ 'maintainer_email' ] ) |
def _get_mapping ( self , schema ) :
"""Get mapping for given resource or item schema .
: param schema : resource or dict / list type item schema""" | properties = { }
for field , field_schema in schema . items ( ) :
field_mapping = self . _get_field_mapping ( field_schema )
if field_mapping :
properties [ field ] = field_mapping
return { 'properties' : properties } |
def record_result ( self , res , prg = '' ) :
"""record the output of the command . Records the result , can have
multiple results , so will need to work out a consistent way to aggregate this""" | self . _log ( self . logFileResult , force_to_string ( res ) , prg ) |
def feed ( self , data ) :
"""added this check as sometimes we are getting the data in integer format instead of string""" | try :
self . rawdata = self . rawdata + data
except TypeError :
data = unicode ( data )
self . rawdata = self . rawdata + data
self . goahead ( 0 ) |
def setLength ( self , personID , length ) :
"""setLength ( string , double ) - > None
Sets the length in m for the given person .""" | self . _connection . _sendDoubleCmd ( tc . CMD_SET_PERSON_VARIABLE , tc . VAR_LENGTH , personID , length ) |
def trigger_all_change_callbacks ( self ) :
"""Trigger all callbacks that were set with on _ change ( ) .""" | return [ ret for key in DatastoreLegacy . store [ self . domain ] . keys ( ) for ret in self . trigger_change_callbacks ( key ) ] |
def generate_machine_id ( new = False , destination_file = constants . machine_id_file ) :
"""Generate a machine - id if / etc / insights - client / machine - id does not exist""" | machine_id = None
machine_id_file = None
logging_name = 'machine-id'
if os . path . isfile ( destination_file ) and not new :
logger . debug ( 'Found %s' , destination_file )
with open ( destination_file , 'r' ) as machine_id_file :
machine_id = machine_id_file . read ( )
else :
logger . debug ( 'Co... |
def from_pauli ( pauli , coeff = 1.0 ) :
"""Make new Term from an Pauli operator""" | if pauli . is_identity or coeff == 0 :
return Term ( ( ) , coeff )
return Term ( ( pauli , ) , coeff ) |
def mkdir ( directory , exists_okay ) :
"""Create a directory on the board .
Mkdir will create the specified directory on the board . One argument is
required , the full path of the directory to create .
Note that you cannot recursively create a hierarchy of directories with one
mkdir command , instead you ... | # Run the mkdir command .
board_files = files . Files ( _board )
board_files . mkdir ( directory , exists_okay = exists_okay ) |
def shell_split ( text ) :
"""Split the string ` text ` using shell - like syntax
This avoids breaking single / double - quoted strings ( e . g . containing
strings with spaces ) . This function is almost equivalent to the shlex . split
function ( see standard library ` shlex ` ) except that it is supporting ... | assert is_text_string ( text )
# in case a QString is passed . . .
pattern = r'(\s+|(?<!\\)".*?(?<!\\)"|(?<!\\)\'.*?(?<!\\)\')'
out = [ ]
for token in re . split ( pattern , text ) :
if token . strip ( ) :
out . append ( token . strip ( '"' ) . strip ( "'" ) )
return out |
def handle_symbol_search ( self , call_id , payload ) :
"""Handler for symbol search results""" | self . log . debug ( 'handle_symbol_search: in %s' , Pretty ( payload ) )
syms = payload [ "syms" ]
qfList = [ ]
for sym in syms :
p = sym . get ( "pos" )
if p :
item = self . editor . to_quickfix_item ( str ( p [ "file" ] ) , p [ "line" ] , str ( sym [ "name" ] ) , "info" )
qfList . append ( it... |
def update_feed ( self , feed , feed_id ) :
"""UpdateFeed .
[ Preview API ] Change the attributes of a feed .
: param : class : ` < FeedUpdate > < azure . devops . v5_0 . feed . models . FeedUpdate > ` feed : A JSON object containing the feed settings to be updated .
: param str feed _ id : Name or Id of the ... | route_values = { }
if feed_id is not None :
route_values [ 'feedId' ] = self . _serialize . url ( 'feed_id' , feed_id , 'str' )
content = self . _serialize . body ( feed , 'FeedUpdate' )
response = self . _send ( http_method = 'PATCH' , location_id = 'c65009a7-474a-4ad1-8b42-7d852107ef8c' , version = '5.0-preview.1... |
def comparison ( ) :
r"""CommandLine :
python - m utool . experimental . dynamic _ connectivity comparison - - profile
python - m utool . experimental . dynamic _ connectivity comparison""" | n = 12
a , b = 9 , 20
num = 3
import utool
for timer in utool . Timerit ( num , 'old bst version (PY)' ) :
g = nx . balanced_tree ( 2 , n )
self = TestETT . from_tree ( g , version = 'bst' , fast = False )
with timer :
self . delete_edge_bst_version ( a , b , bstjoin = False )
import utool
for timer... |
def delete ( self , ** kwargs ) :
"""Removes this app object from the platform .
The current user must be a developer of the app .""" | if self . _dxid is not None :
return dxpy . api . app_delete ( self . _dxid , ** kwargs )
else :
return dxpy . api . app_delete ( 'app-' + self . _name , alias = self . _alias , ** kwargs ) |
def _ensure_url_has_path ( self , url ) :
"""ensure the url has a path component
eg . http : / / example . com # abc converted to http : / / example . com / # abc""" | inx = url . find ( '://' )
if inx > 0 :
rest = url [ inx + 3 : ]
elif url . startswith ( '//' ) :
rest = url [ 2 : ]
else :
rest = url
if '/' in rest :
return url
scheme , netloc , path , query , frag = urlsplit ( url )
if not path :
path = '/'
url = urlunsplit ( ( scheme , netloc , path , query , f... |
def dd2dm ( dd ) :
"""Convert decimal to degrees , decimal minutes""" | d , m , s = dd2dms ( dd )
m = m + float ( s ) / 3600
return d , m , s |
def normalize_full_name_false ( decl ) :
"""Cached variant of normalize
Args :
decl ( declaration . declaration _ t ) : the declaration
Returns :
str : normalized name""" | if decl . cache . normalized_full_name_false is None :
decl . cache . normalized_full_name_false = normalize ( declaration_utils . full_name ( decl , with_defaults = False ) )
return decl . cache . normalized_full_name_false |
def make_name_from_git ( repo , branch , limit = 53 , separator = '-' , hash_size = 5 ) :
"""return name string representing the given git repo and branch
to be used as a build name .
NOTE : Build name will be used to generate pods which have a
limit of 64 characters and is composed as :
< buildname > - < b... | branch = branch or 'unknown'
full = urlparse ( repo ) . path . lstrip ( '/' ) + branch
repo = git_repo_humanish_part_from_uri ( repo )
shaval = sha256 ( full . encode ( 'utf-8' ) ) . hexdigest ( )
hash_str = shaval [ : hash_size ]
limit = limit - len ( hash_str ) - 1
sanitized = sanitize_strings_for_openshift ( repo , ... |
def curve_constructor ( curve ) :
"""Image for : class ` . Curve ` docstring .""" | if NO_IMAGES :
return
ax = curve . plot ( 256 )
line = ax . lines [ 0 ]
nodes = curve . _nodes
ax . plot ( nodes [ 0 , : ] , nodes [ 1 , : ] , color = "black" , linestyle = "None" , marker = "o" )
add_patch ( ax , nodes , line . get_color ( ) )
ax . axis ( "scaled" )
ax . set_xlim ( - 0.125 , 1.125 )
ax . set_ylim ... |
def sample_surface_even ( mesh , count ) :
"""Sample the surface of a mesh , returning samples which are
approximately evenly spaced .
Parameters
mesh : Trimesh object
count : number of points to return
Returns
samples : ( count , 3 ) points in space on the surface of mesh
face _ index : ( count , ) i... | from . points import remove_close
radius = np . sqrt ( mesh . area / ( 2 * count ) )
samples , ids = sample_surface ( mesh , count * 5 )
result , mask = remove_close ( samples , radius )
return result , ids [ mask ] |
def dumps ( voevent , pretty_print = False , xml_declaration = True , encoding = 'UTF-8' ) :
"""Converts voevent to string .
. . note : : Default encoding is UTF - 8 , in line with VOE2.0 schema .
Declaring the encoding can cause diffs with the original loaded VOEvent ,
but I think it ' s probably the right t... | vcopy = copy . deepcopy ( voevent )
_return_to_standard_xml ( vcopy )
s = etree . tostring ( vcopy , pretty_print = pretty_print , xml_declaration = xml_declaration , encoding = encoding )
return s |
def _get_post_url ( self , obj ) :
"""Needed to retrieve the changelist url as Folder / File can be extended
and admin url may change""" | # Code from django ModelAdmin to determine changelist on the fly
opts = obj . _meta
return reverse ( 'admin:%s_%s_changelist' % ( opts . app_label , opts . model_name ) , current_app = self . admin_site . name ) |
def verify_experiment_module ( verbose ) :
"""Perform basic sanity checks on experiment . py .""" | ok = True
if not os . path . exists ( "experiment.py" ) :
return False
# Bootstrap a package in a temp directory and make it importable :
temp_package_name = "TEMP_VERIFICATION_PACKAGE"
tmp = tempfile . mkdtemp ( )
clone_dir = os . path . join ( tmp , temp_package_name )
to_ignore = shutil . ignore_patterns ( os . ... |
def ack ( self , delivery_tag , multiple = False ) :
'''Acknowledge delivery of a message . If multiple = True , acknowledge up - to
and including delivery _ tag .''' | args = Writer ( )
args . write_longlong ( delivery_tag ) . write_bit ( multiple )
self . send_frame ( MethodFrame ( self . channel_id , 60 , 80 , args ) ) |
def getDirectory ( rh ) :
"""Get the virtual machine ' s directory statements .
Input :
Request Handle with the following properties :
function - ' CMDVM '
subfunction - ' CMD '
userid - userid of the virtual machine
Output :
Request Handle updated with the results .
Return code - 0 : ok , non - zer... | rh . printSysLog ( "Enter getVM.getDirectory" )
parms = [ "-T" , rh . userid ]
results = invokeSMCLI ( rh , "Image_Query_DM" , parms )
if results [ 'overallRC' ] == 0 :
results [ 'response' ] = re . sub ( '\*DVHOPT.*' , '' , results [ 'response' ] )
rh . printLn ( "N" , results [ 'response' ] )
else : # SMAPI A... |
def _setbin_safe ( self , binstring ) :
"""Reset the bitstring to the value given in binstring .""" | binstring = tidy_input_string ( binstring )
# remove any 0b if present
binstring = binstring . replace ( '0b' , '' )
self . _setbin_unsafe ( binstring ) |
def compute_tls13_resumption_secret ( self ) :
"""self . handshake _ messages should be ClientHello . . . ClientFinished .""" | if self . connection_end == "server" :
hkdf = self . prcs . hkdf
elif self . connection_end == "client" :
hkdf = self . pwcs . hkdf
rs = hkdf . derive_secret ( self . tls13_master_secret , b"resumption master secret" , b"" . join ( self . handshake_messages ) )
self . tls13_derived_secrets [ "resumption_secret"... |
def sign_execute_withdrawal ( withdrawal_params , key_pair ) :
"""Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function .
Execution of this function is as follows : :
sign _ execute _ withdrawal ( withdrawal _ params = signable _ params , private _ k... | withdrawal_id = withdrawal_params [ 'id' ]
signable_params = { 'id' : withdrawal_id , 'timestamp' : get_epoch_milliseconds ( ) }
encoded_message = encode_message ( signable_params )
execute_params = signable_params . copy ( )
execute_params [ 'signature' ] = sign_message ( encoded_message = encoded_message , private_ke... |
def outLineReceived ( self , line ) :
"""Handle data via stdout linewise . This is useful if you turned off
buffering .
In your subclass , override this if you want to handle the line as a
protocol line in addition to logging it . ( You may upcall this function
safely . )""" | log_debug ( '<<< {name} stdout >>> {line}' , name = self . name , line = self . outFilter ( line ) ) |
def value ( self ) :
"""Returns the current load average as a value between 0.0 ( representing
the * min _ load _ average * value ) and 1.0 ( representing the
* max _ load _ average * value ) . These default to 0.0 and 1.0 respectively .""" | load_average_range = self . max_load_average - self . min_load_average
return ( self . load_average - self . min_load_average ) / load_average_range |
def dumps ( obj , skipkeys = False , ensure_ascii = True , check_circular = True , allow_nan = True , cls = None , indent = None , separators = None , encoding = 'utf-8' , default = None , use_decimal = True , namedtuple_as_object = True , tuple_as_array = True , bigint_as_string = False , sort_keys = False , item_sort... | # cached encoder
if ( not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not iterable_as_array and not bigint_as_string and not sort_keys and ... |
def __init_from_csc ( self , csc , params_str , ref_dataset ) :
"""Initialize data from a CSC matrix .""" | if len ( csc . indices ) != len ( csc . data ) :
raise ValueError ( 'Length mismatch: {} vs {}' . format ( len ( csc . indices ) , len ( csc . data ) ) )
self . handle = ctypes . c_void_p ( )
ptr_indptr , type_ptr_indptr , __ = c_int_array ( csc . indptr )
ptr_data , type_ptr_data , _ = c_float_array ( csc . data )... |
def broadcast ( * sinks_ ) :
"""The | broadcast | decorator creates a | push | object that receives a
message by ` ` yield ` ` and then sends this message on to all the given sinks .
. . | broadcast | replace : : : py : func : ` broadcast `""" | @ push
def bc ( ) :
sinks = [ s ( ) for s in sinks_ ]
while True :
msg = yield
for s in sinks :
s . send ( msg )
return bc |
def equal ( lhs , rhs ) :
"""Returns the result of element - wise * * equal to * * ( = = ) comparison operation with
broadcasting .
For each element in input arrays , return 1 ( true ) if corresponding elements are same ,
otherwise return 0 ( false ) .
Equivalent to ` ` lhs = = rhs ` ` and ` ` mx . nd . bro... | # pylint : disable = no - member , protected - access
return _ufunc_helper ( lhs , rhs , op . broadcast_equal , lambda x , y : 1 if x == y else 0 , _internal . _equal_scalar , None ) |
def configure ( ctx , integration , args , show_args , editable ) :
"""Configure an integration with default parameters .
You can still provide one - off integration arguments to : func : ` honeycomb . commands . service . run ` if required .""" | home = ctx . obj [ "HOME" ]
integration_path = plugin_utils . get_plugin_path ( home , defs . INTEGRATIONS , integration , editable )
logger . debug ( "running command %s (%s)" , ctx . command . name , ctx . params , extra = { "command" : ctx . command . name , "params" : ctx . params } )
logger . debug ( "loading {} (... |
def DictOf ( name , * fields ) :
"""This function creates a dict type with the specified name and fields .
> > > from pyws . functions . args import DictOf , Field
> > > dct = DictOf (
. . . ' HelloWorldDict ' , Field ( ' hello ' , str ) , Field ( ' hello ' , int ) )
> > > issubclass ( dct , Dict )
True
... | ret = type ( name , ( Dict , ) , { 'fields' : [ ] } )
# noinspection PyUnresolvedReferences
ret . add_fields ( * fields )
return ret |
from typing import List , Tuple , Union
def count_frequency_of_elements ( t : Tuple [ Union [ str , int ] ] , l : List [ Union [ str , int ] ] ) -> int :
"""A function to count the occurrences of all elements from a list within a tuple .
Args :
t ( Tuple [ Union [ str , int ] ] ) : A tuple containing elements .... | total_count = 0
for element in t :
if element in l :
total_count += 1
return total_count |
def remove_node ( self , node , stop = False ) :
"""Removes a node from the cluster .
By default , it doesn ' t also stop the node , just remove from
the known hosts of this cluster .
: param node : node to remove
: type node : : py : class : ` Node `
: param stop : Stop the node
: type stop : bool""" | if node . kind not in self . nodes :
raise NodeNotFound ( "Unable to remove node %s: invalid node type `%s`." , node . name , node . kind )
else :
try :
index = self . nodes [ node . kind ] . index ( node )
if self . nodes [ node . kind ] [ index ] :
del self . nodes [ node . kind ] ... |
def list_upgrades ( refresh = True , ** kwargs ) : # pylint : disable = unused - argument
'''List all available package upgrades .
CLI Example :
. . code - block : : bash
salt ' * ' pkg . list _ upgrades''' | ret = { }
if salt . utils . data . is_true ( refresh ) :
refresh_db ( )
cmd = [ 'opkg' , 'list-upgradable' ]
call = __salt__ [ 'cmd.run_all' ] ( cmd , output_loglevel = 'trace' , python_shell = False )
if call [ 'retcode' ] != 0 :
comment = ''
if 'stderr' in call :
comment += call [ 'stderr' ]
i... |
def _GetPathSegmentIndexForValueWeights ( self , value_weights ) :
"""Retrieves the index of the path segment based on value weights .
Args :
value _ weights : the value weights object ( instance of _ PathSegmentWeights ) .
Returns :
An integer containing the path segment index .
Raises :
RuntimeError :... | largest_weight = value_weights . GetLargestWeight ( )
if largest_weight > 0 :
value_weight_indexes = value_weights . GetIndexesForWeight ( largest_weight )
else :
value_weight_indexes = [ ]
if value_weight_indexes :
path_segment_index = value_weight_indexes [ 0 ]
else :
path_segment_index = value_weight... |
def start_instance ( self , key_name , public_key_path , private_key_path , security_group , flavor , image_id , image_userdata , username = None , node_name = None , network_ids = None , price = None , timeout = None , boot_disk_device = None , boot_disk_size = None , boot_disk_type = None , boot_disk_iops = None , pl... | connection = self . _connect ( )
log . debug ( "Checking keypair `%s`." , key_name )
# the ` _ check _ keypair ` method has to be called within a lock ,
# since it will upload the key if it does not exist and if this
# happens for every node at the same time ec2 will throw an error
# message ( see issue # 79)
with Boto... |
def icon ( self ) :
"""Returns the URL of a recommended icon for display .""" | if self . _icon == '' and self . details != None and 'icon' in self . details :
self . _icon = self . details [ 'icon' ]
return self . _icon |
def get_or_load_name ( self , type_ , id_ , method ) :
"""read - through cache for a type of object ' s name .
If we don ' t have a cached name for this type / id , then we will query the
live Koji server and store the value before returning .
: param type _ : str , " user " or " tag "
: param id _ : int , ... | name = self . get_name ( type_ , id_ )
if name is not None :
defer . returnValue ( name )
instance = yield method ( id_ )
if instance is None :
defer . returnValue ( None )
self . put_name ( type_ , id_ , instance . name )
defer . returnValue ( instance . name ) |
def turn_physical_off ( self ) :
"""NAME :
turn _ physical _ off
PURPOSE :
turn off automatic returning of outputs in physical units
INPUT :
( none )
OUTPUT :
( none )
HISTORY :
2014-06-17 - Written - Bovy ( IAS )""" | self . _roSet = False
self . _voSet = False
self . _orb . turn_physical_off ( ) |
def object_factory ( api , api_version , kind ) :
"""Dynamically builds a Python class for the given Kubernetes object in an API .
For example :
api = pykube . HTTPClient ( . . . )
NetworkPolicy = pykube . object _ factory ( api , " networking . k8s . io / v1 " , " NetworkPolicy " )
This enables constructio... | resource_list = api . resource_list ( api_version )
resource = next ( ( resource for resource in resource_list [ "resources" ] if resource [ "kind" ] == kind ) , None )
base = NamespacedAPIObject if resource [ "namespaced" ] else APIObject
return type ( kind , ( base , ) , { "version" : api_version , "endpoint" : resou... |
def update ( self , move ) :
"""Updates position by applying selected move
: type : move : Move""" | if move is None :
raise TypeError ( "Move cannot be type None" )
if self . king_loc_dict is not None and isinstance ( move . piece , King ) :
self . king_loc_dict [ move . color ] = move . end_loc
# Invalidates en - passant
for square in self :
pawn = square
if isinstance ( pawn , Pawn ) :
pawn ... |
def get_link_page_text ( link_page ) :
"""Construct the dialog box to display a list of links to the user .""" | text = ''
for i , link in enumerate ( link_page ) :
capped_link_text = ( link [ 'text' ] if len ( link [ 'text' ] ) <= 20 else link [ 'text' ] [ : 19 ] + '…' )
text += '[{}] [{}]({})\n' . format ( i , capped_link_text , link [ 'href' ] )
return text |
def drop ( self , force = False ) :
"""Drop the database
Parameters
drop : boolean , default False
Drop any objects if they exist , and do not fail if the databaes does
not exist""" | self . client . drop_database ( self . name , force = force ) |
def _read_para_rvs_hmac ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP RVS _ HMAC parameter .
Structure of HIP RVS _ HMAC parameter [ RFC 8004 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| HMAC |
| | Padding |
Octets Bits Name Description
0 0 ... | _hmac = self . _read_fileng ( clen )
rvs_hmac = dict ( type = desc , critical = cbit , length = clen , hmac = _hmac , )
_plen = length - clen
if _plen :
self . _read_fileng ( _plen )
return rvs_hmac |
def _iter_names ( self ) :
"""Generate a key / value pair for each name in this table . The key is a
( platform _ id , name _ id ) 2 - tuple and the value is the unicode text
corresponding to that key .""" | table_format , count , strings_offset = self . _table_header
table_bytes = self . _table_bytes
for idx in range ( count ) :
platform_id , name_id , name = self . _read_name ( table_bytes , idx , strings_offset )
if name is None :
continue
yield ( ( platform_id , name_id ) , name ) |
def _optimise_barcodes ( self , data , min_bar_height = 20 , min_bar_count = 100 , max_gap_size = 30 , min_percent_white = 0.2 , max_percent_white = 0.8 , ** kwargs ) :
"""min _ bar _ height = Minimum height of black bars in px . Set this too
low and it might pick up text and data matrices ,
too high and it mig... | re_bars = re . compile ( r'1{%s,}' % min_bar_height )
bars = { }
for i , line in enumerate ( data ) :
for match in re_bars . finditer ( line ) :
try :
bars [ match . span ( ) ] . append ( i )
except KeyError :
bars [ match . span ( ) ] = [ i ]
grouped_bars = [ ]
for span , se... |
def get_brain ( brain_or_object ) :
"""Return a ZCatalog brain for the object
: param brain _ or _ object : A single catalog brain or content object
: type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain
: returns : True if the object is a catalog brain
: rtype : bool""" | if is_brain ( brain_or_object ) :
return brain_or_object
if is_root ( brain_or_object ) :
return brain_or_object
# fetch the brain by UID
uid = get_uid ( brain_or_object )
uc = get_tool ( "uid_catalog" )
results = uc ( { "UID" : uid } ) or search ( query = { 'UID' : uid } )
if len ( results ) == 0 :
return ... |
def term_with_coeff ( term , coeff ) :
"""Change the coefficient of a PauliTerm .
: param PauliTerm term : A PauliTerm object
: param Number coeff : The coefficient to set on the PauliTerm
: returns : A new PauliTerm that duplicates term but sets coeff
: rtype : PauliTerm""" | if not isinstance ( coeff , Number ) :
raise ValueError ( "coeff must be a Number" )
new_pauli = term . copy ( )
# We cast to a complex number to ensure that internally the coefficients remain compatible .
new_pauli . coefficient = complex ( coeff )
return new_pauli |
def print_table ( * args , ** kwargs ) :
"""if csv :
import csv
t = csv . writer ( sys . stdout , delimiter = " ; " )
t . writerow ( header )
else :
t = PrettyTable ( header )
t . align = " r "
t . align [ " details " ] = " l " """ | t = format_table ( * args , ** kwargs )
click . echo ( t ) |
def longest_existing_path ( _path ) :
r"""Returns the longest root of _ path that exists
Args :
_ path ( str ) : path string
Returns :
str : _ path - path string
CommandLine :
python - m utool . util _ path - - exec - longest _ existing _ path
Example :
> > > # ENABLE _ DOCTEST
> > > from utool . ... | existing_path = _path
while True :
_path_new = os . path . dirname ( existing_path )
if exists ( _path_new ) :
existing_path = _path_new
break
if _path_new == existing_path :
print ( '!!! [utool] This is a very illformated path indeed.' )
existing_path = ''
break
... |
def _load_sym ( sym , logger = logging ) :
"""Given a str as a path the symbol . json file or a symbol , returns a Symbol object .""" | if isinstance ( sym , str ) : # sym is a symbol file path
cur_path = os . path . dirname ( os . path . realpath ( __file__ ) )
symbol_file_path = os . path . join ( cur_path , sym )
logger . info ( 'Loading symbol from file %s' % symbol_file_path )
return sym_load ( symbol_file_path )
elif isinstance ( ... |
def zstack_proxy_iterator ( self , s = 0 , c = 0 , t = 0 ) :
"""Return iterator of : class : ` jicimagelib . image . ProxyImage ` instances in the zstack .
: param s : series
: param c : channel
: param t : timepoint
: returns : zstack : class : ` jicimagelib . image . ProxyImage ` iterator""" | for proxy_image in self :
if proxy_image . in_zstack ( s = s , c = c , t = t ) :
yield proxy_image |
def build_table ( self , msg ) :
"""Format each row of the table .""" | rows = msg . split ( '\n' )
if rows :
header_row , * body_rows = rows
self . create_md_row ( header_row , True )
for row in body_rows :
self . create_md_row ( row ) |
def best_match ( self , target , choices ) :
"""Return the best match .""" | all = self . all_matches
try :
best = next ( all ( target , choices , group = False ) )
return best
except StopIteration :
pass |
def execute ( self ) :
"""Starts a new cluster .""" | cluster_template = self . params . cluster
if self . params . cluster_name :
cluster_name = self . params . cluster_name
else :
cluster_name = self . params . cluster
creator = make_creator ( self . params . config , storage_path = self . params . storage )
if cluster_template not in creator . cluster_conf :
... |
def make_box_pixel_mask_from_col_row ( column , row , default = 0 , value = 1 ) :
'''Generate box shaped mask from column and row lists . Takes the minimum and maximum value from each list .
Parameters
column : iterable , int
List of colums values .
row : iterable , int
List of row values .
default : in... | # FE columns and rows start from 1
col_array = np . array ( column ) - 1
row_array = np . array ( row ) - 1
if np . any ( col_array >= 80 ) or np . any ( col_array < 0 ) or np . any ( row_array >= 336 ) or np . any ( row_array < 0 ) :
raise ValueError ( 'Column and/or row out of range' )
shape = ( 80 , 336 )
mask =... |
def findAll ( self , pattern ) :
"""Searches for an image pattern in the given region
Returns ` ` Match ` ` object if ` ` pattern ` ` exists , empty array otherwise ( does not
throw exception ) . Sikuli supports OCR search with a text parameter . This does not ( yet ) .""" | find_time = time . time ( )
r = self . clipRegionToScreen ( )
if r is None :
raise ValueError ( "Region outside all visible screens" )
return None
seconds = self . autoWaitTimeout
if not isinstance ( pattern , Pattern ) :
if not isinstance ( pattern , basestring ) :
raise TypeError ( "find expected ... |
def _apply_krauss_single_qubit ( krauss : Union [ Tuple [ Any ] , Sequence [ Any ] ] , args : 'ApplyChannelArgs' ) -> np . ndarray :
"""Use slicing to apply single qubit channel .""" | zero_left = linalg . slice_for_qubits_equal_to ( args . left_axes , 0 )
one_left = linalg . slice_for_qubits_equal_to ( args . left_axes , 1 )
zero_right = linalg . slice_for_qubits_equal_to ( args . right_axes , 0 )
one_right = linalg . slice_for_qubits_equal_to ( args . right_axes , 1 )
for krauss_op in krauss :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.