content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def download(i):
"""
Input: {
(repo_uoa)
(module_uoa)
(data_uoa)
(new_repo_uoa) - new repo UOA; "local" by default
(skip_module_check) - if 'yes', do not check if module for a given component exists
}
Output: {
... | 21,400 |
def recursiveUpdate(target, source):
"""
Recursively update the target dictionary with the source dictionary, leaving unfound keys in place.
This is different than dict.update, which removes target keys not in the source
:param dict target: The dictionary to be updated
:param dict source: The dicti... | 21,401 |
def macro_bank_usa_interest_rate():
"""
美联储利率决议报告, 数据区间从19820927-至今
https://datacenter.jin10.com/reportType/dc_usa_interest_rate_decision
https://cdn.jin10.com/dc/reports/dc_usa_interest_rate_decision_all.js?v=1578581921
:return: 美联储利率决议报告-今值(%)
:rtype: pandas.Series
"""
t = time.time()
... | 21,402 |
def print_usage():
""" Prints usage instructions to user """
print("python3 main.py -f [path/to/file] -s [simulator] -a [simulate/verify]")
print(" -f Path to input file. REQUIRED.")
print(" -a Simulate or Verify. Optional.")
print(' [default] "simulate" or "s" ')
print(' ... | 21,403 |
def get_kwd_group(soup):
"""
Find the kwd-group sections for further analysis to find
subject_area, research_organism, and keywords
"""
kwd_group = None
kwd_group = extract_nodes(soup, 'kwd-group')
return kwd_group | 21,404 |
def drqa_train():
"""
Train the drqa model, requires preprocessed data
"""
pass | 21,405 |
def read_transport_file(input_file_name):
"""
Reads File "input_file_name".dat, and returns lists containing the atom
indices of the device atoms, as well as the atom indices of
the contact atoms. Also, a dictionary "interaction_distances" is generated,
which spcifies the maximum interaction distanc... | 21,406 |
def init_zooplankton_defaults():
"""Initialize default parameters for zooplankton"""
global _zooplankton_defaults | 21,407 |
def testNoResources():
"""Test making a match without resources."""
claim = ResourceClaim.create((
ResourceSpec.create('ref0', 'typeA', ()),
))
check(claim, (), None) | 21,408 |
def a_metric_of_that_run_exists(data_access, metric_id, run_id):
"""A metric of that run exists."""
data_access.get_run_dao().get(run_id)["info"] = {
"metrics": [metric_id]}
data_access.get_metrics_dao().should_receive("get") \
.with_args(run_id, metric_id) \
.and_return({"metric_id"... | 21,409 |
def handle_srv6_path(operation, grpc_address, grpc_port, destination,
segments=None, device='', encapmode="encap", table=-1,
metric=-1, bsid_addr='', fwd_engine='linux', key=None,
update_db=True, db_conn=None, channel=None):
"""
Handle a SRv6 Path.
... | 21,410 |
def mask_outside_polygon(poly_verts, ax, facecolor=None, edgecolor=None, alpha=0.25):
"""
Plots a mask on the specified axis ("ax", defaults to plt.gca()) such that
all areas outside of the polygon specified by "poly_verts" are masked.
"poly_verts" must be a list of tuples of the verticies in the polyg... | 21,411 |
def setup_data(cluster):
"""
Get decision boundaries by means of np.meshgrid
:return: Tuple (vectors, centroids, X component of mesghgrid, Y component of meshgrid, )
"""
feature_vectors, _, centroids, _, kmeans = cluster
# Step size of the mesh. Decrease to increase the quality of the VQ.
h... | 21,412 |
def generate_equations(model, cleanup=True, verbose=False):
"""
Generate math expressions for reaction rates and species in a model.
This fills in the following pieces of the model:
* odes
* species
* reactions
* reactions_bidirectional
* observables (just `coefficients` and `species` ... | 21,413 |
def Routing_Table(projdir, rootgrp, grid_obj, fdir, strm, Elev, Strahler, gages=False, Lakes=None):
"""If "Create reach-based routing files?" is selected, this function will create
the Route_Link.nc table and Streams.shp shapefiles in the output directory."""
# Stackless topological sort algorithm, adapted... | 21,414 |
def list_errors(
conx: Connection,
) -> t.List[t.Tuple[int, datetime.datetime, str, str, str, str]]:
"""Return list of all errors.
The list returned contains each error as an element in the list. Each
element is a tuple with the following layout:
(seq nr, date, err msg, err detail, level, stat... | 21,415 |
async def get_incident(incident_id):
"""
Get incident
---
get:
summary: Get incident
tags:
- incidents
parameters:
- name: id
in: path
required: true
description: Object ID
responses:
200:
... | 21,416 |
def partition_vector(vector, sets, fdtype: str='float64') -> List[NDArrayNfloat]: # pragma: no cover
"""partitions a vector"""
vectors = []
for unused_aname, aset in sets:
if len(aset) == 0:
vectors.append(np.array([], dtype=fdtype))
continue
vectori = vector[aset]
... | 21,417 |
def colorStrip(strip, color):
"""Wipe color across display a pixel at a time."""
for i in range(strip.numPixels()):
strip.setPixelColor(i, color)
strip.show() | 21,418 |
def gen_BatchIterator(data, batch_size=100, shuffle=True):
"""
Return the next 'batch_size' examples
from the X_in dataset
Reference
=========
[1] tensorflow.examples.tutorial.mnist.input_data.next_batch
Input
=====
data: 4d np.ndarray
The samples to be batched
batch_siz... | 21,419 |
def calculate_G4(
n_numbers,
neighborsymbols,
neighborpositions,
G_elements,
theta,
zeta,
eta,
Rs,
cutoff,
cutofffxn,
Ri,
normalized=True,
image_molecule=None,
n_indices=None,
weighted=False,
):
"""Calculate G4 symmetry function.
These are 3 body or a... | 21,420 |
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--output',
type=str,
required=False,
help='GCS URL where results will be saved as a CSV.')
parser.add_argument(
'--query',
type=str,
required=True,
... | 21,421 |
def paths_from_root(graph, start):
"""
Generates paths from `start` to every other node in `graph` and puts it in
the returned dictionary `paths`.
ie.: `paths_from_node(graph, start)[node]` is a list of the edge names used
to get to `node` form `start`.
"""
paths = {start: []}
q = [start... | 21,422 |
def list_to_dict(l:Sequence, f:Optional[Callable]=None) -> Dict:
""" Convert the list to a dictionary in which keys and values are adjacent
in the list. Optionally, a function `f` can be passed to apply to each value
before adding it to the dictionary.
Parameters
----------
l: typing.Sequence
... | 21,423 |
def inner(a, b):
"""Computes an inner product of two arrays.
Ordinary inner product of vectors for 1-D arrays (without complex conjugation).
Parameters
----------
a, b : array_like
If *a* and *b* are nonscalar, their shape must match.
Returns
-------
out : ndarray
out.... | 21,424 |
def remove_list_redundancies(lst: Sequence[T]) -> list[T]:
"""
Used instead of list(set(l)) to maintain order
Keeps the last occurrence of each element
"""
return list(reversed(dict.fromkeys(reversed(lst)))) | 21,425 |
def concatenate(arrays, axis):
"""Concatenate along axis.
Differs from numpy.concatenate in that it works if the axis doesn't exist.
"""
logger.debug('Applying asarray to each element of arrays.')
arrays = [np.asarray(array) for array in arrays]
logger.debug('Adding axes to each element of arra... | 21,426 |
def s7_blastn_xml(qry, base, threads):
""" run blastn with xml output qry and base are absolute paths """
print("Step7 ... :" + qry)
os.makedirs(os.path.join(hivdrm_work_dir, s7_prefix), exist_ok = True)
qry_file = os.path.basename(qry)
base_file = os.path.basename(base)
sample_name = os.path.sp... | 21,427 |
def bpformat(bp):
"""
Format the value like a 'human-readable' file size (i.e. 13 Kbp, 4.1 Mbp,
102 bp, etc.).
"""
try:
bp = int(bp)
except (TypeError, ValueError, UnicodeDecodeError):
return avoid_wrapping("0 bp")
def bp_number_format(value):
return formats.number_f... | 21,428 |
def get_module_id_from_event(event):
"""
Helper function to get the module_id from an EventHub message
"""
if "iothub-connection-module_id" in event.message.annotations:
return event.message.annotations["iothub-connection-module-id".encode()].decode()
else:
return None | 21,429 |
def pipe_literal_representer(dumper, data):
"""Create a representer for pipe literals, used internally for pyyaml."""
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') | 21,430 |
def verify_remote_versions(setup):
"""Examine the remote versions."""
setup_ver = setup.VER
gc_ver, _, _ = release.get_last_google_code_version(setup.NAME)
pypi_ver, _, _ = pypi_list.get_latest_version(setup.NAME)
if gc_ver and gc_ver == setup_ver:
print(' code.google.com version is up-to-date')
else:... | 21,431 |
def RecognitionNeuralNetworkModelSmall(ih, iw, ic, nl):
"""
A simple model used to test the machinery on TrainSmall2.
ih, iw, ic - describe the dimensions of the input image
mh, mw - describe the dimensions of the output mask
"""
dropout = 0.1
model = Sequential()
model.add(Conv2D(32,... | 21,432 |
def _quick_rec_str(rec):
"""try to print an identifiable description of a record"""
if rec['tickets']:
return "[tickets: %s]" % ", ".join(rec["tickets"])
else:
return "%s..." % rec["raw_text"][0:25] | 21,433 |
def A006577(start: int = 0, limit: int = 20) -> Collection[int]:
"""Number of halving and tripling steps to reach 1 in '3x+1' problem,
or -1 if 1 is never reached.
"""
def steps(n: int) -> int:
if n == 1:
return 0
x = 0
while True:
if n % 2 == 0:
... | 21,434 |
def split_to_sentences_per_pages(text):
""" splitting pdfminer outputted text into list of pages and cleanup
paragraphs"""
def split_into_sentences(line):
"""cleanup paragraphs"""
return ifilter(None, (i.strip() for i in line.split('\n\n')))
return ifilter(None, imap(split_into_sentences... | 21,435 |
def lookup(_id=None, article_id=None, user_id=None, mult=False):
"""
Lookup a reaction in our g.db
"""
query = {}
if article_id:
query["article_id"] = ObjectId(article_id)
if user_id:
query["user_id"] = ObjectId(user_id)
if _id:
query["_id"] = ObjectId(_id)
if m... | 21,436 |
def connection(user='m001-student', password='m001-mongodb-basics'):
"""connection: This function connects mongoDB to get MongoClient
Args:
user (str, optional): It's user's value for URL ATLAS srv. Defaults to 'm001-student'.
password (str, optional): It's password's value for URL ATLAS srv. D... | 21,437 |
async def get_selection(ctx, choices, delete=True, pm=False, message=None, force_select=False):
"""Returns the selected choice, or None. Choices should be a list of two-tuples of (name, choice).
If delete is True, will delete the selection message and the response.
If length of choices is 1, will return the... | 21,438 |
def data_dir():
""" Get SUNCG data path (must be symlinked to ~/.suncg)
:return: Path to suncg dataset
"""
if 'SUNCG_DATA_DIR' in os.environ:
path = os.path.abspath(os.environ['SUNCG_DATA_DIR'])
else:
path = os.path.join(os.path.abspath(os.path.expanduser('~')), ".suncg")
... | 21,439 |
def total_variation(images, name=None):
"""Calculate and return the total variation for one or more images.
(A mirror to tf.image total_variation)
The total variation is the sum of the absolute differences for neighboring
pixel-values in the input images. This measures how much noise is in the
ima... | 21,440 |
def get_vivareal_data(driver_path: str, address: str, driver_options: Options = None) -> list:
"""
Scrapes vivareal site and build a array of maps in the following format:
[
{
"preço": int,
"valor_de_condominio": int,
"banheiros": int,
"quartos": int,... | 21,441 |
def extract_image(data):
"""Tries and extracts the image inside data (which is a zipfile)"""
with ZipFile(BytesIO(data)) as zip_file:
for name in zip_file.namelist()[::-1]:
try:
return Image.open(BytesIO(zip_file.read(name)))
except UnidentifiedImageError:
... | 21,442 |
def construct_getatt(node):
"""
Reconstruct !GetAtt into a list
"""
if isinstance(node.value, (six.text_type, six.string_types)):
return node.value.split(".")
elif isinstance(node.value, list):
return [s.value for s in node.value]
else:
raise ValueError("Unexpected node ... | 21,443 |
def check_root():
"""
Check whether the program is running
as root or not.
Args:
None
Raises:
None
Returns:
bool: True if running as root, else False
"""
user = os.getuid()
return user == 0 | 21,444 |
def rss(x, y, w, b):
"""residual sum of squares for linear regression
"""
return sum((yi-(xi*wi+b))**2 for xi, yi, wi in zip(x,y, w)) | 21,445 |
def sortFiles(path, dst, dryRun = False, reverse = False):
"""
Rename the source files to a descriptive name and place
them in the dst folder
path : The source folder containing the files
dst : The destination folder to place the files
dryRun : If True, do not make any changes on disk
... | 21,446 |
def test__read_json_from_gz(mock_pathlib_path_isfile):
"""Tests function ``_read_json_from_gz()``."""
from dirty_cat.datasets.fetching import _read_json_from_gz
from json import JSONDecodeError
dummy_file_path = Path("file/path.gz")
# Passing an invalid file path (does not exist).
mock_pathli... | 21,447 |
def get_index(lang, index):
"""
Given an integer index this function will return the proper string
version of the index based on the language and other considerations
Parameters
----------
lang : str
One of the supported languages
index : int
Returns
-------
str
... | 21,448 |
def sampleFunction(x: int, y: float) -> float:
"""
Multiply int and float sample.
:param x: x value
:type x: int
:param y: y value
:type y: float
:return: result
:return type: float
"""
return x * y | 21,449 |
def n_elements_unique_intersection_np_axis_0(a: np.ndarray, b: np.ndarray) -> int:
"""
A lot faster than to calculate the real intersection:
Example with small numbers:
a = [1, 4, 2, 13] # len = 4
b = [1, 4, 9, 12, 25] # (len = 5)
# a, b need to be unique!!!
unique(concat(a,... | 21,450 |
def test_power():
"""
Test raising quantities to a power.
"""
values = [2 * kilogram, np.array([2]) * kilogram,
np.array([1, 2]) * kilogram]
for value in values:
assert_quantity(value ** 3, np.asarray(value) ** 3, kilogram ** 3)
# Test raising to a dimensionless quantit... | 21,451 |
def Setup(test_options):
"""Runs uiautomator tests on connected device(s).
Args:
test_options: A UIAutomatorOptions object.
Returns:
A tuple of (TestRunnerFactory, tests).
"""
test_pkg = test_package.TestPackage(test_options.uiautomator_jar,
test_options.uiautom... | 21,452 |
def barcode_junction_counts(inhandle):
"""Return count dict from vdjxml file with counts[barcode][junction]"""
counts = dict()
for chain in vdj.parse_VDJXML(inhandle):
try: # chain may not have barcode
counts_barcode = counts.setdefault(chain.barcode,dict())
except AttributeEr... | 21,453 |
def is_following(user, actor):
"""
retorna True si el usuario esta siguiendo al actor
::
{% if request.user|is_following:another_user %}
You are already following {{ another_user }}
{% endif %}
"""
return Follow.objects.is_following(user, actor) | 21,454 |
def test_workspace_lifecycle(exopy_qtbot, workspace, tmpdir):
"""Test the workspace life cycle.
"""
workbench = workspace.plugin.workbench
log = workbench.get_plugin('exopy.app.logging')
# Check UI creation
def assert_ui():
assert workspace._selection_tracker._thread
assert wor... | 21,455 |
def rf_make_ones_tile(num_cols: int, num_rows: int, cell_type: Union[str, CellType] = CellType.float64()) -> Column:
"""Create column of constant tiles of one"""
jfcn = RFContext.active().lookup('rf_make_ones_tile')
return Column(jfcn(num_cols, num_rows, _parse_cell_type(cell_type))) | 21,456 |
def test_addressing_user_email():
"""Tests making a blockchain address for an user email and that it:
1. is a 35-byte non-zero hexadecimal string
2. is unique - a different user email yields a different address
3. is deterministic - same user email yields same address, even if different case
4. the ... | 21,457 |
def get_block_hash_from_height(height):
"""
Request a block hash by specifying the height
:param str height: a bitcoin block height
:return: a bitcoin block address
"""
resource = f'block-height/{height}'
return call_api(resource) | 21,458 |
def analyze_json(
snippet_data_json: str,
root_dir: str
) -> Tuple[Set[str], Set[str], Set[str], List[pdd.PolyglotDriftData]]:
"""Perform language-agnostic AST analysis on a directory
This function processes a given directory's language-specific
analysis (stored in a polyglot_snippet_data.json file... | 21,459 |
def hover_over_element(id_or_elem):
"""Hover over an element using Selenium ActionChains.
:argument id_or_elem: The identifier of the element, or its element object.
"""
elem = _get_elem(id_or_elem)
action = action_chains.ActionChains(_test.browser)
action.move_to_element(elem)
action.perf... | 21,460 |
def delete_metrics(conn, metric_names_list):
"""
:type conn: pyKairosDB.connect object
:param conn: the interface to the requests library
:type metric_names_list: list of str
:param metric_names_list: A list of metric names to be deleted
"""
for metric in metric_names_list:
delete_m... | 21,461 |
def list_clusters(event, context):
"""List clusters"""
clusters = []
cluster_items = storage.get_cluster_table().scan()
for cluster in cluster_items.get('Items', []):
clusters.append(cluster['id'])
return {
"statusCode": 200,
"body": json.dumps(clusters)
} | 21,462 |
def run():
"""Tally end-of-timestep quantities."""
print("\n" + "-" * 79)
print("Tally step ({:4d})".format(time.step))
print("-" * 79)
# Start-of-step radiation energy density
radnrgdens = np.zeros(mesh.ncells)
radnrgdens[:] = phys.a * mesh.temp[:] ** 4
# Temperature increase
nrg_... | 21,463 |
def round(data):
"""Compute element-wise round of data.
Parameters
----------
data : relay.Expr
The input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.round(data) | 21,464 |
def deserialize(member, class_indexing):
"""
deserialize
"""
class_name = member[0].text
if class_name in class_indexing:
class_num = class_indexing[class_name]
else:
return None
bnx = member.find('bndbox')
box_x_min = float(bnx.find('xmin').text)
box_y_min = floa... | 21,465 |
def interval_weighting(intervals, lower, upper):
"""
Compute a weighting function by finding the proportion
within the dataframe df's lower and upper bounds.
Note: intervals is of the form ((lower, upper, id), ...)
"""
if len(intervals) == 1:
return np.asarray([1])
wts = np.ones(le... | 21,466 |
async def monitor_buttons(reverse_pin, slower_pin, faster_pin, controls):
"""Monitor buttons that reverse direction and change animation speed.
Assume buttons are active low.
"""
with keypad.Keys(
(reverse_pin, slower_pin, faster_pin), value_when_pressed=False, pull=True
) as keys:
w... | 21,467 |
def centroid_precursor_frame(mzml_data_struct):
"""
Read and returns a centroid spectrum for a precursor frame
This function uses the SDK to get and return an MS1 centroid spectrum for
the requested frame.
Parameters
----------
mzml_data_struct : dict
structure of the mzml data
... | 21,468 |
def floor_ts(
ts: Union[pd.Timestamp, pd.DatetimeIndex], freq=None, future: int = 0
) -> Union[pd.Timestamp, pd.DatetimeIndex]:
"""Floor timestamp to period boundary.
i.e., find (latest) period start that is on or before the timestamp.
Parameters
----------
ts : Timestamp or DatetimeIndex.
... | 21,469 |
def start_xmlrpc_server():
"""
Initialize the XMLRPC thread
"""
def register_module(module):
for name, function in module.__dict__.items():
if hasattr(function, '__call__'):
server.register_function(function, name)
print("[+] Starting XMLRPC server: {}:{}".format... | 21,470 |
def check_results(jobname, app_config):
"""" return T/F if there is a results file """
fp = results_file_path(jobname, app_config)
# if results file exists and it's non-zero size, then true
return( os.path.exists(fp) and os.path.getsize(fp) > 0) | 21,471 |
def create_geo_database():
"""
Create a geo db.
"""
log.info("Starting to create the geo db")
log.info("Waiting for the database to be ready")
log.info(f"Testing connection on host: {ctx.geo_db_hostname} and port {ctx.geo_db_port}")
# We need to sleep and retry ubtil the db wakes up
s =... | 21,472 |
def createNewForest():
"""Returns a dictionary for a new forest data structure."""
forest = {'width': WIDTH, 'height': HEIGHT}
for x in range(WIDTH):
for y in range(HEIGHT):
if (random.randint(1, 10000) / 100) <= INITIAL_TREE_DENSITY:
forest[(x, y)] = TREE # Start as a t... | 21,473 |
def vardamp(iter):
"""
execute trajs in vardamp folder
"""
#folderpath = '/home/fan/workspace/EOC/matlab/trajs/vardamp/command/'
#filenames = glob.glob(folderpath+'*.csv')
#savefolder = '/home/fan/workspace/EOC/matlab/trajs/vardamp/record/'
folderpath = '/home/fan/catkin_ws/src/maccepavd/pym... | 21,474 |
def test_show_external_log_redirect_link_with_local_log_handler(capture_templates, admin_client, endpoint):
"""Do not show external links if log handler is local."""
url = f'{endpoint}?dag_id=example_bash_operator'
with capture_templates() as templates:
admin_client.get(url, follow_redirects=True)
... | 21,475 |
def test_filter():
"""
Base class filter function
"""
def test():
"""
Test the filter function
"""
try:
for i in _TEST_FRAME_.keys():
for j in range(10):
test = _TEST_FRAME_.filter(i, "<", j)
assert all(map(lambda x: x < j, test[i]))
test = _TEST_FRAME_.filter(i, "<=", j)
assert a... | 21,476 |
def exp_moving_average(values, window):
""" Numpy implementation of EMA
"""
if window >= len(values):
if len(values) == 0:
sma = 0.0
else:
sma = np.mean(np.asarray(values))
a = [sma] * len(values)
else:
weights = np.exp(np.linspace(-1., 0., window)... | 21,477 |
def update_auth_data(auth_data: dict, ex: int = None):
"""
更新认证数据
:param auth_data: 登录认证数据
:param ex: 数据过期秒数
"""
RedisUtils().set('token:' + auth_data.get('token'), auth_data, ex) | 21,478 |
def parabolic(f, x):
"""
Quadratic interpolation in order to estimate the location of a maximum
https://gist.github.com/endolith/255291
Args:
f (ndarray): a vector a samples
x (int): an index on the vector
Returns:
(vx, vy): the vertex coordinates of a parabola passing... | 21,479 |
def texture(
mh,
tex_info,
location, # Upper-right corner of the TexImage node
label, # Label for the TexImg node
color_socket,
alpha_socket=None,
is_data=False,
):
"""Creates nodes for a TextureInfo and hooks up the color/alpha outputs."""
x, y = location
pytexture = ... | 21,480 |
def arith_expr(draw):
"""
arith_expr: term (('+'|'-') term)*
"""
return _expr_builder(draw, term, '+-') | 21,481 |
def test_clonotype_clusters_end_to_end(
adata_define_clonotype_clusters,
receptor_arms,
dual_ir,
same_v_gene,
within_group,
expected,
expected_size,
):
"""Test define_clonotype_clusters with different parameters"""
ir.pp.ir_dist(
adata_define_clonotype_clusters,
cutof... | 21,482 |
def extract_running_speed(module_params):
"""Writes the stimulus and pkl paths to the input json
Parameters
----------
module_params: dict
Session or probe unique information, used by each module
Returns
-------
module_params: dict
Session or probe unique information, used by each ... | 21,483 |
def sliced_transposed_product(
mat,
block_size,
axes=(-1,),
precision=lax.Precision.DEFAULT,
):
"""Returns the blocked slices representing a symmetric contraction.
Specifically, the output is a contraction of the input mat with itself, in the
specified axes.
Args:
mat: The matrix... | 21,484 |
def _is_ipython_line_magic(line):
"""
Determines if the source line is an IPython magic. e.g.,
%%bash
for i in 1 2 3; do
echo $i
done
"""
return re.match(_IS_IPYTHON_LINE_MAGIC, line) is not None | 21,485 |
def osu_to_excel(
osu_path: str,
excel_path: str = '',
n: int = None,
compact_log: bool = False,
display_progress=True,
**kwargs
) -> str:
"""Export metadata and hitobjects in a xlsx file."""
metadata = from_osu(
osu_path,
n=n,
compact_log=compact_log,
display_progress=display_progress
)
mode =... | 21,486 |
def get_cluster_env() -> ClusterEnv:
"""Get cardano cluster environment."""
socket_path = Path(os.environ["CARDANO_NODE_SOCKET_PATH"]).expanduser().resolve()
state_dir = socket_path.parent
work_dir = state_dir.parent
repo_dir = Path(os.environ.get("CARDANO_NODE_REPO_PATH") or work_dir)
instance_... | 21,487 |
def convert_pybites_chars(text):
"""Swap case all characters in the word pybites for the given text.
Return the resulting string."""
return "".join(
char.swapcase() if char.lower() in PYBITES else char for char in text
) | 21,488 |
def get_meminfo():
"""
Return the total memory (in MB).
:return: memory (float).
"""
mem = 0.0
with open("/proc/meminfo", "r") as fd:
mems = fd.readline()
while mems:
if mems.upper().find("MEMTOTAL") != -1:
try:
mem = float(mems.s... | 21,489 |
def process_inline_semantic_match(placeholder_storage, match_object):
"""
Process a single inline-semantic match object.
"""
delimiter = match_object.group('delimiter')
tag_name = TAG_NAME_FROM_INLINE_SEMANTIC_DELIMITER[delimiter]
attribute_specification = match_object.group('attribute_specification')... | 21,490 |
async def insert_cd_inurl_name(cluster_id: str, iso_name: str):
""" Find SR by Name """
try:
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
except KeyError as key_error:
raise HTTPException(
... | 21,491 |
def main_add(args):
"""Start the add-environment command and return exit status code."""
return add_env_spec(args.directory, args.name, args.packages, args.channel) | 21,492 |
def download(version):
"""Download the release archive for |version|."""
# This is the timeout used on each blocking operation, not the entire
# life of the connection. So it's used for initial urlopen and for each
# read attempt (which may be partial reads). 5 minutes should be fine.
TIMEOUT = 5 ... | 21,493 |
def clean_galaxy(name: str, data_directory: str, yes_flag: bool) -> None:
"""Clean galaxy directory for specified galaxy
Args:
name (str): Name of the galaxy
data_directory (str): dr2 data directory
yes_flag (bool): switch to skip asking before removing
"""
print(f"Cleaning file... | 21,494 |
def write(objct, fileoutput, binary=True):
"""
Write 3D object to file. (same as `save()`).
Possile extensions are:
- vtk, vti, npy, npz, ply, obj, stl, byu, vtp, vti, mhd, xyz, tif, png, bmp.
"""
obj = objct
if isinstance(obj, Points): # picks transformation
obj = objct.polydat... | 21,495 |
def npy2point(folder='ct_train', to_save='v', number_points=300, dim=3, crop_size=224, tocrop=False):
"""
convert .npy to point cloud
:param folder: the folder name of the data set
:param to_save: choose which oen to save. 'v' represents vertices, 'p' represents plots, '' represents all.
:param numb... | 21,496 |
def instantiate_env_class(builder: IRBuilder) -> Value:
"""Assign an environment class to a register named after the given function definition."""
curr_env_reg = builder.add(
Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line)
)
if builder.fn_info.is_nested:
buil... | 21,497 |
def initialize():
"""
Initialise Halcon
"""
# path where dl_training_PK.hdl and dl_visulaization_PK.hdl files are located | 21,498 |
def validate_recaptcha(token):
"""
Send recaptcha token to API to check if user response is valid
"""
url = 'https://www.google.com/recaptcha/api/siteverify'
values = {
'secret': settings.RECAPTCHA_PRIVATE_KEY,
'response': token
}
data = urlencode(values).encode("utf-8")
... | 21,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.