seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def ring_to_vector(z_list: list, max_size: int = 9) -> list:
"""
Convert the ring sizes vector to a fixed length vector
For example, l can be [3, 5, 5], meaning that the atom is involved
in 1 3-sized ring and 2 5-sized ring. This function will convert it into
[ 0, 0, 1, 0, 2, 0, 0, 0, 0, 0].
Arg... | bigcode/self-oss-instruct-sc2-concepts |
def mag(db_image):
"""Reverse of log/db: decibel to magnitude"""
return 10 ** (db_image / 20) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Optional
from typing import Tuple
from typing import Dict
import inspect
def gather_init_params(
obj: Any,
ignore: Optional[Tuple[str, ...]] = None,
) -> Dict[str, Any]:
"""Extract the parameters passed to an object's ``__init__()``.
Args:
obj (object... | bigcode/self-oss-instruct-sc2-concepts |
def pythonize(t):
""" Make valid fields ints, essentially deserialize """
t["retweet"] = True if t["retweet"] == "True" else False
t["likes_count"] = int(t["likes_count"])
t["replies_count"] = int(t["replies_count"])
t["retweets_count"] = int(t["retweets_count"])
t["photos"] = t["photos"].split(",")
t["hashtags"... | bigcode/self-oss-instruct-sc2-concepts |
def check_required_params(req, keys):
"""
Helper to check if all valid params are present
"""
for key in keys:
if key not in req.keys():
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def mu_transform(x):
""" Forward operation of mu-law transform for 16-bit integers. """
assert x.min() >= -1 and x.max() <= 1
return torch.sign(x) * torch.log(1 + 32768. * torch.abs(x)) / math.log(1 + 32768.) | bigcode/self-oss-instruct-sc2-concepts |
def max_min_layers(nx_graph, max_layer=True):
"""
Returns the maximal (highest in hierarchy) layer (those nodes with in degree = 0) or the minimal layer (k_out = 0)
:param nx_graph: networkX graph
:param max_layer: Bool, if True, returns maximal layer (k_in = 0), else returns nodes for which k_out = 0, ... | bigcode/self-oss-instruct-sc2-concepts |
def check_balanced_parens(parens):
"""
Given that a string can be composed of parentheses, brackets,
and curly braces, check whether an input string has balanced
brackets.
"""
matches = {
'}': '{',
')': '(',
']': '[',
}
ls = []
for paren in parens:
i... | bigcode/self-oss-instruct-sc2-concepts |
def read_file_lines(file):
"""Returns a list of str lines in text file"""
with open(file, mode="rt", encoding="utf-8") as f:
return f.readlines() | bigcode/self-oss-instruct-sc2-concepts |
def name(layer):
"""Returns the class name of a protocol layer."""
return layer.__class__.__name__ | bigcode/self-oss-instruct-sc2-concepts |
import torch
def training_collate(batch):
"""Custom collate fn for dealing with batches of images.
Arguments:
batch: (tuple) A tuple of tensor images
Return:
(tensor) batch of images stacked on their 0 dim
"""
# imgs = list()
# for img in batch:
# _c, _h, _w = img.sha... | bigcode/self-oss-instruct-sc2-concepts |
def frequency_to_probability(counts_table):
"""
Convert a contingency table expressed in frequencies to one
expressed in probabilities.
"""
total = counts_table.sum()
probs_table = counts_table / float(total)
return probs_table | bigcode/self-oss-instruct-sc2-concepts |
def top_preds(preds, labels, k=5):
"""
Top 1 and top k precision
:param preds: Softmax output tensor with probabilities
:param labels: Labels in batch
:param k: top k precision, default top5
:return:
"""
correct = 0
topk = 0
for i in range(len(labels)):
classes = (-preds... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def get_input_files(cfg, index=0):
"""
Load input configuration file.
Get a dictionary with input files from the metadata.yml files.
"""
metadata_file = cfg['input_files'][index]
with open(metadata_file) as input_file:
metadata = yaml.safe_load(input_file)
return metad... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def gauss_points(
n: float,
) -> List[List[float]]:
"""Returns the Gaussian weights and locations for *n* point Gaussian integration of
a linear triangular element.
:param int n: Number of Gauss points (1, 3 or 6)
:return: An *n x 3* matrix consisting of the integration w... | bigcode/self-oss-instruct-sc2-concepts |
def get_game_info(game):
"""
Gets printable game information.
"""
return (
"%d (%s: %s [%d] vs. %s [%d])" % (
game['game_id'], game['date'], game['home_team'], game['home_score'], game['road_team'], game['road_score'],
)) | bigcode/self-oss-instruct-sc2-concepts |
def scaleData(features):
"""
Normalizes features in order for gradient descent to work correctly (improves the convergence speed of the logistic regression algorithm)
features is an arg containing the sample of feature data to be normalized
Normalization is made using Rescaling (min-max normalization) ... | bigcode/self-oss-instruct-sc2-concepts |
def _GetColFormatString(width, align_right):
"""Returns the format string for a field.
"""
if align_right:
sign = ""
else:
sign = "-"
return "%%%s%ss" % (sign, width) | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_vocab_test(text):
"""
Parse the following structure into list of vocab tokens
Input:
..
..
..
Output:
[result,
hair,
strong,
tear,
..
..
..
]
"""
text = re.sub(' ?\d+ \xef\x81\xb1 ?', '\n', text)
text = re.sub(' ?\d+ ... | bigcode/self-oss-instruct-sc2-concepts |
def AddNodeVersionFlag(parser, hidden=False):
"""Adds a --node-version flag to the given parser."""
help_text = """\
The Kubernetes version to use for nodes. Defaults to server-specified.
The default Kubernetes version is available using the following command.
$ gcloud container get-server-config
"""
return ... | bigcode/self-oss-instruct-sc2-concepts |
def match_keypoints(optical_flow, prev_kps):
"""Match optical flow keypoints
:param optical_flow: output of cv2.calcOpticalFlowPyrLK
:param prev_kps: keypoints that were passed to cv2.calcOpticalFlowPyrLK to create optical_flow
:return: tuple of (cur_matched_kp, prev_matched_kp)
"""
# 当前帧的角点,状态... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def default_dataset_location(dataset_name: str) -> Path:
"""
Return the default location of a dataset.
This currently returns "~/.avalanche/data/<dataset_name>" but in the future
an environment variable bay be introduced to change the root path.
:param dataset_name: The ... | bigcode/self-oss-instruct-sc2-concepts |
def get_km_user_image_upload_path(km_user, imagename):
"""
Get the path to upload the kmuser image to.
Args:
km_user:
The km_user whose image is being uploaded.
imagename (str):
The original name of the image being uploaded.
Returns:
str:
The... | bigcode/self-oss-instruct-sc2-concepts |
def peak(lst: list[int]) -> int:
"""
Return the peak value of `lst`.
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
5
>>> peak([1, 10, 9, 8, 7, 6, 5, 4])
10
>>> peak([1, 9, 8, 7])
9
>>> peak([1, 2, 3, 4, 5, 6, 7, 0])
7
>>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])
4
"""
# mid... | bigcode/self-oss-instruct-sc2-concepts |
def get_country_lat_lon_extent(country):
"""
See https://data.humdata.org/dataset/bounding-boxes-for-countries/resource/aec5d77d-095a-4d42-8a13-5193ec18a6a9
Args:
country:
Returns: longitude(left) longitude(right), latitude (bottom), latitude(top)
"""
#
# 'mexico', 'south_africa', ... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import re
def test_versions(run):
"""Test versions.
config.json - contains the HASS addon version
Dockerfile - installs the specific sunsynk library from pypi
setup.py - sunsynk library on pypi
"""
def _get_version(filename, regex):
txt = Path(filename).r... | bigcode/self-oss-instruct-sc2-concepts |
def hdu_get_time(hdu, time_format='bmjd'):
"""
Will be used as a key function for the list.sort() or sorted() functions.
Example,
hdus.sort(key=hdu_fits_by_time)
where hdus is a list of HDU objects, will call hdu_by_time() on each element
in the list, and then sort the elements according t... | bigcode/self-oss-instruct-sc2-concepts |
def title_case(f_name, l_name):
"""
Take a first name and last name and format it
to return the title case version.
"""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs"
f_name = f_name.lower()
l_name = l_name.lower()
f_name_T = ("{:s}{:s}".format(f_name[... | bigcode/self-oss-instruct-sc2-concepts |
def is_nt_arc_present(rtn, nt_arc_label):
"""
Check if rtn contains nonterminal arc with label nt_arc_label.
:param rtn: RTN FST object
:param nt_arc_label: Nonterminal arc label
:return: Boolean
"""
nt_arc_label = int(nt_arc_label)
for state in rtn.states:
for arc in state.arc... | bigcode/self-oss-instruct-sc2-concepts |
import heapq
def largest_export_versions(n):
"""Creates a filter that keeps the largest n export versions.
Args:
n: number of versions to keep.
Returns:
A filter function that keeps the n largest paths.
"""
def keep(paths):
heap = []
for idx, path in enumerate(paths):
if path.export_... | bigcode/self-oss-instruct-sc2-concepts |
def build_extracted_list(input_list, subinterval):
""" A utility function to extract a number of elements from a list, leaving only a certain subset.
Generates a new list with just the subset. Creates the subset by specifying a sub-interval.
:param input_list: The list to be extracted
:type input_l... | bigcode/self-oss-instruct-sc2-concepts |
def subject_destroy(client, subject_id):
"""Destroy the subject or raise if it does not exist."""
return client.subject_destroy(subject_id=subject_id) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def convert_drive_files_old_to_new(old: Dict[str, Any]) -> Dict[str, Any]:
"""Convert data from the original format (which had "answers-cleaned" field) to a clearer format."""
question_id = old["questionid"]
raw = old["raw-original-answers"]
clusters = {
... | bigcode/self-oss-instruct-sc2-concepts |
def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} | bigcode/self-oss-instruct-sc2-concepts |
def measurement_id(measurement_uuid: str, agent_uuid: str) -> str:
"""
Measurement IDs used by Iris
>>> measurement_id("57a54767-8404-4070-8372-ac59337b6432", "e6f321bc-03f1-4abe-ab35-385fff1a923d")
'57a54767-8404-4070-8372-ac59337b6432__e6f321bc-03f1-4abe-ab35-385fff1a923d'
Measurement IDs used by... | bigcode/self-oss-instruct-sc2-concepts |
def fourier_make_response_real(response):
"""
Turn a frequency filter function into a real one (in the time domain).
Done by reflecting and complex conjugating positive frequency part to negative frequencies.
`response` is a function with a single argument (frequency), return value is a modified fu... | bigcode/self-oss-instruct-sc2-concepts |
def get_avatar(member):
"""Returns default avatar, if custom doesn't exist"""
if member.avatar_url:
return member.avatar_url
return member.default_avatar_url | bigcode/self-oss-instruct-sc2-concepts |
def transform_tone(tone):
"""Transforms keyword `negative`, `neutral` or `positive` into `-1`, `0` or `1`.
:param tone: string representation of tone.
:type tone: str
:return: number representation of tone.
:rtype: str
"""
if 'negative':
return '-1'
elif 'neutral':
retu... | bigcode/self-oss-instruct-sc2-concepts |
def update_param_grid(param_grid, sizes):
"""Update parameters of the grid search.
Args:
param_grid: current grid search dictionary
sizes: dataset.shape
Returns:
param_grid: updated grid search dictionary
"""
if 'h_units' in param_grid.keys():
# NN and simple_linear data
if sizes[1] > 1:
... | bigcode/self-oss-instruct-sc2-concepts |
def polynomial_mul_polynomial(a, b):
"""
Multiplication function of two polynomials.
:param a: First polynomial.
:param b: Second polynomial.
:return: The result of multiplication two polynomials
"""
number_type = type(a[0]) if a else type(b[0]) if b else float
len_a, len_b = len(a), len... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_GSC_weights(weights_dict, rooted_tree):
"""
This is a novel (I believe) normalization scheme that I came up with to re-scale
GSC weights. It simply divides the weight for each terminal by the overall depth of that
terminal and therefore can/should(?) be thought of as a % independence.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_attribute(node_id, runtime_property, deployment_id, rest_client):
""" Get a runtime property for the first node instance of a node in
a deployment.
:param node_id: The ID of a node template in a deployment.
:type node_id: str
:param runtime_property: The key of a runtime property.
:type ... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def _HashFileHandle(fh):
"""sha1 of a file like object.
Arguments:
fh: file handle like object to hash.
Returns:
sha1 as a string.
"""
hasher = hashlib.sha1()
try:
while True:
data = fh.read(4096)
if not data:
break
hasher.update(data)
finally:
f... | bigcode/self-oss-instruct-sc2-concepts |
def aztec_tonalpohualli_name(date):
"""Return the name field of an Aztec tonalpohualli
date = [number, name]."""
return date[1] | bigcode/self-oss-instruct-sc2-concepts |
def _classify_rec(rec):
"""Determine class of variant in the record.
"""
if max([len(x) for x in rec.alleles]) == 1:
return "snp"
else:
return "indel" | bigcode/self-oss-instruct-sc2-concepts |
def is_last_best(name, history, min_delta):
"""Checks whether the last element is the best score so far
by taking into account an absolute improvement threshold min_delta."""
if len(history) == 1:
# If first validation, return True to save it
return True
new_value = history[-1]
# b... | bigcode/self-oss-instruct-sc2-concepts |
def leiaInt(msg='', dado='Número', f=False):
"""
Um input que só aceita e continua a execução caso receba um número inteiro
:param msg: Mensagem que será exibida antes de pedir o input
:param dado: o tipo de valor lido para personalizar a mensagem de erro - "[!] 'dado' inválido! Digite novamente."
... | bigcode/self-oss-instruct-sc2-concepts |
def discrete_distribution(data):
"""
Build a discrete distribution in form of { point : probability }
:param data: numpy.array, (data points, dimension)
:return: dict of distribution
"""
distr = { }
n = data.shape[0]
for point in data:
if tuple(point) in distr:
distr[... | bigcode/self-oss-instruct-sc2-concepts |
def get_filename(pathname, split_char='/'):
"""
:param pathname: path name
:param split_char: Path interval character
:return: file name
"""
pathname = pathname.split(split_char)
return pathname[-1] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def to_indexes(input_range: str) -> List[int]:
"""
Takes a string representing some indexes and returns a list of integers containing the indexes.
>>>
>>> to_indexes('2, 5-8, 21')
[2, 5, 6, 7, 8, 21]
>>>
:param input_range: str
:return: List[int]: A list contai... | bigcode/self-oss-instruct-sc2-concepts |
def version_tuple(v):
"""Creates a version tuple from a version string for consistent comparison of versions.
Conversion to tuples is needed because version '2.12.9' is higher then '2.7.8' however::
>>> '2.12.9' > '2.7.8'
False
Instead we need:
>>> version_tuple('2.12.9') > version_tuple('2.... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def read_1(stream):
""" read 1 byte from stream """
return struct.unpack('<B', stream.read(1))[0] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def collate_fn(data):
"""Pad the sequences.
This function will be used to pad the sessions to max length
in the batch and transpose the batch from
batch_size x max_seq_len to max_seq_len x batch_size.
It will return padded vectors, labels and lengths of each session (before padding)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_sphinx_build_command(project):
"""Builds the sphinx-build command using project properties.
"""
options = ["-b %s" % project.get_property("sphinx_builder"),
"-c %s" % project.expand_path(project.get_property("sphinx_config_path")),
project.expand_path(project.get_proper... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def collate_list(vec):
"""
If vec is a list of Tensors, it concatenates them all along the first dimension.
If vec is a list of lists, it joins these lists together, but does not attempt to
recursively collate. This allows each element of the list to be, e.g., its own dict.
If vec i... | bigcode/self-oss-instruct-sc2-concepts |
from textwrap import dedent
def build_brace_pattern(level, separators):
"""
Build a brace pattern upto a given depth
The brace pattern parses any pattern with round, square, curly, or angle
brackets. Inside those brackets, any characters are allowed.
The structure is quite simple and is recursiv... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def choose_n(total, sample_size):
"""Given a number of items N and a sample size S, returns all possible
unordered S-tuples of integers up to N."""
return list(itertools.combinations(range(1, total + 1), sample_size)) | bigcode/self-oss-instruct-sc2-concepts |
def decode_varint_py(buffer, pos=0):
""" Decode an integer from a varint presentation. See
https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints
on how those can be produced.
Arguments:
buffer (bytearry): buffer to read from.
pos (int): optional position... | bigcode/self-oss-instruct-sc2-concepts |
def expand_year(year):
"""Convert 2-digit year to 4-digit year."""
if year < 80:
return 2000 + year
else:
return 1900 + year | bigcode/self-oss-instruct-sc2-concepts |
def readList(infile,
column=0,
map_function=str,
map_category={},
with_title=False):
"""read a list of values from infile.
Arguments
---------
infile : File
File object to read from
columns : int
Column to take from the file.
map... | bigcode/self-oss-instruct-sc2-concepts |
def is_file_covered(file_cov):
"""Returns whether the file is covered."""
return file_cov['summary']['regions']['covered'] | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string(len: int) -> str:
""" Generate a _random string of desired length.
:param len: Desired character length for generated string.
:return: Generated _random string.
"""
alphanumeric_alphabet = ''.join([string.ascii_letters, string.digits])
generated_s... | bigcode/self-oss-instruct-sc2-concepts |
def is_multi_label(labels_list):
"""Whether labels list provided is a multi-label dataset.
Parameters
----------
labels_list : list
list of labels (integers) or multiple labels (lists of integers) or mixed
Returns
-------
True if multi-label
"""
return any([isinstance(l, li... | bigcode/self-oss-instruct-sc2-concepts |
def valid_operation(x: str) -> bool:
"""
Whether or not an opcode is valid
:param x: opcode
:return: whether or not the supplied opcode is valid
"""
return not x.startswith("__") and not x == "bytecode_format" | bigcode/self-oss-instruct-sc2-concepts |
import pwd
def parse_uid(uid):
"""Parse user id.
uid can be an interger (uid) or a string (username), if a username
the uid is taken from the password file.
"""
try:
return int(uid)
except ValueError:
if pwd:
return pwd.getpwnam(uid).pw_uid
raise | bigcode/self-oss-instruct-sc2-concepts |
def ngrams(iterable, n=1):
"""Generate ngrams from an iterable
l = range(5)
list(l) -> [0, 1, 2, 3, 4, 5]
list(ngrams(l, n=1)) -> [(0,), (1,), (2,), (3,), (4,)]
list(ngrams(l, n=2)) -> [(0, 1), (1, 2), (2, 3), (3, 4)]
list(ngrams(l, n=3)) -> [(0, 1, 2), (1, 2, 3), (2, 3, 4)]
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def counter(string):
"""
Calculate count of elements in string.
"""
result = [f'Count of {elem} = {string.count(elem)}\n'for elem in set(string)]
return "".join(result) | bigcode/self-oss-instruct-sc2-concepts |
def try_key(dictionary, key, default):
"""
Try to get the value at dict[key]
:param dictionary: A Python dict
:param key: A key
:param default: The value to return if the key doesn't exist
:return: Either dictionary[key] or default if it doesn't exist.
"""
try:
return dictionary[... | bigcode/self-oss-instruct-sc2-concepts |
def generate_coordinate_rect(x_start, x_finish, y_start, y_finish):
"""
Generate tuples for coordinates in rectangle (x_start, x_finish) -> (y_start, y_finish)
"""
coords = []
for i in range(x_start, x_finish):
for j in range(y_start, y_finish):
coords.append((i, j))
return c... | bigcode/self-oss-instruct-sc2-concepts |
def detect_cycle(head):
"""
Question 8.4: Detect a cycle in a singly-linked list.
Return None if there is no cycle.
If there is, return the first node in the cycle.
"""
slow = head
fast = head
cycle_length = 0
while fast and fast.next and fast.next.next:
slow = slow.next
... | bigcode/self-oss-instruct-sc2-concepts |
def stdDevOfLengths(L):
"""
L: a list of strings
returns: float, the standard deviation of the lengths of the strings,
or NaN if L is empty.
"""
if (len(L) == 0):
return float('NaN')
# compute mean first
sumVals = 0
for s in L:
sumVals += len(s)
meanV... | bigcode/self-oss-instruct-sc2-concepts |
def get_add_llil(src):
"""
Returns llil to add
:param src: source of operation
:return: generator for llil expression for add
"""
def add_llil(il, instr):
return il.set_reg(4, 'a', il.add(4, il.reg(4, 'a'), src(il, instr)))
return add_llil | bigcode/self-oss-instruct-sc2-concepts |
import json
def ReportJson(build_statuses):
"""Generate the json description of a given build.
Args:
build_statuses: List of build_status dict's from FetchBuildStatus.
Returns:
str to display as the final report.
"""
report = {}
for build_status in build_statuses:
report[build_status['build... | bigcode/self-oss-instruct-sc2-concepts |
def get_static_data(modelSpec):
"""
Return a dictionary of static values that all objects of this model
have.
This applies only to kubernetes resources where ``kind`` and
``apiVersion`` are statically determined by the resource. See the
`Kubernetes OpenAPI Spec Readme`__.
For example for a... | bigcode/self-oss-instruct-sc2-concepts |
def usernameslist(data):
"""
Returns list of usernames of all users.
"""
return [u['name'] for u in data['users']] | bigcode/self-oss-instruct-sc2-concepts |
import math
def distATT(x1,y1,x2,y2):
"""Compute the ATT distance between two points (see TSPLIB documentation)"""
xd = x2 - x1
yd = y2 - y1
rij = math.sqrt((xd*xd + yd*yd) /10.)
tij = int(rij + .5)
if tij < rij:
return tij + 1
else:
return tij | bigcode/self-oss-instruct-sc2-concepts |
import time
def gen_filename(sample, dist, temp):
"""
Function to generate the string to use as the filename of the
output file. The information contained in the filename are hardcoded
to match our requirements, but can be easily changed.
Parameters
----------
sample: str
Str... | bigcode/self-oss-instruct-sc2-concepts |
import random
def roll(sides):
""" Roll a (sides) sided die and return the value. 1 <= N <= sides """
return random.randint(1,sides) | bigcode/self-oss-instruct-sc2-concepts |
import re
def splitCIGAR(SAM_CIGAR):
"""
Split CIGAR string into list of tuples with format (len,operator)
"""
CIGARlist = list()
for x in re.findall('[0-9]*[A-Z|=]',SAM_CIGAR):
CIGARlist.append((int(re.findall('[0-9]*', x)[0]),re.findall('[A-Z]|=', x)[0]))
#174M76S --> [(174,M),(76,S)... | bigcode/self-oss-instruct-sc2-concepts |
def actionToGcdType(actionType) :
"""Returns the gcdType matching a given actionType
"""
if actionType == 'gcdSkill':
return 'global'
elif actionType == 'instantSkill':
return 'instant' | bigcode/self-oss-instruct-sc2-concepts |
import math
def radians_to_degrees(radians):
"""Convert radians to degrees."""
return 180.0 * radians / math.pi | bigcode/self-oss-instruct-sc2-concepts |
def ask(prompt, type_=None, min_=None, max_=None, range_=None):
"""Get user input of a certain type, with range and min/max options."""
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
... | bigcode/self-oss-instruct-sc2-concepts |
def form_metaquast_cmd_list(metaquast_fp, outdir, input_fasta):
"""format argument received to generate list to be used for metquast subprocess call
Args:
metaquast_fp(str): the string representing the path to metaquast executable
outdir(str): the string representing the path to the output dire... | bigcode/self-oss-instruct-sc2-concepts |
def robots(environ):
"""Returns robots.txt"""
status = "200 OK"
responseHeaders = [("Content-type", "text/plain")]
with open("robots.txt", "r") as f:
output = f.read()
return status, responseHeaders, output | bigcode/self-oss-instruct-sc2-concepts |
def train(data, length=50):
"""Return average of last n data samples.
Args:
data (np.ndarray): Time series data
length (int, optional): Length of used window (last n values). Defaults to 50.
"""
return data.ravel()[-length:].mean() | bigcode/self-oss-instruct-sc2-concepts |
def find_location(index, SIZE):
"""
Finds the x and y coordinates in a square grid of SIZE**2 given an index.
It is assumed that we are counting from left to right on a set of rows top-down, and that area is square.
Rows and columns start from 0 given Python indexing conventions.
e.g.
0... | bigcode/self-oss-instruct-sc2-concepts |
def extract_golden_standard(path_to_standard):
"""
Extracts the golden standard associations into a dict
:param path_to_standard: str, path to the golden standard associations
:return: list<(word<str>, meaning<str>)> tuples
"""
lexicon = set()
with open(path_to_standard) as f:
for l... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(filename):
"""
Opens the file, reads the data, closes it and turns it into a dictionary.
Parameters
----------
filename : string
The filename of a JSON file to be opened and read.
Returns
-------
Dictionary
The JSON data in the file as a Pyt... | bigcode/self-oss-instruct-sc2-concepts |
def empty_units(number: int, from_unit: int) -> int:
"""
Puts zeros on all digits from the from_unit
num being 152 and from_unit being 1 gives 100
"""
mask: int = int(10 ** (from_unit + 1))
return number - (number % mask) | bigcode/self-oss-instruct-sc2-concepts |
def subtract(a, b):
"""
Returns the result of subtracting b from a
>>> subtract(2, 1)
1
>>> subtract(10, 10)
0
>>> subtract(7, 10)
-3
"""
return a - b | bigcode/self-oss-instruct-sc2-concepts |
def to_celsius(temp):
"""Converts temperature in Kelvin to Celsius"""
temp_in_c = round(temp-273.15)
return temp_in_c | bigcode/self-oss-instruct-sc2-concepts |
import torch
def logistic_rsample(mu_ls):
"""
Returns a sample from Logistic with specified mean and log scale.
:param mu_ls: a tensor containing mean and log scale along dim=1,
or a tuple (mean, log scale)
:return: a reparameterized sample with the same size as the input
mean ... | bigcode/self-oss-instruct-sc2-concepts |
def make_record(type_name, attributes, defaults=None):
"""Factory for mutable record classes.
A record acts just like a collections.namedtuple except slots are writable.
One exception is that record classes are not equivalent to tuples or other
record classes of the same length.
Note, each call to `make_rec... | bigcode/self-oss-instruct-sc2-concepts |
def n_max_matchings(A, B):
"""
Compute the number of maximum matchings in a complete bipartite graph on A + B vertices.
A and B are required to be nonnegative.
Corner Case: If at least one of the sides has zero vertices, there is one maximal matching: the empty set.
"""
a = min(A, B)
b = max... | bigcode/self-oss-instruct-sc2-concepts |
def generate_product_instance_id(vm_fqn, product_name, product_version):
"""
Method to generate instance id for installed products (product instances)
:param vm_fqn: FQN (where product has been installed)
:param product_name: Product name (instance)
:param product_version: Product release (instance)... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_gldas_start_date(product):
"""
Get NOAH GLDAS start date.
Parameters
----------
product : str
Product name.
Returns
-------
start_date : datetime
Start date of NOAH GLDAS product.
"""
dt_dict = {
"GLDAS_Noah_v20_02... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def adjacent_digits(n: int, digits: str) -> List[str]:
"""List of all adjacent digits of `n` length in `digits`."""
adjacents = []
while len(digits) >= n:
adjacents.append(digits[:n])
digits = digits[1:]
return adjacents | bigcode/self-oss-instruct-sc2-concepts |
def descriptor_target_split(file):
"""
Split the input data into descriptors and target DataFrames
Parameters:
file: pandas.DataFrame
Input DataFrame containing descriptors and target data.
Returns:
descriptors: pandas.DataFrame
Descriptors... | bigcode/self-oss-instruct-sc2-concepts |
import codecs
import json
def dump(data, handle, **kwargs):
"""Serialize ``data`` as a JSON formatted stream to ``handle``.
We use ``ensure_ascii=False`` to write unicode characters specifically as this improves the readability of the json
and reduces the file size.
"""
try:
if 'b' in han... | bigcode/self-oss-instruct-sc2-concepts |
def format_file_size(size):
"""according file size return human format
Arguments:
size {int} -- file size
Returns:
str -- human format file size
"""
if size < 1024:
return '%i' % size + 'B'
if 1024 <= size < 1024 ** 2:
return '%.1f' % float(size / 1024) + 'K'
... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.