seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def mscb(t):
"""
Find the index of the most significant change bit,
the bit that will change when t is incremented
aka the power of 2 boundary we are at
>>> mscb(0)
0
>>> mscb(1)
1
>>> mscb(7)
3
>>> mscb(8)
0
"""
return (t^(t+1)).bit_length()-1 | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import re
def get_terms(tickers: List[str]) -> List[str]:
"""Map tickers to bond terms, e.g. Brazil 5Y -> 5Y"""
return re.findall(r"\d+[MYmy]", "|".join(tickers)) | bigcode/self-oss-instruct-sc2-concepts |
def format_percent(n, baseline):
"""Format a ratio as a percentage (showing two decimal places).
Returns a string.
Accepts baseline zero and returns '??' or '--'.
"""
if baseline == 0:
if n == 0:
return "--"
else:
return "??"
return "%.2f%%" % (100 * n ... | bigcode/self-oss-instruct-sc2-concepts |
def _gendesc(infiles):
"""
Generate a desc entity value.
Examples
--------
>>> _gendesc("f")
'coeff'
>>> _gendesc(list("ab"))
['coeff0', 'coeff1']
"""
if isinstance(infiles, (str, bytes)):
infiles = [infiles]
if len(infiles) == 1:
return "coeff"
retur... | bigcode/self-oss-instruct-sc2-concepts |
def _get_arguments(*args):
"""Helper function which prepares input data for custom myrange2 and
myrange3 functions. It makes sure that at least one but no more than three
integers were supplied. Returns tuple of three integers, where the last
number is never zero. Can raise TypeError or ValueError exce... | bigcode/self-oss-instruct-sc2-concepts |
def has_empty_domains(csp) :
"""Returns True if the problem has one or more empty domains, otherwise False"""
variables = csp.variables
for var in variables:
if len(csp.get_domain(var)) == 0:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def github_paginate(session, url):
"""Combines return from GitHub pagination
:param session: requests client instance
:param url: start url to get the data from.
See https://developer.github.com/v3/#pagination
"""
result = []
while url:
r = session.get(url)
result.extend(r.... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_stats(csv_path):
"""Parse aligned results csv file to get results.
Args:
csv_path: str, aligned result path, e.g., xx_corresp.txt
Returns:
stat_dict, dict, keys: true positive (TP), deletion (D), insertion (I),
substitution (S), error rate (ER), ground truth numbe... | bigcode/self-oss-instruct-sc2-concepts |
import re
def scrape_eps(soup, sngl=False):
"""Scrapes all episode names and numbers from a specified HTML page, in
the form of a specified :class:`bs4.BeautifulSoup` object.
:param soup: A :class:`bs4.BeautifulSoup` object containing the HTML of
the Wikipedia page to be scraped.
:para... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(filename):
""" Return the contents of a file as a string. """
with open(filename) as f:
str = f.read()
return str | bigcode/self-oss-instruct-sc2-concepts |
def get_strand_color(is_rev):
"""
Get color for forward and reverse reads
:param is_rev: True if read is reversed
:return:
"""
if is_rev == 240.0:
return 1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
import math
def define_cutoff(max_freq, passing_freq, high_pass):
""" # Define Cutoff Value
Args:
max_freq (int): the max frequency allowed
passing_freq (int): the cutoff value
high_pass (bool): if is a high pass filter
Returns:
float: the cutoff value to subtitute wc
... | bigcode/self-oss-instruct-sc2-concepts |
import types
def is_object_module(obj):
"""
Test if the argument is a module object.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, types.ModuleType) | bigcode/self-oss-instruct-sc2-concepts |
def registrar(registry, name="entry"):
"""
Creates and returns a register function that can be used as a decorator
for registering functions into the given registry dictionary.
:param registry: Dictionary to add entry registrations to.
:param name: Name to give to each entry. "entry" is used by def... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def make_datetime_pretty_md(DateTime: datetime):
"""pretty print DateTime for use in Markdown
Args:
DateTime (datetime): DateTime to pretty print, format: 2020-09-05 17:30:00
Returns:
str: pretty printed DateTime, in markdown syntax
"""
return DateT... | bigcode/self-oss-instruct-sc2-concepts |
def string_to_array(string):
"""Convert a string to array, even if empty."""
if string == "":
return [""]
return string.split() | bigcode/self-oss-instruct-sc2-concepts |
def senhas_nao_iguais(senha, senha2):
"""Verifica se as senhas digitadas não são iguais"""
return senha != senha2 | bigcode/self-oss-instruct-sc2-concepts |
def quote_stripped(value: str) -> str:
"""
Strip out a single level of single (') or double (") quotes.
"""
single, double = "'", '"'
if (value.startswith(single) and value.endswith(single)) or\
(value.startswith(double) and value.endswith(double)):
return value[1:-1]
return value | bigcode/self-oss-instruct-sc2-concepts |
import six
def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (six.text_type, six.binary_type)):
... | bigcode/self-oss-instruct-sc2-concepts |
def code_block(text, language=""):
"""Return a code block.
If a language is specified a fenced code block is produced, otherwise the
block is indented by four spaces.
Keyword arguments:
language -- Specifies the language to fence the code in (default blank).
>>> code_block("This is a simple c... | bigcode/self-oss-instruct-sc2-concepts |
def le16_bytes_to_list(bstr):
"""Convert 16bit little-endian bytes to list"""
i = iter(bstr)
return [lb + 256*next(i) for lb in i] | bigcode/self-oss-instruct-sc2-concepts |
def get_displacement_vector(molecule, start_atom, end_atom):
"""
Get the displacement vector between `start_atom` and `end_atom`.
"""
position1, position2 = (
molecule.get_atomic_positions((start_atom, end_atom))
)
return position2 - position1 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def is_directory_entry(entry: Dict) -> bool:
"""Return if given entry is for directory."""
return "directory" == entry["type"] | bigcode/self-oss-instruct-sc2-concepts |
import six
def FuzzyBool(value):
"""Returns value as a boolean with special handling for false-like strings."""
if (isinstance(value, six.string_types) and
value.strip().lower() in ('false', 'no', '0')):
return False
return bool(value) | bigcode/self-oss-instruct-sc2-concepts |
def _get_saml_user_data_property(request, prop_slug):
"""
Shortcut for getting samlUserData properties generated by python3-saml.
These can sometimes manifest as lists or strings.
:param request: HttpRequest
:param prop_slug: string (property slug)
:return: string or None
"""
value = req... | bigcode/self-oss-instruct-sc2-concepts |
def rect_from_sides(left, top, right, bottom):
"""Returns list of points of a rectangle
defined by it's `left`, `top`, `right`, and `bottom`
coordinates, ordered counter-clockwise."""
return [
(left, bottom),
(right, bottom),
(right, top ),
(left, top ),
] | bigcode/self-oss-instruct-sc2-concepts |
def img2windows(img, h_split, w_split):
"""Convert input tensor into split stripes
Args:
img: tensor, image tensor with shape [B, C, H, W]
h_split: int, splits width in height direction
w_split: int, splits width in width direction
Returns:
out: tensor, splitted image
""... | bigcode/self-oss-instruct-sc2-concepts |
def tcl_findprd_prepcuref(center, tail, noprefix=False, key2mode=False):
"""
Prepare candidate PRD.
:param center: PRD-center-tail.
:type center: str
:param tail: PRD-center-tail.
:type tail: int
:param noprefix: Whether to skip adding "PRD-" prefix. Default is False.
:type noprefix: ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Callable
import inspect
def find_scrapers(module) -> List[Callable]:
"""
Build a list of 'scraper' functions contained in a module.
These consist of every function public function (i.e., does not begin with_)
that is defined, but not imported, in the module
... | bigcode/self-oss-instruct-sc2-concepts |
def has_numbers(string):
"""Returns true if there are digits in the string"""
return any(char.isdigit() for char in string) | bigcode/self-oss-instruct-sc2-concepts |
def is_melceplogf0_evaluator(evaluator_keys):
"""Are these evaluator keys from MelCepLogF0 evaluator?"""
return (len(evaluator_keys) == 2 and
evaluator_keys[0] == 'max_mel_cep_distortion' and
evaluator_keys[1] == 'max_log_f0_error') | bigcode/self-oss-instruct-sc2-concepts |
from warnings import warn
def _deprecated_getitem_method(name, attrs):
"""Create a deprecated ``__getitem__`` method that tells users to use
getattr instead.
Parameters
----------
name : str
The name of the object in the warning message.
attrs : iterable[str]
The set of allowe... | bigcode/self-oss-instruct-sc2-concepts |
def _to_utf8_string(s):
"""Encodes the input csv line as a utf-8 string when applicable."""
return s if isinstance(s, bytes) else s.encode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
import click
def show(obj):
"""Display the content of the configuration file."""
if obj.temporary:
click.secho("This is a temporary config file. Please create a "
"proper config file using `quickci config create`.",
fg="red")
click.echo(obj.show())
retur... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Any
def contains_class_type(l: Iterable, cls: Any) -> bool:
"""Return if the given list contains a class with the given type"""
for e in l:
if isinstance(e, cls):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def extract_uuidlist_from_record(uuid_string_list):
"""Extract uuid from Service UUID List
"""
start = 1
end = len(uuid_string_list) - 1
uuid_length = 36
uuidlist = []
while start < end:
uuid = uuid_string_list[start:(start + uuid_length)]
start += uuid_length + 1
uui... | bigcode/self-oss-instruct-sc2-concepts |
def get_exchange_trading_pair(table_name):
"""Function to get exchange and trading_pair bc coinbase_pro has an extra '_' """
# for coinbase_pro
if len(table_name.split('_')) == 4:
exchange = table_name.split('_')[0] + '_' + table_name.split('_')[1]
trading_pair = table_name.split('_')[2] + ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_did(did):
"""Takes a did and returns the run number, dtype, hash"""
scope, name = did.split(':')
number = int(scope.split('_')[1])
dtype, h = name.split('-')
return number, dtype, h | bigcode/self-oss-instruct-sc2-concepts |
def standard2natural(mu, sigma):
"""
Converts standard parameterisation of a 1-D Gaussian to natural
parameterisation.
:param mu: The mean, (*, D).
:param sigma: The standard deviation, (*, D).
:return: np1, np2, (*, D), (*, D).
"""
assert mu.shape[-1] == sigma.shape[-1], "mu (*, D), sig... | bigcode/self-oss-instruct-sc2-concepts |
def collapse_axes(xlab, ylab):
"""Return X/Y labels for unique X positions"""
_xlab, _ylab, pos = [xlab[0]], [ylab[0]], [0]
for i in range(1, len(xlab)):
if xlab[i] != xlab[i-1]:
_xlab.append(xlab[i])
_ylab.append(ylab[i])
pos.append(i)
return _xlab, _ylab, po... | bigcode/self-oss-instruct-sc2-concepts |
def check_filters_enabled(params):
""" Check if filters are enabled
"""
tab = params.tab
filters = tab.get('filters', None)
if tab is None:
return False
if not filters or not filters.get('items', None) or not filters.get('conjunction', None):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def get_percentile_values(cycle_time_dataframe, percentiles):
"""
Get percentile values for cycle times from cycle time data frame.
"""
return tuple([cycle_time_dataframe.Cycle_time.quantile(p/100.0) for p in percentiles]) | bigcode/self-oss-instruct-sc2-concepts |
def compare_bits(mem_entry, mem_idx, test_bit):
"""Compare a memory entry to the expected bit value for that entry"""
valid_entry = True
for bit_idx, bit in enumerate(reversed(mem_entry)):
valid_entry = False
assert int(bit) == test_bit, (
"Incorrect bit @ index {} of mem entry #... | bigcode/self-oss-instruct-sc2-concepts |
def hitTest( a, b ):
"""Circular collision test. Assumes x, y, and radius members on both objects."""
r = a.radius + b.radius
x = abs( a.x - b.x )
y = abs( a.y - b.y )
if x <= r and y <= r and x*x + y*y <= r*r:
return 1
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def validateCPE(cpe):
"""
Returns None if CPE text is valid, validation error string otherwise.
"""
if not cpe.startswith("cpe:"):
return 'CPE must start with "cpe:"'
return None | bigcode/self-oss-instruct-sc2-concepts |
def bold(text: str):
"""Return bolded text"""
return f"**{text}**" | bigcode/self-oss-instruct-sc2-concepts |
import re
def _compose_comment(remote: str, sha: str, git_log: str) -> str:
"""Composes a comment describing the original (triggering) commit.
Arguments:
remote {str} -- a link to the remote git repo
sha {str} -- the hash of the commit
git_log {str} -- the git log for the commit
... | bigcode/self-oss-instruct-sc2-concepts |
def CountWordOccurences(wordArray):
"""Returns a dictionary containing each word in the array and how often it occurs"""
dict = {}
for word in wordArray:
# If the dictionary does not contain the word, add it to the dictionary with 1 occurence
if not word in dict:
dict[word] = 1
... | bigcode/self-oss-instruct-sc2-concepts |
def add_one(x: int):
"""Add one to `x`
Args:
x: an integer
"""
return x + 1 | bigcode/self-oss-instruct-sc2-concepts |
def discard_empty_elements(soup, exempt=()):
"""Remove HTML elements that have no/whitespace-only content"""
for tag in soup.find_all():
if len(tag.get_text(strip=True)) == 0 and tag.name not in exempt:
tag.extract()
return soup | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def get_color_for_figure(n_vertices: int) -> Tuple[int, int, int]:
"""Returns an RBG color tuple depending on the number of vertices."""
if n_vertices == 3:
return (200, 0, 0)
elif n_vertices == 4:
return (0, 200, 0)
elif n_vertices >= 10:
return (0, ... | bigcode/self-oss-instruct-sc2-concepts |
import math
def dist(p0, p1):
""" Calculates the distance between two xy coordinates, each
each coordinated supplied by a tupel"""
return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2) | bigcode/self-oss-instruct-sc2-concepts |
def get_ages(df, sex):
"""Returns the ages of men or women, whom Embarked from section C.
Parameters:
df(pyspark.sql.DataFrame): based on the titanic.csv module
sex(str): for our dataset, it is a binary classification of 'male' or 'female'
Returns: List[float]
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def pb_dict(message):
"""Create dict representation of a protobuf message"""
return dict([(field.name, value) for field, value in message.ListFields()]) | bigcode/self-oss-instruct-sc2-concepts |
def get_resource_bar(avail, total, text='', long=False):
"""Create a long/short progress bar with text overlaid. Formatting handled in css."""
if long:
long_str = ' class=long'
else:
long_str = ''
bar = (f'<div class="progress" data-text="{text}">'
f'<progress{long_str} max="... | bigcode/self-oss-instruct-sc2-concepts |
def dongers(l, b, i):
"""ヽ༼ຈل͜ຈ༽ノ"""
b.l_say(dongers.__doc__, i)
return True | bigcode/self-oss-instruct-sc2-concepts |
def to_camel_case(text, split=" "):
"""
Converts text to camel case, e.g. ("the camel is huge" => "theCamelIsHuge")
Args:
text (string): Text to be camel-cased
split (char): Char to split text into
"""
camel_case_text = text
splitter = text.split(split)
if splitter:
c... | bigcode/self-oss-instruct-sc2-concepts |
def read_input(path: str):
"""
Read game board file from path.
Return list of str.
"""
lines = []
with open(path, 'r', encoding='utf-8') as file:
for line in file:
lines.append(line.strip())
return lines | bigcode/self-oss-instruct-sc2-concepts |
import torch
def check_random_state(seed, device=torch.device("cuda")):
"""Turn seed into a torch.Generator instance
Parameters
----------
seed : None | int | instance of torch.Generator
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a n... | bigcode/self-oss-instruct-sc2-concepts |
def swedish_translator(firstname, lastname):
"""Check if 'firstname lastname' is a Swedish translator."""
swedish_translators = [
"Linnea Åshede"
]
name = firstname + " " + lastname
if name in swedish_translators:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_stock_root(path: Path) -> Path:
"""
Traverse from given path up till root of the system to figure out the root of the
stock repo. A stock repo must be hangar repo, a git repo and must have a head.stock
file. The head.stock file has the information required for stockroo... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import shutil
def pwhich(command: str) -> Path:
"""Path to given command.
shutil.which only returns a string.
:returns: Path to command
:rtype: pathlib.Path
"""
path_str = shutil.which(command)
assert path_str, f"{command} not found"
return Path(path_str) | bigcode/self-oss-instruct-sc2-concepts |
def _get_class_name(property_repr: str) -> str:
"""
Extract the class name from the property representation.
:param property_repr: The representation
:type property_repr: str
:return: The class name
:rtype: str
"""
return property_repr[: property_repr.index("(")] | bigcode/self-oss-instruct-sc2-concepts |
def fixed_crops(X, crop_shape, crop_type):
"""
Take center or corner crops of images.
Inputs:
- X: Input data, of shape (N, C, H, W)
- crop_shape: Tuple of integers (HH, WW) giving the size to which each
image will be cropped.
- crop_type: One of the following strings, giving the type of crop to
co... | bigcode/self-oss-instruct-sc2-concepts |
def mp0(en):
"""Return the 0th order energy."""
return en.sum() | bigcode/self-oss-instruct-sc2-concepts |
def strip_numbers(text):
"""Strip numbers from text."""
return ''.join(filter(lambda u: not u.isdigit(), text)) | bigcode/self-oss-instruct-sc2-concepts |
def create_minio_dispatcher_node(name):
"""
Args:
name(str): Name of the minio node
Returns:
dict: A dictionnary with the minio node configuration
"""
return {
"endpoint_url": "http://{:s}:9000/".format(name),
"aws_access_key_id": "playcloud",
"aws_secret_acce... | bigcode/self-oss-instruct-sc2-concepts |
def r_to_depth(x, interval):
"""Computes rainfall depth (mm) from rainfall intensity (mm/h)
Parameters
----------
x : float,
float or array of float
rainfall intensity in mm/h
interval : number
time interval (s) the values of `x` represent
Returns
-------
output... | bigcode/self-oss-instruct-sc2-concepts |
def RunLintOverAllFiles(linter, filenames):
"""Runs linter over the contents of all files.
Args:
lint: subclass of BaseLint, implementing RunOnFile()
filenames: list of all files whose contents will be linted
Returns:
A list of tuples with format [(filename, line number, msg), ...] with any
viol... | bigcode/self-oss-instruct-sc2-concepts |
def import_words(filename):
"""Imports words from a given .txt file and returns it.
"""
# Initialize resuts variable
results = []
# This with statement ensures the file is only open for a certain amount of time.
# This can save RAM and processing speeds in larger projects
# Rename the spri... | bigcode/self-oss-instruct-sc2-concepts |
def order_to_degree(order):
"""Compute the degree given the order of a B-spline."""
return int(order) - 1 | bigcode/self-oss-instruct-sc2-concepts |
def _get_object_from_classname(classname, data):
""" Returns an object instance for given classname and data dictionary.
Args:
classname (str): Full classname as string including the modules, e.g. repo.Y if class Y is defined in module repo.
data (dict): dictionary of data used to initialize th... | bigcode/self-oss-instruct-sc2-concepts |
import zlib
def anonymize(user_uid: str, user_ip: str) -> str:
"""Make a user-readable hashed identity."""
if user_uid:
return "Goog#%d" % (zlib.adler32(user_uid.encode()) % 10000,)
return "Anon#%d" % (zlib.adler32(user_ip.encode()) % 10000,) | bigcode/self-oss-instruct-sc2-concepts |
import math
def deg2num(lat_deg, lon_deg, zoom):
"""Convert latitude and longitude to x/y tile coordinates."""
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def hex_rand(n):
"""
Generates a hexadecimal string with `n` random bits.
"""
return "%x" % random.SystemRandom().getrandbits(n) | bigcode/self-oss-instruct-sc2-concepts |
def is_tcp_rst(tcp_data):
"""is TCP RST?"""
return tcp_data["flags"]["rst"] == 1 | bigcode/self-oss-instruct-sc2-concepts |
import copy
def merge_dicts(dict1, dict2, recycle=True):
"""
Recursively merge two dictionaries. dict2's values will override dict1's
:param recycle: if True then write the merged dictionary into dict1, otherwise do not modify dict1
:return: a single dictionary
"""
assert type(dict1) is dict... | bigcode/self-oss-instruct-sc2-concepts |
def serialize_config( config_data ):
"""
Generate a .ini-formatted configuration string to e.g. save to disk.
"""
return "[syndicate]\n" + "\n".join( ["%s=%s" % (config_key, config_value) for (config_key, config_value) in config_data.items()] ) | bigcode/self-oss-instruct-sc2-concepts |
def clamp(num):
"""
Return a "clamped" version of the given num,
converted to be an int limited to the range 0..255 for 1 byte.
"""
num = int(num)
if num < 0:
return 0
if num >= 256:
return 255
return num | bigcode/self-oss-instruct-sc2-concepts |
def name(cls):
"""Get a nice name for this object."""
return cls.__class__.__name__ | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def partition_data(data: List[List[str]]
) -> Tuple[List[List[str]], List[List[str]]]:
"""Partitions data into train and test partitions.
The train partition consists of 80% of the data.
The test partition consists of 20% of the data.
... | bigcode/self-oss-instruct-sc2-concepts |
def _first(iterable, what, test='equality'):
"""return the index of the first occurance of ``what`` in ``iterable``
"""
if test=='equality':
for index, item in enumerate(iterable):
if item == what:
break
else:
index = None
else:
raise N... | bigcode/self-oss-instruct-sc2-concepts |
def equal_probs(num_values):
"""Make an array of equal probabilities."""
prob = 1.0 / num_values
probs = [prob for i in range(num_values)]
return probs | bigcode/self-oss-instruct-sc2-concepts |
def _GenerateLocalProperties(sdk_dir):
"""Returns the data for project.properties as a string."""
return '\n'.join([
'# Generated by //build/android/gradle/generate_gradle.py',
'sdk.dir=%s' % sdk_dir,
'']) | bigcode/self-oss-instruct-sc2-concepts |
def set_contourf_properties(stroke_width, fcolor, fill_opacity, level, unit):
"""Set property values for Polygon."""
return {
"stroke": fcolor,
"stroke-width": stroke_width,
"stroke-opacity": 1,
"fill": fcolor,
"fill-opacity": fill_opacity,
"title": "{} {}".format... | bigcode/self-oss-instruct-sc2-concepts |
def _preprocess_padding(padding):
"""Convert keras' padding to tensorflow's padding.
# Arguments
padding: string, `"same"` or `"valid"`.
# Returns
a string, `"SAME"` or `"VALID"`.
# Raises
ValueError: if `padding` is invalid.
"""
if padding == 'same':
padding = 'S... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def check_length(caption: str, limit: int = 1024) -> str:
"""checks length of message against Telegram limits
Args:
caption (str): Message string.
limit (int, optional): Message length limit. Defaults to 1024.
Returns:
str: If caption length minus en... | bigcode/self-oss-instruct-sc2-concepts |
def get_target_dimension_order(out_dims, direction_to_names):
"""
Takes in an iterable of directions ('x', 'y', 'z', or '*') and a dictionary
mapping those directions to a list of names corresponding to those
directions. Returns a list of names in the same order as in out_dims,
preserving the order ... | bigcode/self-oss-instruct-sc2-concepts |
def add_claims_to_jwt_token(user):
"""
Return the claims that should be added to the JWT token.
This function is called whenever create_access_token is called.
"""
return {
"roles": list(map(lambda r: r.name, user.roles)),
"permissions": list(map(lambda p: p.name, user.permissions))... | bigcode/self-oss-instruct-sc2-concepts |
def create_titoli(conn, titoliTuple):
"""
Create a new record into the titoli table
:param conn:
:param titoliTuple:
:return: titoliRecord id
"""
sql = ''' INSERT INTO titoliCounter('cvid', 'titolo-01', 'titolo-02','titolo-03','titolo-04','titolo-05','titolo-06','titolo-07','titolo-08','titolo-09','titolo-10','t... | bigcode/self-oss-instruct-sc2-concepts |
def status(level, solved, err):
"""Calculate status from status and err."""
if solved:
if err:
status = 'multiple solution'
else:
status = 'level ' + str(level)
else:
if err:
status = 'no solution'
else:
status = 'give up'
r... | bigcode/self-oss-instruct-sc2-concepts |
def get_target_info(target):
"""Return target information as a version tuple."""
return tuple(int(x) for x in target) | bigcode/self-oss-instruct-sc2-concepts |
def to_string(number):
""" Convert float/int to string
>>> to_string(13)
'13'
"""
return str(int(number)) | bigcode/self-oss-instruct-sc2-concepts |
def custom_returns(prices, predicted_prices, is_returns, frequency=252):
"""
Calculates expected return from user fed predicted prices or returns.
:param prices: historical price data
:type prices: pd.DataFrame
:param predicted_prices: predicted data of asset prices or returns
:type predicted_... | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(source, target):
"""二分探索. 計算量: O(log n) """
start, end = 0, len(source)
while start <= end:
index = (start + end) // 2 # index: 中央値
if source[index] == target:
# 見つかったらそのindexを返す
return index
elif source[index] < target:
# 検索範囲... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import List
def cell_regions(
x_len: float, y_len: float, factor: float = 2 / 3, buffer: float = 3.5
) -> Tuple[List[List[float]], ...]:
"""Calculate the boundary of the different regions used for classification.
When running an interface simulation there is a region ... | bigcode/self-oss-instruct-sc2-concepts |
def get_post_match(child, args, index, child_dict):
"""
matching function for post nodes
Args:
child: the matched child from which we check post tokens.
args: list of incoming tokens.
index: position in args list where comparison continues.
child_dict: the dictionary that is ... | bigcode/self-oss-instruct-sc2-concepts |
def cursorNextOrNone(cursor):
"""
Given a Mongo cursor, return the next value if there is one. If not,
return None.
:param cursor: a cursor to get a value from.
:returns: the next value or None.
"""
try:
return cursor.next() # noqa - B305
except StopIteration:
return N... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _parse_block(block: str) -> Tuple[str, str]:
"""Extract question and answer from a text block."""
question_start = block.find('\n', block.find('Вопрос')) + 1
question_end = block.find('\n\n', question_start)
question = block[question_start:question_end]
question = " ".... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def sinc3(t):
""" sinc3: t -> (t - sin(t)) / (t**3) """
e = 0.01
r = torch.zeros_like(t)
a = torch.abs(t)
s = a < e
c = (s == 0)
t2 = t[s] ** 2
r[s] = 1/6*(1-t2/20*(1-t2/42*(1-t2/72))) # Taylor series O(t^8)
r[c] = (t[c]-torch.sin(t[c]))/(t[c]**3)
return r | 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.