content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def show_branch_panel(
on_done,
local_branches_only=False,
remote_branches_only=False,
ignore_current_branch=False,
ask_remote_first=False,
local_branch=None,
selected_branch=None):
"""
Show a quick panel with branches. The callback `on_done(branch)` will
... | 47,800 |
def map_str(string,char_encoding=default_char_encoding):
"""
Maps
"""
hold = torch.Tensor([char_encoding[x] for x in string])
hold = hold.long()
return hold | 47,801 |
def dav_index(context, data):
"""List files in a WebDAV directory."""
# This is made to work with ownCloud/nextCloud, but some rumor has
# it they are "standards compliant" and it should thus work for
# other DAV servers.
url = data.get("url")
context.log.info("Fetching WebDAV path: %s" % url)
... | 47,802 |
def parse_section(section):
"""
Works out the component and section from the "Section" field.
Sections like `python` or `libdevel` are in main.
Sections with a prefix, separated with a forward-slash also show the
component.
It returns a list of strings in the form [component, section].
For ... | 47,803 |
def test_set_default_values_none_needed(test_attributes_semiconductor):
"""should set default values for each parameter <= 0.0."""
test_attributes_semiconductor["application_id"] = 2
test_attributes_semiconductor["construction_id"] = 4
test_attributes_semiconductor["power_rated"] = 0.5
test_attribut... | 47,804 |
def tpm3_exon1_exon8_t_to_g():
"""Create test fixture for TPM3."""
params = {
"gene": "TPM3",
"chr": "NC_000001.11",
"start": 154192135,
"end": 154170399,
"exon_start": 1,
"exon_end": 8,
"exon_end_offset": 0,
"exon_start_offset": 0,
"transc... | 47,805 |
def ecg_rsp(ecg_rate, sampling_rate=1000, method="vangent2019"):
"""**ECG-Derived Respiration (EDR)**
Extract ECG-Derived Respiration (EDR), a proxy of a respiratory signal based on heart rate. *
Note that this implementation is far from being complete, as the information in the related
papers prevents... | 47,806 |
def _get_version() -> str:
"""Returns the package version.
Adapted from:
https://github.com/deepmind/dm-haiku/blob/d4807e77b0b03c41467e24a247bed9d1897d336c/setup.py#L22
Returns:
Version number.
"""
path = '__init__.py'
version = '__version__'
with open(path) as fp:
for line in fp:
if lin... | 47,807 |
def find_misparsed_node(section_node, label, change, amended_labels):
""" Nodes can get misparsed in the sense that we don't always know where
they are in the tree. This uses label to find a candidate for a mis-parsed
node and creates an appropriate change. """
candidates = find_candidate(section_node,... | 47,808 |
def degree_corrected_community_generative_model(num_nodes, class_prob,
bp_mu, bp_alpha, bp_beta,
node_theta,
burnin, end_time, n_cores=1, seed=None):
"""
Degree correct... | 47,809 |
def neighborhood(
iterable: List[Any],
) -> Generator[Any, Any, Any]:
""" """
if not iterable:
return iterable
iterator = iter(iterable)
prev_item = None
current_item = next(iterator) # throws StopIteration if empty.
for next_item in iterator:
yield (prev_item, current_item... | 47,810 |
def grafieken():
"""Deze functie maakt grafieken en plaatst ze in de template.
:return: de HTML pagina
"""
top_3_organismen_grafiek() # Functie die grafiek aanmaakt over de database
top_10_hoogste_scores() # Functie die grafiek aanmaakt over de database
return render_template('grafieken.... | 47,811 |
def path():
"""
传过来给定图片的路径即可,需要绝对路径
:return:
:rtype:
"""
jsonres = request.get_json()
#images是图片的路径
image_dir= jsonres.get('images', None)
#识别图片的路径
image_file_list = get_image_file_list(image_dir)
#把所有的图片的名字,bbox,识别结果放在一个tuple里面返回
images_result = []
for image_file in ... | 47,812 |
def optimizetou(ex,n,pl,pt,l,s,datapath):
"""Helps you optimize time of use tariff
Arguments:
datapath: provide a folder path containing all input .csv files
"""
pt = pt.split(',')
print(pt)
config_dict = {
'export_path': os.path.join(ex,n),
'plot_result': pl,
... | 47,813 |
def input_pipeline(filenames,
experiment_proto,
final_mbsz,
hps,
num_epochs=None,
num_threads=1):
"""Using Queues create an infinite stream of training minibatches.
Args:
filenames: list of paths to sstables tf.Examp... | 47,814 |
def mAP(iou_threshold=0.5, threshold=0.01) -> CallbackProtocol:
"""Build a callback that computes mAP. All kwargs
passed to detector.mAP()"""
# pylint: disable=unused-argument
def callback(detector, summaries, data_dir):
return {
f"{split}_mAP": round(
np.nanmean(
... | 47,815 |
def run_n_experiment(src_path, target_language='es', n_train=2000, n_to_copy=None, eval_tta=False,
n_test=3000,
do_baseline=True, tta_langs=('et',), **classif_kwargs):
"""Experiment on smaller version of IMBD with different augmentation strategies"""
reference_path = ma... | 47,816 |
def update_table1(is_open, signup, user_edit, user_remove):
"""update_table
"""
df = lookup_data()
# Add icons
df[_('Active')] = df[_('Active')].apply(lambda x:
html.I(className="fa fa-check") if x else None
)
df[_('Edit')] = df[_('UID')].apply(lambda x:
dbc.Button(
... | 47,817 |
def pip():
"""Install python requirements. Alternatively, use Pipenv."""
local("pip install -r requirements/base.txt") | 47,818 |
def sync_images():
"""Run image sync using an action.
Execute an initial image sync using an action to ensure that the
cloud is populated with images at the right point in time during
deployment.
"""
logging.info("Synchronising images using glance-simplestreams-sync")
generic_utils.assertAc... | 47,819 |
def get_std_encoding(stream):
"""
Get encoding of the stream
Args:
stream: stream
Returns:
encoding or file system encoding
"""
return getattr(stream, "encoding", None) or sys.getfilesystemencoding() | 47,820 |
def create_app(*args, **kwargs):
"""
Create flask app with predefined values.
:return: Flask application
"""
"""Create flask app with all configuration set"""
app = flask.Flask(__name__)
app.register_blueprint(pps_blueprint)
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO... | 47,821 |
def _rebase_node(curr: Optional[SQLNode], pre: SQLNode) -> SQLNode:
"""shorthand for a common pattern"""
return pre if curr is None else curr.rebase(pre) | 47,822 |
async def test_kp_unavailable(client):
"""
Test that when a KP is unavailable we add a message to
the log but continue running
"""
QGRAPH = query_graph_from_string(
"""
n0(( categories[] biolink:ChemicalSubstance ))
n0(( ids[] CHEBI:6801 ))
n0-- biolink:treats -->n1
... | 47,823 |
def tweet_movie():
"""
Tweets a random movie stored in the local database.
"""
init_db(DB_PATH)
movie = get_next_movie()
logger.info("Selected movie: Name='%s', LanguageId='%s'",
movie.name, DEFAULT_LANGUAGE_ID)
stop_words = get_stop_words()
wc = WordCloud(movie, stop_wor... | 47,824 |
def proposal_list(request):
"""Retrieve and return a list of proposals, optionally
filtered by the given acceptance status.
Requires API Key.
URL: /<YEAR>/pycon_api/proposals/
To filter by proposal type, add a GET query param "type" with
a value of "talk", "tutorial", "lightning", or "poster"... | 47,825 |
def apply_mask(image, mask, color, alpha=0.5):
"""Apply the given mask to the image.
"""
for c in range(3):
image[:, :, c] = np.where(mask == 1,
image[:, :, c] *
(1 - alpha) + alpha * color[c] * 255,
... | 47,826 |
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py
"""
string = unidecode(string)
string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
string = re.sub(r"\'s", " \'s... | 47,827 |
def test_handles_add_labware_offset(
subject: LabwareStore,
) -> None:
"""It should add the labware offset to the state and add the ID."""
request = LabwareOffsetCreate(
definitionUri="offset-definition-uri",
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
vector=LabwareOffs... | 47,828 |
def dkm_ms_em_remote_check_stopping(w, wo, epsilon):
"""
Stopping condition is distance below some epsilon
"""
delta = np.sum([abs(w[i] - wo[i]) for i in range(len(w))])
# print("Delta", delta)
result = delta > epsilon
return result | 47,829 |
def test_lint_mypy():
"""Verifies mypy linting."""
subprocess.run([sys.executable, "-m", "mypy", ROOT_DIR], check=True) | 47,830 |
def create_kms(c):
"""Create a predefined KMS for pipes"""
c.run(' '.join([
f'gcloud kms keyrings create {KEYRING}',
get_project_option(),
f'--location=global',
]))
c.run(' '.join([
f'gcloud kms keys create {KEY}',
get_project_option(),
f'--location=globa... | 47,831 |
def parse_from_string(root_processor, xml_string):
"""
Parses the XML string using the processor starting from the root of the document.
:param xml_string: XML string to parse.
See also :func:`declxml.parse_from_file`
"""
if not _is_valid_root_processor(root_processor):
raise InvalidRo... | 47,832 |
def validate(args, limit_to=None):
"""Validate an input dictionary for Coastal Blue Carbon.
Args:
args (dict): The args dictionary.
limit_to=None (str or None): If a string key, only this args parameter
will be validated. If ``None``, all args parameters will be
validat... | 47,833 |
def findBestK(x_train, y_train, params, R):
""" Función que calcula los valores de accuracy media obtenidos con validación
cruzada para los valores del parámetro K que se indican como parámetro, y
visualiza dichos valores en un gráfico
Args:
x_train: conjunto de entrena... | 47,834 |
def pdf_to_img(pdf: str) -> [str]:
"""
Takes a base64 encoded string representing a PDF and turns it into a list of base64 encoded strings
representing pages in the PDF
:param pdf:
:return: list of strings
"""
imgs = list()
decoded = b64string_to_bytes(pdf)
images = convert_from_byte... | 47,835 |
def is_ready():
"""Checks if IoT Inspector is ready to interface with the AR app."""
return OK_JSON | 47,836 |
def get_indicators_command(client: Client, insight_category: list, insight_data_type: list, args: dict) -> List[Dict]:
"""Create indicators.
Arguments:
client {Client} -- Client derives from BaseClient.
insight_category {List[String]} -- List of SafeBreach insight categ... | 47,837 |
def create_container(
image_id: str,
container_name: str,
mounts: tp.Optional[tp.List[str]] = None
) -> str:
"""
Create, but do not start, an OCI container.
Refer to 'buildah create --help' for details about mount
specifications and '--replace'.
Args:
image_id: The container im... | 47,838 |
def train_model(training_data: list[tuple], test_data: list[tuple], count: int):
"""
Trains model given training data. Code structure taken from https://realpython.com/sentiment-analysis-python
Changes were made due to some efficiency issues, unclear code, and outdated uses of APIs and libraries
"""
... | 47,839 |
def engineer_features(df,training=True):
"""
for any given day the target becomes the sum of the next days revenue
for that day we engineer several features that help predict the summed revenue
the 'training' flag will trim data that should not be used for training
when set to false all data wi... | 47,840 |
def inconsistent_target_program():
"""Returns a benchmark.Benchmark with an inconsistent target program."""
examples = [
benchmark.Example(
inputs=[
[10],
[20],
],
output=[40], # Should be 30.
),
]
constants = [0]
description = 'add elemen... | 47,841 |
def _slice_slice(outer, outer_len, inner, inner_len):
"""
slice a slice - we take advantage of Python 3 range's support
for indexing.
"""
assert(outer_len >= inner_len)
outer_rng = range(*outer.indices(outer_len))
rng = outer_rng[inner]
start, stop, step = rng.start, rng.stop, rng.step
... | 47,842 |
def tp(a):
"""Tranpose 1d vector"""
return a[np.newaxis].T | 47,843 |
def _parse_interval(value):
"""
Do some nasty try/except voodoo to get some sort of datetime
object(s) out of the string.
"""
try:
return sorted(aniso8601.parse_interval(value))
except ValueError:
try:
return aniso8601.parse_datetime(value), None
except ValueE... | 47,844 |
def test_rrm_beacon_req_table_unknown_subelem(dev, apdev):
"""Beacon request - beacon table mode - unknown subelement"""
params = {"ssid": "rrm", "rrm_beacon_report": "1"}
hapd = hostapd.add_ap(apdev[0], params)
dev[0].connect("rrm", key_mgmt="NONE", scan_freq="2412")
addr = dev[0].own_addr()
... | 47,845 |
def is_masquerading_as_non_audit_enrollment(user, course_key, course_masquerade=None):
"""
Return if the user is a staff member masquerading as a user
in _any_ enrollment track _except_ audit
"""
group_id = _get_masquerade_group_id(ENROLLMENT_TRACK_PARTITION_ID, user, course_key, course_masquerade)
... | 47,846 |
def holding_value_grouped_nb(holding_value, group_lens):
"""Get holding value series per group."""
check_group_lens(group_lens, holding_value.shape[1])
out = np.empty((holding_value.shape[0], len(group_lens)), dtype=np.float_)
from_col = 0
for group in range(len(group_lens)):
to_col = from_... | 47,847 |
def read_upload(up_file, data_model=None):
"""
take a file that should be ready for upload
using the data model, check that all required columns are full,
and that all numeric data is in fact numeric.
print out warnings for any validation problems
return True if there were no problems, otherwise... | 47,848 |
def predict(network, X, batch_size, device, move_network=True):
""" predict batchwise """
# Build DataLoader
if move_network:
network = network.to(device)
y = torch.Tensor(X.size()[0])
data = DataLoader(TensorDataset(X, y), batch_size, False)
# Batch prediction
network.eval()
r, ... | 47,849 |
def get_token(username, password, returnsession=False, s=requests.Session()):
"""Issues a login request. The token returned by this function
is required for all methods in this module.
@param username: The marketwatch.com username (email).
@param password: The plaintext marketwatch.com password.
@return: Requests... | 47,850 |
def assert_equals_numpy_array(input_variable, base_value, allow_nan=False):
"""Input variable must be numpy array with all elements == some real number.
:param input_variable: Input variable.
:param base_value: All elements must == this number.
:param allow_nan: Boolean flag. If True, array elements a... | 47,851 |
def read_glossary_df(plugins):
"""Returns the glossary as a DataFrame, created from the schemas.yml file. NOTE: This is used by the GUI."""
global __glossary_df
if __glossary_df is None:
schemas = cea.schemas.schemas(plugins)
glossary_df = pd.DataFrame(columns=["SCRIPT", "LOCATOR_METHOD", "W... | 47,852 |
def extract_all(session_path, save=False, data=False):
"""
Extract all behaviour data from Bpod whithin the specified folder.
The timing information from FPGA is extracted in
:func:`~ibllib.io.extractors.ephys_fpga`
:param session_path: folder containing sessions
:type session_path: str or pat... | 47,853 |
def tokenize(data):
""" Tokenization.
Tokenize and lemmatize the sentences; extract labels of tokens.
Parameters
----------
data : list of dict
each dict should have the following form:
{"sentence": str,
"sentence_id": str,
"annotations": [
{"ann_id": str
"text": str,
"sta... | 47,854 |
def shn_import_csv(file, table=None):
""" Import CSV file into Database """
if table:
table.import_from_csv_file(file)
else:
# This is the preferred method as it updates reference fields
db.import_from_csv_file(file)
db.commit() | 47,855 |
def store_all_unfollowers(username, all_unfollowers, logger, logfolder):
""" Store all Unfollowers data in a local storage at generated date """
generation_date = datetime.today().strftime("%d-%m-%Y")
all_unfollowers_size = len(all_unfollowers)
file_directory = "{}/relationship_data/{}" \
... | 47,856 |
def rotate_thread(thymio: Thymio, angle: float, verbose: bool = False, function=stop, args=None, kwargs=None):
"""
Rotates of the desired angle by using a timer on a parallel thread.
:param function: function to execute at the end of rotation, default stop
:param args: array of non-keyworded ... | 47,857 |
def first(pcollection, **options):
"""
取出PCollection中的第一个元素
Args:
pcollection (PCollection): 输入PCollection
**options: 可配置选项
Returns:
PObject: 取出的单个元素,以PObject给出
>>> from bigflow import transforms
>>> _p = _pipeline.parallelize([3, 7, 1, 3, 2, 8])
>>> transforms.first(... | 47,858 |
def select_values_over_last_axis(values, indices):
"""
Auxiliary function to select logits corresponding to chosen tokens.
:param values: logits for all actions: float32[batch,tick,action]
:param indices: action ids int32[batch,tick]
:returns: values selected for the given actions: float[batch,tick]... | 47,859 |
def dump_adcs(adcs, drvname='ina219', interface=2):
"""Dump xml formatted INA219 adcs for servod.
Args:
adcs: array of adc elements. Each array element is a tuple consisting of:
slv: int representing the i2c slave address plus optional channel if ADC
(INA3221 only) has multiple channels. ... | 47,860 |
def list_launch_agents():
"""
Return an array of the files that are present in ~/Library/LaunchAgents,
/System/Library/LaunchAgents/ and /Library/LaunchAgents/
"""
files = list_system_launch_agents()
files += list_library_launch_agents()
files += list_homedir_launch_agents()
return files | 47,861 |
def get_projection_point_dst(coords_src, M):
""" Gets the coordinate equivalent in surface projection space from original
view space
Args:
coords_src: `numpy.darray` coordinate in the original image space
M: `numpy.darray` rotation matrix
Returns:
coords_src: `numpy.da... | 47,862 |
def test_eval_void():
"""
Check that conn.voidEval() does not return any result in contrast to
conn.eval()
"""
assert conn.r('a=1') == 1.0
assert conn.eval('a=1') == 1.0
assert conn.voidEval('a=1') is None
assert conn.eval('a=1', void=True) is None
assert conn.r('a=1', void=True) is ... | 47,863 |
def torchify(a):
"""Converts an array or a dict of numpy arrays to CPU tensors.
If you'd like CUDA tensors, follow the tensor-ification ``.cuda()`` ; the attribute delegation
built into :class:`~rebar.dotdict.dotdict` s will do the rest.
Floats get mapped to 32-bit PyTorch floats; ints get mapped ... | 47,864 |
def cache_apps(sg_connection, cfg_descriptor, bundle_cache_root):
"""
Iterates over all environments within the given configuration descriptor
and caches all items into the bundle cache root.
:param sg_connection: Shotgun connection
:param cfg_descriptor: Config descriptor
:param bundle_cache_r... | 47,865 |
def respond_to_help_command(message):
"""Send help message to requesting user"""
bot.send_chat_action(message.chat.id, "typing")
bot.send_message(
message.chat.id, messages.HELP_MESSAGE, parse_mode="Markdown"
) | 47,866 |
def rel_angle(vec_set1, vec_set2):
"""
Calculate the relative angle between two vector sets
Args:
vec_set1(array[array]): an array of two vectors
vec_set2(array[array]): second array of two vectors
"""
return vec_angle(vec_set2[0], vec_set2[1]) / vec_angle(
vec_set1[0], vec_... | 47,867 |
def create_dir():
"""create dir if not exist"""
for dir_name in TUNING_DATA_DIRS:
Path(TUNING_DATA_PATH + dir_name).mkdir(parents=True, exist_ok=True) | 47,868 |
def test_norm_sum():
"""Test RMS of sum of zernikes is the square root of the sum of the coefficients."""
# set up coordinates
x = np.linspace(-1, 1, 2048)
xx, yy = np.meshgrid(x, x) # xy indexing is default
r, theta = cart2pol(yy, xx)
# make coefs
np.random.seed(12345)
c0, c1 = np.rand... | 47,869 |
def equalization(data, equilibrium_points):
"""
Эквализация данных.
Параметры:
data - таблица данных, которые нужно выровнять. Тип - pandas.DataFrame.
equilibrium_points - точки сдвига равновесия. Для каждого столбца нужно
использовать свою точку равновесия, т.к. у каждой кривой должна ... | 47,870 |
def from_config(config_file="./config.json"):
"""Run training from a config file
:param config_file: JSON file with arguments as per "training" CLI.
:return:
"""
import json
with open(config_file, "r") as f:
config_string = f.read()
config = json.loads(config_string)
return ... | 47,871 |
def load_anomalies_text(input_path):
"""Loads the Anomalies proto stored in text format in the input path.
Args:
input_path: File path from which to load the Anomalies proto.
Returns:
An Anomalies protocol buffer.
"""
anomalies = anomalies_pb2.Anomalies()
anomalies_text = file_io.read_file_to_stri... | 47,872 |
def mkMatQ(l: int) -> np.ndarray:
"""
Create the special permutation matrix
Parameters
----------
l : int
Returns
-------
out : np.ndarray
Square array size 2*l+1, see Examples
See Also
-------
permutationMat
Examples
--------
>>> mkMatQ(2)
[[0, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[1, 0, 0, 0, 0],
... | 47,873 |
def is_isbn_or_key(q):
"""
判断搜索关键字是isbn还是key
:param q:
:return:
"""
# isbn13 13位0-9数字;isbn10 10位0-9数字,中间含有 '-'
isbn_or_key = 'key'
if len(q) == 13 and q.isdigit():
isbn_or_key = 'isbn'
if '-' in q:
short_q = q.replace('-', '')
if len(short_q) == 10 and short_q... | 47,874 |
def find_scripts(entry_points=False, suffix=''):
"""Find IPython's scripts.
if entry_points is True:
return setuptools entry_point-style definitions
else:
return file paths of plain scripts [default]
suffix is appended to script names if entry_points is True, so that the
Python 3 s... | 47,875 |
def text_group(msg):
""" 监听用户消息,用于自动回复 """
handle_group_helper(msg) | 47,876 |
def get_upright_box(waymo_box):
"""Convert waymo box to upright box format and return the convered box."""
xmin = waymo_box.center_x - waymo_box.length / 2
# xmax = waymo_box.center_x+waymo_box.length/2
ymin = waymo_box.center_y - waymo_box.width / 2
# ymax = waymo_box.center_y+waymo_box.width/2
... | 47,877 |
def trigger_caching():
"""Triggers manual caching of a specific transaction (MetadataCreated or MetadataUpdated event)
---
tags:
- name
consumes:
- application/json
parameters:
- name: transactionId
required: true
description: transaction id containing MetadataCreat... | 47,878 |
def update_two_contribution_score(click_time_one, click_time_two):
"""
user cf user contribution score update v2
:param click_time_one: different user action time to the same item
:param click_time_two: time two
:return: contribution score
"""
delta_time = abs(click_time_two - click_time_one... | 47,879 |
def series_dropna(series, axis=0, inplace=False, how=None):
"""
Return a new Series with missing values removed.
See the :ref:`User Guide <missing_data>` for more on which values are
considered missing, and how to work with missing data.
Parameters
----------
axis : {0 or 'index'}, default... | 47,880 |
def partial_escape(xpath):
"""
Copied from http://stackoverflow.com/questions/275174/how-do-i-perform-html-decoding-encoding-using-python-django
but without replacing the single quote
"""
return mark_safe(force_unicode(xpath).replace('&', '&').replace('<', '<').replace('>', '>').replace('... | 47,881 |
def identify_regions(lat_lon, coordinates=False):
"""
Returns the region associated with the given lat/lon point.
Args:
lat_lon (:obj:`list` of :obj:`float`): latitude/longitude point to
access
coordinates (bool): optionally include a list of all registered
coordinates f... | 47,882 |
def _init_git():
"""Init git locally and to bitbucket"""
from pykern import pkcli
from pykern import pkio
import datetime
import re
import subprocess
title = pkio.py_path().basename
v = datetime.datetime.utcnow().strftime('%Y%m%d-%H%M%S')
name = 'sim-{}-{}'.format(pkio.py_path().bas... | 47,883 |
def fix_text_note(text):
"""Wrap CHS document text."""
if not text:
return ""
else:
return """* CHS "Chicago Streets" Document:\n> «{}»""".format(text) | 47,884 |
def test_device_put_method_end_with_space_brand(flask_app, db): # pylint: disable=unused-argument
""" To verify that registration device
method is working properly and response is correct"""
registration = create_registration(REG_REQ_DATA, uuid.uuid4())
registration.update_status('Pending Review')... | 47,885 |
def GetCBSPLogFile():
"""
Generate the CBSP base file name used for many things, including accessing *jason* files.
"""
return Config.GetCBSPInstanceName() | 47,886 |
def pretty_xml(document: 'Document',
declaration: Optional[str] = None,
encoding: Optional[str] = UTF8,
indent: int = 2) -> str:
"""Render the given :class:`~xml.dom.minidom.Document` `document` into a prettified string."""
kwargs = {
'encoding': encoding or ... | 47,887 |
def cluster(image, R):
"""Split the image points up into a number of clusters
At first there are 10 clusters
1. The centre of each cluster are set to be equally
spaced out in angle, at a radius of 1
2. Each point is looped through and assigned to the
... | 47,888 |
def load_dataset(path: str, train_ratio: float = 0.9):
"""
:param path:
:param train_ratio:
:return:
"""
user_indptr = np.memmap(os.path.join(path, 'user_indptr.bin'), dtype=np.int32, mode='r')
user_indices = np.memmap(os.path.join(path, 'user_indices.bin'), dtype=np.int32, mode='r')
... | 47,889 |
def bbox_xyxy_to_cxcywh(bbox):
"""Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, w, h).
Args:
bbox (Tensor): Shape (n, 4) for bboxes.
Returns:
Tensor: Converted bboxes.
"""
x1, y1, x2, y2 = bbox.split((1, 1, 1, 1), dim=-1)
bbox_new = [(x1 + x2) / 2, (y1 + y2) / 2, (... | 47,890 |
def get_isolated_page(request: HttpRequest) -> bool:
"""Accept a GET param `?nav=no` to render an isolated, navless page."""
return request.GET.get("nav") == "no" | 47,891 |
def merge_overlap_gene_coverage(data_dir, sample_ids, chrom):
"""
For single chromosome, join multiple RNA Seq alignment files' gene coverage vectors for genes in genome
that overlap others on the chromosome of interest. Similar in spirit to merge_chrom_coverage,
but join is over individual genes' cover... | 47,892 |
def migrate(config: dict, app_logger: logger.Logger) -> bool:
"""
Run migration. If :param config['MIGRATION_ID']: is not specified, then run all PENDING migrations starting from
older one. If one of migrations fails then stop execution and return False.
:param config: pymigrate configuration.
:par... | 47,893 |
def test_list_unsigned_short_enumeration_3_nistxml_sv_iv_list_unsigned_short_enumeration_4_5(mode, save_output, output_format):
"""
Type list/unsignedShort is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/unsignedShort/Schema+Instance/NISTSchema-SV-IV-list-unsignedS... | 47,894 |
def stco_copy(in_fh, out_fh, box, delta=0):
"""Copy for stco box.
Args:
in_fh: file handle, source to read index table from.
out_fh: file handle, destination for index file.
box: box, stco box to copy.
delta: int, offset change for index entries.
"""
index_copy(in_fh, out_fh, bo... | 47,895 |
def _fetch_cpu_count():
"""
Returns the number of available CPUs on machine in use.
Parameters:
-----------
None
Returns:
--------
multiprocessing.cpu_count()
Notes:
------
None
"""
return multiprocessing.cpu_count() | 47,896 |
def inspect_lattice(latfile=None, out=None, _machine=None):
"""Inspect FLAME lattice file, print a lattice information report,
if failed, print nothing.
Parameters
----------
latfile :
FLAME lattice file.
out :
output stream, stdout by default.
_machine :
FLAME machi... | 47,897 |
def MakeAxesActor():
"""
Make an axis actor.
:return: The axis actor.
"""
axes = vtkAxesActor()
axes.SetShaftTypeToCylinder()
axes.SetXAxisLabelText('X')
axes.SetYAxisLabelText('Y')
axes.SetZAxisLabelText('Z')
axes.SetTotalLength(1.0, 1.0, 1.0)
axes.SetCylinderRadius(1.0 * a... | 47,898 |
def run_subproc(cmds, captured=False, envs=None):
"""Runs a subprocess, in its many forms. This takes a list of 'commands,'
which may be a list of command line arguments or a string, representing
a special connecting character. For example::
$ ls | grep wakka
is represented by the following c... | 47,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.