content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def relative_url_prefixer(filePath: str, newText: str) -> None:
"""Prepends some text to a relative URL."""
replace(
filePath,
r'(?<!(\/|<|\w|:))((\/)(\w{0,}))(?<!(\/))',
f'{newText}\\2',
False
) | 5,335,500 |
def gen_geo(num_nodes, theta, lambd, source, target, cutoff, seed=None):
"""Generates a random graph with threshold theta consisting of 'num_nodes'
and paths with maximum length 'cutoff' between 'source' adn target.
Parameters
----------
num_nodes : int
Number of nodes.
thet... | 5,335,501 |
def FilterExceptions(image_name, errors):
"""Filter out the Application Verifier errors that have exceptions."""
exceptions = _EXCEPTIONS.get(image_name, [])
def _HasNoException(error):
# Iterate over all the exceptions.
for (severity, layer, stopcode, regexp) in exceptions:
# And see if they match... | 5,335,502 |
def dim(text: str, reset_style: Optional[bool] = True) -> str:
"""Return text in dim"""
return set_mode("dim", False) + text + (reset() if reset_style else "") | 5,335,503 |
def write_methods(path, thing, method):
"""
write_methods function has all of necesary commands to write objects in
number of formats.
"""
global SUPPORTED_SAVE_METHODS
if method.lower() in SUPPORTED_SAVE_METHODS:
if method.lower() == 'pickle':
if not path.endswith(".spec"):... | 5,335,504 |
def test_validate_user():
"""Test the validate instrument user function.
"""
u = InstrUser()
res, msg = validate_user(u)
assert not res and 'id' in msg
u.id = 'test'
res, msg = validate_user(u)
assert not res and 'policy' in msg
u.policy = 'unreleasable'
res, msg = validate_u... | 5,335,505 |
def want_color_output():
"""Return ``True`` if colored output is possible/requested and not running in GUI.
Colored output can be explicitly requested by setting :envvar:`COCOTB_ANSI_OUTPUT` to ``1``.
"""
want_color = sys.stdout.isatty() # default to color for TTYs
if os.getenv("NO_COLOR") is not... | 5,335,506 |
def jaccard(list1, list2):
"""calculates Jaccard distance from two networks\n
| Arguments:
| :-
| list1 (list or networkx graph): list containing objects to compare
| list2 (list or networkx graph): list containing objects to compare\n
| Returns:
| :-
| Returns Jaccard distance between list1 and list2
... | 5,335,507 |
def default_argument_preprocessor(args):
"""Return unmodified args and an empty dict for extras"""
extras = {}
return args, extras | 5,335,508 |
def expand_site_packages(site_packages: List[str]) -> Tuple[List[str], List[str]]:
"""Expands .pth imports in site-packages directories"""
egg_dirs: List[str] = []
for dir in site_packages:
if not os.path.isdir(dir):
continue
pth_filenames = sorted(name for name in os.listdir(dir... | 5,335,509 |
def early_anomaly(case: pd.DataFrame) -> pd.DataFrame:
"""
A sequence of 2 or fewer events executed too early, which is then skipped later in the case
Parameters
-----------------------
case: pd.DataFrame,
Case to apply anomaly
Returns
-----------------------
Case with the appli... | 5,335,510 |
def get_package_version():
"""
:returns: package version without importing it.
"""
base = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(base, "gotalk/__init__.py")) as initf:
for line in initf:
m = version.match(line.strip())
if not m:
... | 5,335,511 |
def parse_cmd(script, *args):
"""Returns a one line version of a bat script
"""
if args:
raise Exception('Args for cmd not implemented')
# http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true
oneline_cmd = '&&'.join(script.split('\n'))
oneline_... | 5,335,512 |
def test_first_subfield():
"""Test sub-field acessor ^* in field with several subfields"""
record = MasterRecord()
record.update(test_data)
first_subfield = format("v26^*", record)
assert first_subfield=='Paris', 'Failed to extract first subfield' | 5,335,513 |
def expected_inheritance(variant_obj):
"""Gather information from common gene information."""
manual_models = set()
for gene in variant_obj.get('genes', []):
manual_models.update(gene.get('manual_inheritance', []))
return list(manual_models) | 5,335,514 |
def player_stats_game(data) -> defaultdict:
"""Individual Game stat parser. Directs parsing to the proper
player parser (goalie or skater).
Receives the player_id branch.
Url.GAME
Args:
data (dict): dict representing JSON object.
Returns:
defaultdict: Parsed Data.
"""
... | 5,335,515 |
def about(request):
"""
View function for about page
"""
return render(
request,
'about.html',
) | 5,335,516 |
def getTimeDeltaFromDbStr(timeStr: str) -> dt.timedelta:
"""Convert db time string in reporting software to time delta object
Args:
timeStr (str): The string that represents time, like 14:25 or 15:23:45
Returns:
dt.timedelta: time delta that has hours and minutes components
"""
if pd... | 5,335,517 |
def colorBool(v) -> str:
"""Convert True to 'True' in green and False to 'False' in red
"""
if v:
return colored(str(v),"green")
else:
return colored(str(v),"red") | 5,335,518 |
def debug_fix():
"""
I have trouble with hitting breakpoints in lask-RESTful class methods.
This method help me.
"""
app.config['DEBUG'] = False
app.config['PROPAGATE_EXCEPTIONS'] = True
app.run(debug=False) | 5,335,519 |
def bootstrap(
tokens: List[str],
measure: str = "type_token_ratio",
window_size: int = 3,
ci: bool = False,
raw=False,
):
"""calculate bootstrap for lex diversity measures
as explained in Evert et al. 2017. if measure='type_token_ratio'
it calculates standardized type-token ratio
:p... | 5,335,520 |
def by_label(move_data, value, label_name, filter_out=False, inplace=False):
"""
Filters trajectories points according to specified value and collum label.
Parameters
----------
move_data : dataframe
The input trajectory data
value : The type_ of the feature values to be use to filter t... | 5,335,521 |
def make_pyrimidine(residue, height = 0.4, scale = 1.2):
"""Creates vertices and normals for pyrimidines:Thymine Uracil Cytosine"""
atoms = residue.atoms
names = [name.split("@")[0] for name in atoms.name]
idx=names.index('N1'); N1 = numpy.array(atoms[idx].coords)
idx=names.index('C2'); C2 = ... | 5,335,522 |
def get_props(filepath, m_co2=22, m_poly=2700/123, N_A=6.022E23,
sigma_co2=2.79E-8, sort=False):
"""
Computes important physical properties from the dft.input file, such as
density of CO2 in the CO2-rich phase, solubility of CO2 in the polyol-rich
phase, and specific volume of the polyol-... | 5,335,523 |
def get_genotype(chrom, rsid):
"""
"""
geno_path = ('/home/hsuj/lustre/geno/'
'CCF_1000G_Aug2013_Chr{0}.dose.double.ATB.RNASeq_MEQTL.txt')
geno_gen = pd.read_csv(geno_path.format(str(chrom)),
sep=" ", chunksize = 10000)
for i in geno_gen:
if rsid in i.index:
... | 5,335,524 |
def task_dosomething(storage):
"""
Task that gets launched to handle something in the background until it is completed and then terminates. Note that
this task doesn't return until it is finished, so it won't be listening for Threadify pause or kill requests.
"""
# An important task that we want to ... | 5,335,525 |
def highway(input_, size, num_layers=1, bias=-2.0, f=tf.nn.relu, scope='Highway'):
"""Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wy + b)
z = t * g(Wy + b) + (1 - t) * y
where g is nonlinearity, t is transform gate, and (1 - t) is carry gate.
"""
with tf.variable_scope(s... | 5,335,526 |
def convert_to_entry(func):
"""Wrapper function for converting dicts of entries to HarEnrty Objects"""
@functools.wraps(func)
def inner(*args, **kwargs):
# Changed to list because tuple does not support item assignment
changed_args = list(args)
# Convert the dict (first argument) to... | 5,335,527 |
def transform(record: dict, key_ref: dict, country_ref: pd.DataFrame, who_coding: pd.DataFrame, no_update_phrase: pd.DataFrame):
"""
Apply transformations to OXCGRT records.
Parameters
----------
record : dict
Input record.
key_ref : dict
Reference for key mapping.
country_r... | 5,335,528 |
def validate_client_parameters(cmd, namespace):
"""Retrieves Batch connection parameters from environment variables"""
from azure.mgmt.batch import BatchManagementClient
from azure.cli.core.commands.client_factory import get_mgmt_service_client
# simply try to retrieve the remaining variables from envi... | 5,335,529 |
def hc_genes(
input_gene_expression: "gene expression data filename (.gct file) where rows are genes and columns are samples",
clustering_type: "single or consensus -- Only single is suported at the moment",
distance_metric: "the function to be used when comparing the distance/similarity of the ... | 5,335,530 |
def detect_text(path):
"""Detects text in the file."""
from google.cloud import vision
import io
client = vision.ImageAnnotatorClient()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.text_detection(image=... | 5,335,531 |
def file_util_is_ext(path, ext):
"""判断是否指定后缀文件,ext不包含点"""
if file_util_get_ext(path) == ext:
return True
else:
return False | 5,335,532 |
def load_tract(repo, tract, patches=None, **kwargs):
"""Merge catalogs from forced-photometry coadds across available filters.
Parameters
--
tract: int
Tract of sky region to load
repo: str
File location of Butler repository+rerun to load.
patches: list of str
List of pa... | 5,335,533 |
def calculate_delta(arg1, arg2):
"""
Calculates and returns a `datetime.timedelta` object representing
the difference between arg1 and arg2. Arguments must be either both
`datetime.date`, both `datetime.time`, or both `datetime.datetime`.
The difference is absolute, so the order of the arguments doesn't matter.
"... | 5,335,534 |
def main():
"""
Execute action from playbook
"""
command = NetAppONTAPWFC()
command.apply() | 5,335,535 |
def create_model_config(model_dir: str, config_path: str = None):
"""Creates a new configuration file in the model directory and returns the config."""
# read the config file
config_content = file_io.read_file_to_string(root_dir(config_path))
# save the config file to the model directory
write_mod... | 5,335,536 |
def get_deployment_physnet_mtu():
"""Retrieves global physical network MTU setting.
Plugins should use this function to retrieve the MTU set by the operator
that is equal to or less than the MTU of their nodes' physical interfaces.
Note that it is the responsibility of the plugin to deduct the value of... | 5,335,537 |
def _path(path):
"""Helper to build an OWFS path from a list"""
path = "/" + "/".join(str(x) for x in path)
return path.encode("utf-8") + b"\0" | 5,335,538 |
def current_milli_time():
"""Return the current time in milliseconds"""
return int(time.time() * 1000) | 5,335,539 |
def function_exists(function_name, *args, **kwargs):
"""
Checks if a function exists in the catalog
"""
# TODO (dmeister): This creates an SQL injection, but it should not
# be a problem for this purpose.
function_exists_text_count = PSQL.run_sql_command(
"SELECT 'function exists' FROM pg_proc WHERE proname='%... | 5,335,540 |
def _loo_jackknife(
func: Callable[..., NDArray],
nobs: int,
args: Sequence[ArrayLike],
kwargs: Dict[str, ArrayLike],
extra_kwargs: Optional[Dict[str, ArrayLike]] = None,
) -> NDArray:
"""
Leave one out jackknife estimation
Parameters
----------
func : callable
Function ... | 5,335,541 |
def VentanaFourierPrincipal (ventana):
"""
Ventana en la que el usuario elige cómo aplicar calor a la placa.
Parámetros de la función:
------------------------
ventana: Variable que cierra una ventana ya abierta.
Salida de la función:
---------------------
Interfaz gráfica con la qu... | 5,335,542 |
def _fastq_illumina_convert_fastq_solexa(in_handle, out_handle, alphabet=None):
"""Fast Illumina 1.3+ FASTQ to Solexa FASTQ conversion (PRIVATE).
Avoids creating SeqRecord and Seq objects in order to speed up this
conversion.
"""
# Map unexpected chars to null
from Bio.SeqIO.QualityIO import so... | 5,335,543 |
def pull_branch(c: InvokeContext, repo: Repo, directory: str, branch_name: str) -> CommandResult:
"""
Change to the repo directory and pull master.
:argument c: InvokeContext
:argument repo: Repo the repo to pull
:argument directory: str the directory to change to
:argument branch_name: ... | 5,335,544 |
def trace_app(app, tracer, service="aiohttp-web"):
"""
Tracing function that patches the ``aiohttp`` application so that it will be
traced using the given ``tracer``.
:param app: aiohttp application to trace
:param tracer: tracer instance to use
:param service: service name of tracer
"""
... | 5,335,545 |
def amin(*args, **kwargs):
"""Async equivalent of min()."""
key_fn = kwargs.pop('key', None)
if kwargs:
raise TypeError('amin() got an unexpected keyword argument')
if len(args) == 0:
raise TypeError('amin() expected 1 arguments, got 0')
elif len(args) == 1:
iterable = args[... | 5,335,546 |
def scheduler(request):
""" This is the host fixture for testinfra. To read more, please see
the testinfra documentation:
https://testinfra.readthedocs.io/en/latest/examples.html#test-docker-images
"""
namespace = os.environ.get('NAMESPACE')
pod = os.environ.get('SCHEDULER_POD')
yield testin... | 5,335,547 |
def sizeof_fmt(num, suffix='B'):
"""Return human readable version of in-memory size.
Code from Fred Cirera from Stack Overflow:
https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
... | 5,335,548 |
def readFPs(filepath):
"""Reads a list of fingerprints from a file"""
try:
myfile = open(filepath, "r")
except:
raise IOError("file does not exist:", filepath)
else:
fps = []
for line in myfile:
if line[0] != "#": # ignore comments
line = line... | 5,335,549 |
def print_selected_expression_type(IniStep, FinStep, simulation_dir, output_dir, gene_indexes, celltype):
""" SImilar than the above equation but prints the count in an file
"""
Noutput = len( gene_indexes )
filename = output_dir + 'BNstates_type'+ str(celltype) +'.txt'
Scores1 = output_id_cel... | 5,335,550 |
def validate_take_with_convert(convert, args, kwargs):
"""
If this function is called via the 'numpy' library, the third parameter in
its signature is 'axis', which takes either an ndarray or 'None', so check
if the 'convert' parameter is either an instance of ndarray or is None
"""
if isi... | 5,335,551 |
def load_operators_expr() -> List[str]:
"""Returns clip loads operators for std.Expr as a list of string."""
abcd = list(ascii_lowercase)
return abcd[-3:] + abcd[:-3] | 5,335,552 |
def findScanNumberString(s):
"""If s contains 'NNNN', where N stands for any digit, return the string
beginning with 'NNNN' and extending to the end of s. If 'NNNN' is not
found, return ''."""
n = 0
for i in range(len(s)):
if s[i].isdigit():
n += 1
else:
n = 0
if n == 4:
return s[i-3:]
return '' | 5,335,553 |
def parseWsUrl(url):
"""
Parses as WebSocket URL into it's components and returns a tuple (isSecure, host, port, resource, path, params).
isSecure is a flag which is True for wss URLs.
host is the hostname or IP from the URL.
port is the port from the URL or standard port derived from scheme (ws =... | 5,335,554 |
def describe_events(SourceIdentifier=None, SourceType=None, StartTime=None, EndTime=None, Duration=None, MaxRecords=None, Marker=None):
"""
Returns events related to clusters, cache security groups, and cache parameter groups. You can obtain events specific to a particular cluster, cache security group, or cach... | 5,335,555 |
def parse_settings(settings: str):
"""Settings generator from get-config.
Get-config returns something that looks like this:
Label: ISO Speed
Type: RADIO
Current: 100
Choice: 0 100
Choice: 1 125
Choice: 2 160
Choice: 3 200
Args:
settings: Re... | 5,335,556 |
def load_image(filename):
"""Loads an image, reads it and returns image size,
dimension and a numpy array of this image.
filename: the name of the image
"""
try:
img = cv2.imread(filename)
print("(H, W, D) = (height, width, depth)")
print("shape: ",img.shape)
... | 5,335,557 |
def add_manipulable(key, manipulable):
"""
add a ArchipackActiveManip into the stack
if not already present
setup reference to manipulable
return manipulators stack
"""
global manips
if key not in manips.keys():
# print("add_manipulable() key:%s not found create n... | 5,335,558 |
def importAllPlugins():
"""
Bring all plugins that KiKit offers into a the global namespace. This
function is impure as it modifies the global variable scope. The purpose
of this function is to allow the PCM proxy to operate.
"""
import importlib
for plugin in availablePlugins:
modu... | 5,335,559 |
def get_wave_data_type(sample_type_id):
"""Creates an SDS type definition for WaveData"""
if sample_type_id is None or not isinstance(sample_type_id, str):
raise TypeError('sample_type_id is not an instantiated string')
int_type = SdsType('intType', SdsTypeCode.Int32)
double_type = SdsType('do... | 5,335,560 |
def _spec_augmentation(x,
warp_for_time=False,
num_t_mask=2,
num_f_mask=2,
max_t=50,
max_f=10,
max_w=80):
""" Deep copy x and do spec augmentation then return it
Args:
... | 5,335,561 |
def deg2rad(x, dtype=None):
"""
Converts angles from degrees to radians.
Args:
x (Tensor): Angles in degrees.
dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
output Tensor.
Returns:
Tensor, the corresponding angle in radians.... | 5,335,562 |
def point_in_ellipse(origin, point, a, b, pa_rad, verbose=False):
"""
Identify if the point is inside the ellipse.
:param origin A SkyCoord defining the centre of the ellipse.
:param point A SkyCoord defining the point to be checked.
:param a The semi-major axis in arcsec of the ellipse
:param ... | 5,335,563 |
def isNumberString(value):
"""
Checks if value is a string that has only digits - possibly with leading '+' or '-'
"""
if not value:
return False
sign = value[0]
if (sign == '+') or (sign == '-'):
if len(value) <= 1:
return False
absValue = value[1:]
... | 5,335,564 |
def initialise_tweet_database():
"""
Initialise Twitter table for storing inbound and outbound Tweet information.
"""
twitter_sql = """
CREATE TABLE Twitter (
procrystal_id integer PRIMARY KEY,
tweet_id text not null,
username text not null,
reply_sent bool not null,... | 5,335,565 |
def vaseline(tensor, shape, alpha=1.0, time=0.0, speed=1.0):
"""
"""
return value.blend(tensor, center_mask(tensor, bloom(tensor, shape, 1.0), shape), alpha) | 5,335,566 |
def _func_length(target_attr: Union[Dict[str, Any], List[Any]], *_: Any) -> int:
"""Function for returning the length of a dictionary or list."""
return len(target_attr) | 5,335,567 |
def assert_option_strategy(strategy, init_opts, exp_opts, **kwargs):
"""Test for any strategy for options handler
strategy : strategy to use
init_opts : dict with keys :code:`{'c1', 'c2', 'w'}` or :code:`{'c1',
'c2', 'w', 'k', 'p'}`
exp_opts: dict with expected values after strategy with giv... | 5,335,568 |
def import_places_from_swissnames3d(
projection: str = "LV95", file: Optional[TextIOWrapper] = None
) -> str:
"""
import places from SwissNAMES3D
:param projection: "LV03" or "LV95"
see http://mapref.org/CoordinateReferenceFrameChangeLV03.LV95.html#Zweig1098
:param file: path to local unzipped ... | 5,335,569 |
def create_file_handler(log_file, handler_level, formatter=logging.Formatter(LOG_FORMAT_STRING)):
"""
Creates file handler which logs even debug messages.
"""
if handler_level == 'debug':
level = logging.DEBUG
elif handler_level == 'info':
level = logging.INFO
elif handler_level == 'warning':
level = log... | 5,335,570 |
def clear():
"""清空模型"""
itasca.command('model new') | 5,335,571 |
def utility_for_osf_spam_or_ham(folder_name):
"""
commandline utility for determining whether osf info is spam or ham and then moving to correct file.
"""
files_folders = os.listdir(folder_name)
for f in files_folders:
try:
if f[0:3] == "dir":
pass
els... | 5,335,572 |
def _generate_data(size):
""" For testing reasons only """
# return FeatureSpec('dummy', name=None, data='x' * size)
return PlotSpec(data='x' * size, mapping=None, scales=[], layers=[]) | 5,335,573 |
def configuration_filename(feature_dir, proposed_splits, split, generalized):
"""Calculates configuration specific filenames.
Args:
feature_dir (`str`): directory of features wrt
to dataset directory.
proposed_splits (`bool`): whether using proposed splits.
split (`str`): tr... | 5,335,574 |
def gammaBGRbuf(
buf: array,
gamma: float) -> array:
"""Apply a gamma adjustment to a
BGR buffer
Args:
buf: unsigned byte array
holding BGR data
gamma: float gamma adjust
Returns:
unsigned byte array
holding gamma adjusted... | 5,335,575 |
def sentence_avg_word_length(df, new_col_name, col_with_lyrics):
"""
Count the average word length in a dataframe lyrics column, given a column name, process it, and save as new_col_name
Parameters
----------
df : dataframe
new_col_name : name of new column
col_with_lyric: co... | 5,335,576 |
def to_sigmas(t,p,w_1,w_2,w_3):
"""Given t = sin(theta), p = sin(phi), and the stds this computes the covariance matrix and its inverse"""
p2 = p*p
t2 = t*t
tc2 = 1-t2
pc2 = 1-p2
tc= np.sqrt(tc2)
pc= np.sqrt(pc2)
s1,s2,s3 = 1./(w_1*w_1),1./(w_2*w_2),1./(w_3*w_3)
a = pc2*tc2*s1 + t2*s... | 5,335,577 |
def fetch_atlas_pauli_2017(version='prob', data_dir=None, verbose=1):
"""Download the Pauli et al. (2017) atlas with in total
12 subcortical nodes.
Parameters
----------
version: str, optional (default='prob')
Which version of the atlas should be download. This can be 'prob'
for th... | 5,335,578 |
def GeometricError(ref_point_1, ref_point_2):
"""Deprecation notice function. Please use indicated correct function"""
print(GeometricError.__name__ + ' is deprecated, use ' + geometricError.__name__ + ' instead')
traceback.print_stack(limit=2)
return geometricError(ref_point_1, ref_point_2) | 5,335,579 |
def svn_fs_open2(*args):
"""svn_fs_open2(char const * path, apr_hash_t fs_config, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t"""
return _fs.svn_fs_open2(*args) | 5,335,580 |
def config(workspace):
"""Return a config object."""
return Config(workspace.root_uri, {}) | 5,335,581 |
def longest_sequence_index(sequences: List[List[XmonQubit]]) -> Optional[int]:
"""Gives the position of a longest sequence.
Args:
sequences: List of node sequences.
Returns:
Index of the longest sequence from the sequences list. If more than one
longest sequence exist, the first on... | 5,335,582 |
def subset_raster(rast, band=1, bbox=None, logger=None):
"""
:param rast: The rasterio raster object
:param band: The band number you want to contour. Default: 1
:param bbox: The bounding box in which to generate contours.
:param logger: The logger object to use for this tool
:return: A dict wit... | 5,335,583 |
def extract_date_features(df):
"""Expand datetime values into individual features."""
for col in df.select_dtypes(include=['datetime64[ns]']):
print(f"Now extracting features from column: '{col}'.")
df[col + '_month'] = pd.DatetimeIndex(df[col]).month
df[col + '_day'] = pd.DatetimeIndex(... | 5,335,584 |
def record_setitem(data, attr, value):
"""Implement `record_setitem`."""
data2 = copy(data)
py_setattr(data2, attr, value)
return data2 | 5,335,585 |
async def test_import_from_yaml(hass, canary) -> None:
"""Test import from YAML."""
with patch(
"homeassistant.components.canary.async_setup_entry",
return_value=True,
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: YAML_CONFIG})
await hass.async_block_till_done(... | 5,335,586 |
def get_git_branch() -> Optional[str]:
"""Get the git branch."""
return _run("git", "branch", "--show-current") | 5,335,587 |
def open_image(path, verbose=True, squeeze=False):
"""
Open a NIfTI-1 image at the given path. The image might have an arbitrary number of dimensions; however, its first
three axes are assumed to hold its spatial dimensions.
Parameters
----------
path : str
The path of the file to be lo... | 5,335,588 |
def add_one_for_ordered_traversal(graph,
node_idx,
current_path=None):
"""
This recursive function returns an ordered traversal of a molecular graph.
This traversal obeys the following rules:
1. Locations may... | 5,335,589 |
def get_kubeseal_version() -> str:
"""Retrieve the kubeseal binary version."""
LOGGER.debug("Retrieving kubeseal binary version.")
binary = current_app.config.get("KUBESEAL_BINARY")
kubeseal_subprocess = subprocess.Popen(
[binary, "--version"],
stdout=subprocess.PIPE,
stderr=subp... | 5,335,590 |
def test_add_interpolated_tensor(example_grid):
""" test the `add_interpolated` method """
f = Tensor2Field(example_grid)
a = np.random.random(f.data_shape)
c = tuple(example_grid.point_to_cell(example_grid.get_random_point()))
c_data = (Ellipsis,) + c
p = example_grid.cell_to_point(c, cartesia... | 5,335,591 |
def get_subject_guide_for_section_params(
year, quarter, curriculum_abbr, course_number, section_id=None):
"""
Returns a SubjectGuide model for the passed section params:
year: year for the section term (4-digits)
quarter: quarter (AUT, WIN, SPR, or SUM)
curriculum_abbr: curriculum abbrevia... | 5,335,592 |
def test_gas_limit_config(BrownieTester, accounts, config):
"""gas limit is set correctly from the config"""
config["active_network"]["gas_limit"] = 5000000
tx = accounts[0].deploy(BrownieTester, True).tx
assert tx.gas_limit == 5000000
config["active_network"]["gas_limit"] = False | 5,335,593 |
def handle_hubbubdelmarkup(bot, ievent):
""" arguments: <feedname> <item> - delete markup item from a feed's markuplist. """
try: (name, item) = ievent.args
except ValueError: ievent.missing('<feedname> <item>') ; return
target = ievent.channel
feed = watcher.byname(name)
if not feed: ievent.rep... | 5,335,594 |
def dense_reach_bonus(task_rew, b_pos, arm_pos, max_reach_bonus=1.5, reach_thresh=.02,
reach_multiplier=all_rew_reach_multiplier):
""" Convenience function for adding a conditional dense reach bonus to an aux task.
If the task_rew is > 1, this indicates that the actual task is complete, a... | 5,335,595 |
def handler_fan_out(event, context):
"""
Publishes an SNS message for each region from which the assets are to be
collected.
"""
elasticsearch_regions = AWS_REGIONS_SET - {'ap-northeast-3'}
for region in elasticsearch_regions:
sns.publish(
TopicArn=os.environ['SNSTopicCollect... | 5,335,596 |
def getAllNumbers(text):
"""
This function is a copy of systemtools.basics.getAllNumbers
"""
if text is None:
return None
allNumbers = []
if len(text) > 0:
# Remove space between digits :
spaceNumberExists = True
while spaceNumberExists:
text = re.... | 5,335,597 |
def optimal_string_alignment_distance(s1, s2):
"""
This is a variation of the Damerau-Levenshtein distance that returns the strings' edit distance
taking into account deletion, insertion, substitution, and transposition, under the condition
that no substring is edited more than once.
... | 5,335,598 |
def handle_stop(event):
"""
Handler for mycroft.stop, i.e. button press
"""
loop.force_unmute() | 5,335,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.