seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
async def readyz():
"""
Readyz endpoint.
"""
return {"status": "ready"} | bigcode/self-oss-instruct-sc2-concepts |
def IoU(boxA, boxB):
"""
Computes the Intersection over Union (IoU) metric, given
two bounding boxes.
Input:
"boxA": bounding box A
"boxB": bounding box B
Output:
"score": IoU score
"""
# Compute the intersection points of the two BBs
xLeft = max(boxA[0], boxB[0])
yLeft ... | bigcode/self-oss-instruct-sc2-concepts |
def is_transition(allele1, allele2):
"""Is the pair of single bp alleles a transition?
Args:
allele1: A string of the first allele, must be 1 bp in length.
allele2: A string of the second allele, must be 1 bp in length.
Returns:
True if allele1/allele2 are a transition SNP.
Raises:
ValueError... | bigcode/self-oss-instruct-sc2-concepts |
def example_choices(field, arg=3):
"""
Returns a number (default: 3) of example choices for a ChoiceFiled (useful for CSV import forms).
"""
examples = []
if hasattr(field, 'queryset'):
choices = [(obj.pk, getattr(obj, field.to_field_name)) for obj in field.queryset[:arg + 1]]
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def f1(x):
"""
A simple quadratic function.
"""
y = x**2 - 3.*x + 5.
return y | bigcode/self-oss-instruct-sc2-concepts |
def arithmetic_sum_n(a_1, d, n):
"""Calculate the sum of an arithmetic series.
Parameters:
a_1 The first element of the series
d The difference between elements
n The number of elements in the series to sum
Return:
The sum of n numbers in the arithmetic seri... | bigcode/self-oss-instruct-sc2-concepts |
def apply_text_replacements(path, text, text_replacements):
"""
If path appears in text_replacements, replace each old value with new value in order.
"""
if path in text_replacements:
for old_val, new_val in text_replacements[path]:
text = text.replace(old_val, new_val)
retur... | bigcode/self-oss-instruct-sc2-concepts |
import re
def humanish(remote_url):
"""Get the humanish part of a remote git url
equivalent of the following multiexpression sed search and replace:
sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g'
https://stackoverflow.com/questions/13839879/how-to-determine-the-humanish-part-of-a-git-repos... | bigcode/self-oss-instruct-sc2-concepts |
def is_shared_to(video: dict) -> bool:
"""
Checks if a video was shared to an account.
Returns True if it was shared to another account, False otherwise.
"""
shared = video.get('sharing')
if shared and shared.get('to_external_acct'):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def input_data_task_id(conf):
# type: (dict) -> str
"""Retrieve input data task id
:param dict conf: configuration object
:rtype: str
:return: task id
"""
return conf['task_id'] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import List
def listify(collection: Any) -> List:
"""
Takes a given collection and returns a list of the elements, handling strings correctly
Parameters
----------
collection: tuple, set, str
Any type of collection or string
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_strides(
strides
):
"""Normalize strides of the same format.
Args:
strides: An integer or pair of integers.
Returns:
A pair of integers.
Raises:
ValueError: Input strides is neither an integer nor a pair of integers.
"""
if isinstance(strides, (list, tuple)) and len(strides)... | bigcode/self-oss-instruct-sc2-concepts |
def realign_shifted_streams(tokens, durations, F0s, shifts):
"""
Durations are shifted by 1, F0 by 2
>>> tokens = ["<s>", "t1", "t2", "t3", "</s>", "x", "x"]
>>> durations = ["<0>", "<0>", "d1", "d2", "d3", "<0>", "x"]
>>> F0s = ["<0>", "<0>", "<0>", "f1", "f2", "f3", "<0>"]
>>> shifts = [1,... | bigcode/self-oss-instruct-sc2-concepts |
def ssv(words):
"""Convert a words list into space separated values"""
line = ""
for w in words:
if len(line) != 0:
line += ' '
line += w
return line | bigcode/self-oss-instruct-sc2-concepts |
def get_region_filename(region, subregion):
"""Returns the filename needed to download/manage PBF files.
Parameters
----------------------
region : str
subregion : str
Returns
----------------------
filename : str
"""
base_name = '{}-latest.osm.pbf'
if subregion is None:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def is_aromatic(n: str, d: Dict[str, Any]) -> bool:
"""Adds indicator of aromaticity of the atom to the node data.
:param n: Node name, this is unused and only included for compatibility with the other functions.
:type n: str
:param d: Node data
:typ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def get_data_types(data):
"""
returns a dictionary with column names and their respective data types
:param pandas.DataFrame data: a dataframe
:rtype: dict[str,str]
"""
dtypes = data.dtypes
return OrderedDict(zip(dtypes.index, dtypes.astype(str))) | bigcode/self-oss-instruct-sc2-concepts |
def _bool_to_str(val):
"""
Convert Python bool to string 'true' or 'false'.
Note we cannot use the standard conversion to str, as Python uses 'True'
and 'False', whereas C++ uses 'true' and 'false'.
"""
return 'true' if val else 'false' | bigcode/self-oss-instruct-sc2-concepts |
import time
def timestamp2date(timestamp):
"""
时间戳转换为日期
Parameters
----------
timestamp: int or str
用户账号
Returns
-------
datetime:
转换好的日期:年-月-日 时:分:秒
"""
time_array = time.localtime(int(timestamp))
datetime = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
... | bigcode/self-oss-instruct-sc2-concepts |
def __data_to_string(write_data):
""" Converts data array to string."""
return "".join(["{:08b}".format(data) for data in write_data]) | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def open_enc(fn, utf16):
"""
Open a file for reading with either the standard built-in open() or the
open in the codecs module for reading UTF-16 encoded files.
:param fn: Name of the file to open
:param utf16: Boolean flag to specify a UTF-16 file
"""
if utf16:
retu... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def account_exists(account_id='jodel_account'):
"""Checks whether an account has already been created."""
if Path('./' + account_id + '.pkl').is_file():
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import zlib
def crc32File(filename, skip=0):
"""Computes the CRC-32 of the contents of filename, optionally
skipping a certain number of bytes at the beginning of the file.
"""
with open(filename, 'rb') as stream:
discard = stream.read(skip)
return zlib.crc32(stream.read()) & 0xfffffff... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_package_name(name):
""" Sanitize package name
Args:
name (str): package name.
Returns:
str: sanitized package name.
"""
return name.replace("+", "plus").strip(" ") | bigcode/self-oss-instruct-sc2-concepts |
def json_get(item, path, default=None):
"""
Return the path of the field in a dict.
Arguments:
item (dict): The object where we want to put a field.
path (unicode): The path separated with dots to the field.
default: default value if path not found.
Return:
The value.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def common_words(sentence1: List[str], sentence2: List[str]) -> List[str]:
"""
Input: Two sentences - each is a list of words in case insensitive ways.
Output: those common words appearing in both sentences. Capital and lowercase
words are treated as the same word.
... | bigcode/self-oss-instruct-sc2-concepts |
def lng180(lng):
"""Returns a longitude in degrees between {-180, 180] given a longitude in degrees."""
newlng = float(lng)
if lng <= -180:
return lng + 360
if newlng > 180:
return lng - 360
return lng | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _calc_elapsed(start, fmt=True):
"""Returns hours, minutes, seconds;
formats to {H}h, {m} min., {s}s if fmt"""
elapsed = datetime.now() - start
hours, remainder = divmod(elapsed.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
if fmt:
... | bigcode/self-oss-instruct-sc2-concepts |
def divide_by(value, arg):
"""
Returns the result of the division of value with arg.
"""
result = 0
try:
result = value / arg
except:
# error in division
pass
return result | bigcode/self-oss-instruct-sc2-concepts |
def dropout_mask(x, sz, dropout):
""" Applies a dropout mask whose size is determined by passed argument 'sz'.
Args:
x (nn.Variable): A torch Variable object
sz (tuple(int, int, int)): The expected size of the new tensor
dropout (float): The dropout fraction to apply
This method use... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def nms(boxes, scores, overlap=0.7):
"""Apply non-maximum suppression at test time to avoid detecting too many
overlapping bounding boxes for a given object.
Args:
scores: (N) FloatTensor
boxes: (N, 4) FloatTensor
overlap: (float) The overlap thresh for suppressing unn... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_generator(obj):
"""
Return True if ``obj`` is a generator
"""
return inspect.isgeneratorfunction(obj) or inspect.isgenerator(obj) | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def decode_text_part(part):
"""Extract the payload from a text/plain mime part as a unicode string"""
txt = part.get_payload(decode=True)
charset = part.get_content_charset('latin1')
# Make sure the charset is supported and fallback to 'ascii' if not
try:
codecs.lookup(charse... | bigcode/self-oss-instruct-sc2-concepts |
def calcite(piezometer=None):
""" Data base for calcite piezometers. It returns the material parameter,
the exponent parameter and a warn with the "average" grain size measure to be use.
Parameter
---------
piezometer : string or None
the piezometric relation
References
----------
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _without_nbt_style(s: str) -> str:
"""
Given a full string with NBT styling, return the string without coloring
and recomb symbols.
:param s: The given string.
:return: The given string without NBT styling.
"""
return re.sub('§ka|§.', '', s).strip() | bigcode/self-oss-instruct-sc2-concepts |
import random
def randbytes(length: int) -> bytes:
"""
Generate a random bytes object.
:param length: Length of the random bytes object.
:return: Random bytes object.
"""
return bytes(random.getrandbits(8) for _ in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def MoveStr2List(mv: str) -> list:
"""
param:
mv: str [x_src, y_src, x_dst, y_dst]
return:
mv_list: List-> [int: x_src, y_src, x_dst, y_dst]
"""
mv_list = []
if mv != " ":
mv_list = list(map(int, mv[1:-1].split(",")))
return mv_list | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def sorted_glob(p: Path, pattern="*"):
"""
return sorted filenames for matched files.
"""
names = [x.name for x in p.glob(pattern)]
names.sort()
return names | bigcode/self-oss-instruct-sc2-concepts |
import torch
def generate_linear_data(n=1000):
"""
Generates an example dataset that can be seperated linearly
Output:
inputs : nx2 dimension FloatTensor
targets : nx1 dimension LongTensor with range [0,1]
"""
torch.manual_seed(123)
inputs = torch.rand(n,2)
targets = torch.s... | bigcode/self-oss-instruct-sc2-concepts |
def nonstandard(cls):
"""
Testcase decorator that marks the test as being non-standard.
These tests are not automatically added to the "standard" group.
"""
cls._nonstandard = True
return cls | bigcode/self-oss-instruct-sc2-concepts |
import torch
def quadratic_bezier(params: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
"""Evaluate a batch of quadratic bezier curves at different points.
Args:
params: torch.Tensor of size [batch, 3, D]. Each batch item is interpreted as four points corresponding to
the start point, the fir... | bigcode/self-oss-instruct-sc2-concepts |
def OR_AND_product_fuzzy(Z_n, U_d):
"""
Compute probability of emitting a zero for fuzzy vectors under OR-AND logic.
"""
out = 1
for l in range(Z_n.shape[0]):
out *= 1 - Z_n[l] * U_d[l]
return 1 - out | bigcode/self-oss-instruct-sc2-concepts |
def get_log_params(prog: str, cfg: dict, def_logfile: str) -> tuple:
"""Get the log file, level and size for the given program from config
The logfile is supposed to be defined by a variable called logfile
within the hierarchy of the config dictionary. Thus, the poller log file
will be {'poller': {'log... | bigcode/self-oss-instruct-sc2-concepts |
def has_view_restrictions(page):
"""Returns True if the page has view restrictions set up, False
otherwise."""
return page.view_restrictions.count() > 0 | bigcode/self-oss-instruct-sc2-concepts |
def drop_prefix(s, pattern):
"""
Remove prefix pattern of a string.
:param s: string
:param pattern: string pattern
"""
if s.startswith(pattern):
return s[len(pattern):]
return s | bigcode/self-oss-instruct-sc2-concepts |
def getAPNTopicFromX509(x509):
"""
Given an L{X509} certificate, extract the UID value portion of the
subject, which in this context is used for the associated APN topic.
@param x509: the certificate
@type x509: L{X509}
@return: C{str} topic, or empty string if value is not found
"""
s... | bigcode/self-oss-instruct-sc2-concepts |
def dec2hp(dec):
"""
Converts Decimal Degrees to HP Notation (float)
:param dec: Decimal Degrees
:type dec: float
:return: HP Notation (DDD.MMSSSS)
:rtype: float
"""
minute, second = divmod(abs(dec) * 3600, 60)
degree, minute = divmod(minute, 60)
hp = degree + (minute / 100) + (s... | bigcode/self-oss-instruct-sc2-concepts |
def mean_normalization(x):
"""
This script is to do mean normalization for DataFrame
Parameter:
x: format: DataFrame
rows:feature
columns:samples
Returns:
output:DataFrame; after mean normalization.
rows:feature
columns:samples
"""
for ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def camel_to_underscore(camelcase):
"""
Convert a camelcased string to underscore_delimited (tweaked from this StackOverflow answer)
http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case
"""
s1 = re.sub('(^/_)([A-Z][a-z]+)', r'\1_\2', camel... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def prepare_device(numberOfGpusToBeUsed):
"""
Function to setup GPU device if available.
The function gets the indices of the GPU devices that are used for DataParallel.
Parameters
----------
numberOfGpusToBeUsed : int
Number of GPUs to be used
... | bigcode/self-oss-instruct-sc2-concepts |
def handles_url( url ):
"""
Does this storage driver handle this kind of URL?
"""
return ".s3.amazonaws.com" in url | bigcode/self-oss-instruct-sc2-concepts |
def after(node, values, positions, places=False):
"""
Returns the set of all nodes that are after the given node.
"""
n = node[positions["_n"]]
if places is not False:
try:
return [values[n + places]]
except IndexError:
return list()
sent_len = node[posit... | bigcode/self-oss-instruct-sc2-concepts |
def remove_empty(dictionary):
"""Removes empty entries from a dictionary."""
for key in list(dictionary.keys()):
if dictionary.get(key) is None:
del dictionary[key]
return dictionary | bigcode/self-oss-instruct-sc2-concepts |
import torch
def div_func(inputs: torch.Tensor, other: float, unsqueeze_dim: int = 1):
"""
Overview:
Divide ``inputs`` by ``other`` and unsqueeze if needed.
Arguments:
- inputs (:obj:`torch.Tensor`): the value to be unsqueezed and divided
- other (:obj:`float`): input would be divi... | bigcode/self-oss-instruct-sc2-concepts |
def parse_namefile_ini(line):
"""
Parse a line from a .ini file to get the described file location
Parameters
----------
line : str
Line from the .ini file, containing the location of a file
of interest.
Returns
-------
processed_line : str
... | bigcode/self-oss-instruct-sc2-concepts |
def normalize(vals):
"""normalize a series of values using min/max normalization"""
return (vals-vals.min())/(vals.max()-vals.min()) | bigcode/self-oss-instruct-sc2-concepts |
def prepare_args(args):
"""
Prepare arguments to be used as the API expects it
:param args: demisto args
:return: transformed args
"""
args = dict((k.replace("-", "_"), v) for k, v in list(args.items()))
if "is_public" in args:
args["is_public"] = args["is_public"] == "True"
retu... | bigcode/self-oss-instruct-sc2-concepts |
def centre(images):
"""Mapping from {0, 1, ..., 255} to {-1, -1 + 1/127.5, ..., 1}."""
return images / 127.5 - 1 | bigcode/self-oss-instruct-sc2-concepts |
def bounce_easeout(pos):
"""
Easing function for animations: Bounce Ease Out
"""
if pos < 4 / 11.0:
return (121 * pos * pos) / 16.0
if pos < 8 / 11.0:
return (363 / 40.0 * pos * pos) - (99 / 10.0 * pos) + (17 / 5.0)
if pos < 9 / 10.0:
return (4356 / 361.0 * pos * pos) - (... | bigcode/self-oss-instruct-sc2-concepts |
def filter_traceback_list(tl):
"""
Returns the subset of `tl` that originates in creator-written files, as
opposed to those portions that come from Ren'Py itself.
"""
rv = [ ]
for t in tl:
filename = t[0]
if filename.endswith(".rpy") and not filename.replace("\\", "/").startswi... | bigcode/self-oss-instruct-sc2-concepts |
def poly_eval_horner(coefs, x):
"""
Evaluates the polynomial whose coefficients are given in coefs on the value x
using the Horner's method. This function is much faster than regular polynomial evaluation.
Polynomial coefficient are stored in coefs from the lowest power to the highest.
x is required... | bigcode/self-oss-instruct-sc2-concepts |
def serialize_results(results : dict) -> str:
"""Serialize a results dict into something usable in markdown."""
n_first_col = 20
ans = []
for k, v in results.items():
s = k + " "*(n_first_col-len(k))
s = s + f"| {v[0]*100:.1f} | {v[1]*100:.1f} |"
ans.append(s)
return "\n".j... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
import base64
def decode(something):
"""
Decodes from base-64 pickled object.
"""
return pickle.loads(base64.b64decode(something)) | bigcode/self-oss-instruct-sc2-concepts |
def retreive_filename(path):
"""
Truncates absolute file directory and returns file name.
Parameters
----------
path : 1-dimensional string containing absolute directory of a file,
in /<dir>/<filename>.<foramt> format.
Returns
-------
filename : <filename> portion of the given file... | bigcode/self-oss-instruct-sc2-concepts |
def is_density_matrix(input):
"""Determine if the input array can be a density matrix.
Args:
input (array): input array.
Returns:
bool: whether input can be a density matrix.
"""
return input.shape[-1] == 2 and input.shape[-2] == 2 | bigcode/self-oss-instruct-sc2-concepts |
import bz2
import pickle
def read_pickle(filepath, compressed=False):
""" Reads the summarized background from a compressed binary file
Parameters
----------
filepath:
Filepath to compressed file
compressed:
Whether to use bz2 compression. Defaults to False
"""
if compress... | bigcode/self-oss-instruct-sc2-concepts |
def test_step(x, model, estimator, **config):
"""Test the `model` given the mini-batch of observations `x` and the gradient estimator/evaluator `estimator`"""
loss, diagnostics, output = estimator(model, x, backward=False, **config)
return diagnostics | bigcode/self-oss-instruct-sc2-concepts |
def get_task_version(taskf):
"""return a version for a taskf.
This is wrapper around taskf.get_version() that will not raise
an exception if a tool is not installed but will return None
instead.
"""
try:
version = taskf().get_version()
except Exception as ex:
msg = str(ex)
... | bigcode/self-oss-instruct-sc2-concepts |
def as_bool(x):
"""
Returns True if the given string in lowercase equals "true",
False otherwise.
"""
return True if x.lower() == "true" else False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
import re
import operator
def condition_matches(value: Union[int, float], format_: str) -> bool:
"""
Return true if the value matches the condition in the pattern.
"""
match = re.search(r"\[(>|>=|<|<=|=)(\d*(?:\.\d*)?)\]", format_)
if not match:
return True
op... | bigcode/self-oss-instruct-sc2-concepts |
def wrap(text, width):
"""
A word-wrap function that preserves existing line breaks. Expects that
existing line breaks are posix newlines.
Preserve all white space except added line breaks consume the space on
which they break the line.
Don't wrap long words, thus the output text may have line... | bigcode/self-oss-instruct-sc2-concepts |
def task2(a):
"""
Function that calculates square value of argument
Input: one integer
Output: one integer
"""
return a**2
#return iloczyn | bigcode/self-oss-instruct-sc2-concepts |
def bucopt(self, method="", nmode="", shift="", ldmulte="", rangekey="",
**kwargs):
"""Specifies buckling analysis options.
APDL Command: BUCOPT
Parameters
----------
method
Mode extraction method to be used for the buckling analysis:
LANB - Block Lanczos
SUBSP... | bigcode/self-oss-instruct-sc2-concepts |
def getNthFromLast(head, n):
"""
Take two pointers one starting from head the other starting from the nth
node, so when the latter node reaches the end the former would have reached
the Lenth-n nodes
"""
ptr = head
c = 0
while ptr and c < n:
# We want the nptr to reach the l... | bigcode/self-oss-instruct-sc2-concepts |
def compareNodes(node_1, node_2):
"""
Compares two nodes to check if they are equal
:param node_1: The first node to check
:type node_1: Node type
:param node_2: The second node to check
:type node_2: Node type
:returns: True or False
:rtype: Boo... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def now() -> datetime:
"""Return the datetime object of the current time.
:return: datetime object represeting current time
"""
return datetime.now().astimezone() | bigcode/self-oss-instruct-sc2-concepts |
def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return '' | bigcode/self-oss-instruct-sc2-concepts |
def correct_time_dilation(df):
"""Short summary.
Parameters
----------
df : Pandas DataFrame
The dataframe containing the photometry of all events.
Returns
-------
Pandas DataFrame
The same dataframe with undilated times.
"""
for idx, row in df.iterrows():
... | bigcode/self-oss-instruct-sc2-concepts |
def _GetLowerBoundBuildNumber(
lower_bound_build_number,
upper_bound_build_number,
# The default window is the number of builds
# Findit will look back for an analysis.
default_build_number_window_size=500):
"""Determines the lowest bound build number relative to an upper bound.
Args:
lower... | bigcode/self-oss-instruct-sc2-concepts |
def get_related_fields(model):
"""
Returns all the fields of `model` that hold the link between referencing objects
and the referenced object (`model`).
:param model: orphaned model class
:returns: list of fields of `model` that hold references via dependent objects
"""
return [
f f... | bigcode/self-oss-instruct-sc2-concepts |
def weekend_integration_1_SS_idx_rule(M):
"""
The index for type 1 weekend-tour type integration constraints is
(day, week, window, tour type).
:param M: Model
:return: Constraint index rule
"""
return [(j, w, i, t) for j in M.DAYS
for w in M.WEEKS
for i in M.WINDOW... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_config(filename: str) -> dict:
"""
Load a configuration file as YAML
"""
with open(filename) as fh:
config = yaml.safe_load(fh)
return config | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Tuple
def normalize_sizes(y_pred: torch.Tensor, y_true: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Normalize tensor sizes
Args:
y_pred (torch.Tensor): the output of the model
If a 3-dimensional tensor, reshapes to a matrix
y_true (torch.... | bigcode/self-oss-instruct-sc2-concepts |
import math
def cos_anneal(e0, e1, t0, t1, e):
""" ramp from (e0, t0) -> (e1, t1) through a cosine schedule based on e \in [e0, e1] """
alpha = max(0, min(1, (e - e0) / (e1 - e0))) # what fraction of the way through are we
alpha = 1.0 - math.cos(alpha * math.pi/2) # warp through cosine
t = alpha * t1 ... | bigcode/self-oss-instruct-sc2-concepts |
def aggregate_actions_and_lengths(actions_per_frame):
"""Identify the actions in a video and count how many frames they last for.
Given a list of actions (e.g. ['a', 'a', 'a', 'b', 'b']) summarise the actions and count their lifespan. For
the example input just given, the function returns (['a', 'b'], [3, ... | bigcode/self-oss-instruct-sc2-concepts |
def get_name_from_attributes(variant):
"""Generates ProductVariant's name based on its attributes."""
values = [
attributechoice_value.title
for attributechoice_value in variant.attribute_map.values()
]
return " / ".join(values) | bigcode/self-oss-instruct-sc2-concepts |
import operator
import pkgutil
def _get_modules_names(package):
"""Get names of modules in package"""
return sorted(
map(operator.itemgetter(1),
pkgutil.walk_packages(package.__path__,
'{0}.'.format(package.__name__)))) | bigcode/self-oss-instruct-sc2-concepts |
def insert_sort(input_list):
"""Insert sort function."""
if isinstance(input_list, list):
for i in range(len(input_list) - 1):
for j in range(i + 1, 0, -1):
if input_list[j] < input_list[j - 1]:
temp = input_list[j]
input_list[j] = inpu... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
from operator import add
def fitness(individual, target):
"""
Calculutes the fitness of an individual, lower is better
:param individual: individual to calculate fitness
:param target: the target value to achieve
"""
result = reduce(add, individual, 0)
return a... | bigcode/self-oss-instruct-sc2-concepts |
def transform_to_bool(value):
"""
Transforms a certain set of values to True or False.
True can be represented by '1', 'True' and 'true.'
False can be represented by '1', 'False' and 'false.'
Any other representation will be rejected.
"""
if value in ['1', 'true', 'True']:
return Tr... | bigcode/self-oss-instruct-sc2-concepts |
import json
def _get_options(options_file=None):
""" Read in options_file as JSON.
:param options_file: filename to return
:type options_file: str
:return: options as dictionary
:rtype: dict
"""
if options_file is not None:
with open(options_file, 'r') as opt_fil... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_jsonp_callback(callback):
""" Returns JSONP callback function name or None.
Callback function names can contain alphanumeric characters as well
as periods (.) and brackets ([ and ]), allowing names like "one.two[3]".
"""
callback = re.sub('[^a-zA-Z0-9\._\[\]]', '', callback)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_bowtie2_index_files(base_index_name):
""" This function returns a list of all of the files necessary for a Bowtie2 index
that was created with the given base_index_name.
Args:
base_index_name (string): the path and base name used to create the bowtie2 index
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def order_heuristic(mgr, var_priority = None):
"""
Most signifiant bits are ordered first in BDD.
var_priority is a list of variable names. Resolves ties if two bits, are of the same priority, it resolves based.
e.g. var_priority = ['x','y','z'] would impose an order ['x_0', 'y_0', 'z_0']
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def scale(n, float_round=None):
"""
High-order function to scale result to arbitrary value.
f = scale(10)
f(5) -> 50
if float_round
f = scale(0.1, 2)
f(10) -> 10.2
:param n: Scaling factor
:param float_round: Number of decimal places
:return: Callable, performing scaling
:r... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def create_readable_data(data: List[int]) -> List[list]:
"""Create a program readable sudoku puzzle given a list of numbers
=== Attributes ===
data: a list of numbers containing sudoku puzzle
=== Returns ===
a readable sudoku puzzle
"""
result = [[data[col + 9 * r... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
from typing import Callable
from typing import Set
def dagroots(sorted_nodes:List[Any],
inbounds:Callable[[Any],Set[Any]])->Set[Any]:
""" Return a set of root nodes of a DAG. DAG should be topologically sorted.
"""
nonroots=set()
acc=set()
for node... | bigcode/self-oss-instruct-sc2-concepts |
def convert_numeric_list(str_list):
"""
try to convert list of string to list of integer(preferred) or float
:param str_list: list of string
:return: list of integer or float or string
"""
assert isinstance(str_list, list)
if not str_list:
return str_list
try:
return l... | bigcode/self-oss-instruct-sc2-concepts |
def hashstring(s):
"""Compute a string hash based on the function "djb2".
Use at most 64 characters.
"""
h = 5381
s = s[0:64]
for c in s:
h = ((h << 5) + h + ord(c)) & 0xffffffff
return h | bigcode/self-oss-instruct-sc2-concepts |
def get_programming_language(repo_info):
"""Return programming language used for repository"""
try:
return repo_info.find('span', {'itemprop': 'programmingLanguage'}).text.strip()
except AttributeError:
return | 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.