seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def extracthypos(synset, limit=999):
"""Given a synset object, return a set with all synsets
underneath it in the PWN structure (including the original)."""
l = limit-1
result = []
result.append(synset)
if synset.hyponyms() and l > 0:
for each in synset.hyponyms():
x = extra... | bigcode/self-oss-instruct-sc2-concepts |
def decimal_to_percent(value, decimal_place=2):
"""
Format a decimal to percentage with two decimal
:param value: the value to be formatted
:param decimal_place default decimal place, default to 2
:return: a string in percentage format, 20.50% etc
"""
format_str = '{:.' + str(2) + '%}'
r... | bigcode/self-oss-instruct-sc2-concepts |
def sec2hms(seconds):
"""
Convert seconds into a string with hours, minutes and seconds.
Parameters:
* seconds : float
Time in seconds
Returns:
* time : str
String in the format ``'%dh %dm %2.5fs'``
Example::
>>> print sec2hms(62.2)
0h 1m 2.20000s
... | bigcode/self-oss-instruct-sc2-concepts |
def get_HTML(file):
"""
Retrieves the source code from a specified saved html file
args:
file: The Specified html to retrieve the source code from
"""
f = open(file, 'r')
lines = f.readlines()
f.close()
return "".join(lines) | bigcode/self-oss-instruct-sc2-concepts |
import fsspec
def map_tgt(tgt, connection_string):
"""Uses fsspec to creating mapped object from target connection string"""
tgt_map = fsspec.get_mapper(tgt, connection_string=connection_string)
return tgt_map | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_brier_score(y_pred, y_true):
"""Brier score implementation follows
https://papers.nips.cc/paper/7219-simple-and-scalable-predictive-uncertainty-estimation-using-deep-ensembles.pdf.
The lower the Brier score is for a set of predictions, the better the predictions are calibrated.""... | bigcode/self-oss-instruct-sc2-concepts |
def color_blend(a, b):
"""
Performs a Screen blend on RGB color tuples, a and b
"""
return (255 - (((255 - a[0]) * (255 - b[0])) >> 8),
255 - (((255 - a[1]) * (255 - b[1])) >> 8),
255 - (((255 - a[2]) * (255 - b[2])) >> 8)) | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def ncolors(levels):
"""Generate len(levels) colors with darker-to-lighter variants
for each color
Args:
levels(list): List with one element per required color. Element
indicates number of variants for that color
Returns:
List of lists with variants for ea... | bigcode/self-oss-instruct-sc2-concepts |
def compileStatus(lOutput, iWarning, iCritical, sFilesystem):
"""
compiles OK/WARNING/CRITICAL/UNKNOWN status
gets:
lOutput : list of dicts for each Disk
iWarning : warning threshold
iCritical : critical threshold
sFilesystem: filesystem which to compare iWarning and iCritical agains... | bigcode/self-oss-instruct-sc2-concepts |
def get_entities_filter(search_entities):
"""Forms filter dictionary for search_entities
Args:
search_entities (string): entities in search text
Returns:
dict: ES filter query
"""
return {
"nested": {
"path": "data.entities",
"filter":{
"bool":{
"should": [
{
"terms":... | bigcode/self-oss-instruct-sc2-concepts |
import math
def rect(r, theta):
"""
theta in degrees
returns tuple; (float, float); (x,y)
"""
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
return x, y | bigcode/self-oss-instruct-sc2-concepts |
def task_update() -> dict:
"""Update existing message catalogs from a *.pot file."""
return {
"actions": [
"pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l en",
"pybabel update -D shooter -i shooter/po/shooter.pot -d shooter/locale -l ru",
],
... | bigcode/self-oss-instruct-sc2-concepts |
def _json_force_object(v):
"""Force a non-dictionary object to be a JSON dict object"""
if not isinstance(v, dict):
v = {'payload': v}
return v | bigcode/self-oss-instruct-sc2-concepts |
def erbs2hz(erbs):
"""
Convert values in Equivalent rectangle bandwidth (ERBs) to
values in Hertz (Hz)
Parameters from [1]
Args:
erbs (float): real number in ERBs
Returns:
hz (float): real number in Hertz
References:
[1] Camacho, A., & Harris, J. G. (2008). A sawt... | bigcode/self-oss-instruct-sc2-concepts |
def split_df_by_regions(df):
"""
Split the dataframe based on TotalUS, regions and sub-regions
"""
df_US = df[df.region == 'TotalUS']
regions = ['West', 'Midsouth', 'Northeast', 'SouthCentral', 'Southeast']
df_regions = df[df.region.apply(lambda x: x in regions and x != 'TotalUS')]
df_subreg... | bigcode/self-oss-instruct-sc2-concepts |
def is_week_day(the_date):
""" Decides if the given date is a weekday.
Args:
the_date: Date object. The date to decide.
Returns:
Boolean. Whether the given date is a weekday.
"""
return the_date.isoweekday() in [1, 2, 3, 4, 5] | bigcode/self-oss-instruct-sc2-concepts |
def path_in_book(path):
"""
A filter function that checks if a given path is part of the book.
"""
if ".ipynb_checkpoints" in str(path):
return False
if "README.md" in str(path):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import posixpath
def format_path(base: str, components: List[str]) -> str:
"""
Formats a base and http components with the HTTP protocol and the expected port.
"""
url = "http://{}:8000/".format(base)
for component in components:
url = posixpath.join(url, component... | bigcode/self-oss-instruct-sc2-concepts |
def FV(pv:float, r:float, n:float, m = 1):
"""
FV(): A function to calculate Future Value.
:param pv: Present Value
:type pv: float
:param r: Rate of Interest/Discount Rate (in decimals eg: 0.05 for 5%)
:type r: float
:param n: Number of Years
:type n: float
:param m: Frequency of Interest Calculatio... | bigcode/self-oss-instruct-sc2-concepts |
def __equivalent_lists(list1, list2):
"""Return True if list1 and list2 contain the same items."""
if len(list1) != len(list2):
return False
for item in list1:
if item not in list2:
return False
for item in list2:
if item not in list1:
return False
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import math
def check_root(string: str) -> str:
"""
A function which takes numbers separated by commas
in string format and returns the number which is a
perfect square and the square root of that number.
If string contains other characters than number or
it has more o... | bigcode/self-oss-instruct-sc2-concepts |
def get_dictvalue_from_xpath(full_dict, path_string):
""" get a value in a dict given a path's string """
key_value = full_dict
for i in path_string.split('/')[1:] :
key_value = key_value[i]
return key_value | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_nterm_mods(seq):
"""
Extract nterminal mods, e.g. acA.
Args:
seq: str, peptide sequence
Returns:
ar-like, list of modifications
"""
# matches all nterminal mods, e.g. glD or acA
nterm_pattern = re.compile(r'^([a-z]+)([A-Z])')
mods = []
# test... | bigcode/self-oss-instruct-sc2-concepts |
def cubic_bezier(p0, p1, p2, p3, t):
""" evaluate cubic bezier curve from p0 to p3 at fraction t for control points p1 and p2 """
return p0 * (1 - t)**3 + 3 * p1 * t*(1 - t)**2 + 3 * p2 * t**2*(1 - t) + p3 * t**3 | bigcode/self-oss-instruct-sc2-concepts |
def filter_results(results, filters, exact_match) -> list[dict]:
"""
Returns a list of results that match the given filter criteria.
When exact_match = true, we only include results that exactly match
the filters (ie. the filters are an exact subset of the result).
When exact-match = false,
we ... | bigcode/self-oss-instruct-sc2-concepts |
def fact(n):
"""Finding factorial iteratively"""
if n == 1 or n == 0:
return 1
result = 1
for i in range(n, 1, -1):
result = result * i
return result | bigcode/self-oss-instruct-sc2-concepts |
def SignDotNetManifest(env, target, unsigned_manifest):
"""Signs a .NET manifest.
Args:
env: The environment.
target: Name of signed manifest.
unsigned_manifest: Unsigned manifest.
Returns:
Output node list from env.Command().
"""
sign_manifest_cmd = ('@mage -Sign $SOURCE -ToFile $TARGET -Ti... | bigcode/self-oss-instruct-sc2-concepts |
def calc_gene_lens(coords, prefix=False):
"""Calculate gene lengths by start and end coordinates.
Parameters
----------
coords : dict
Gene coordinates table.
prefix : bool
Prefix gene IDs with nucleotide IDs.
Returns
-------
dict of dict
Mapping of genes to leng... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def int_to_one_hot(class_labels, nb_classes, device, soft_target=1.):
""" Convert tensor containing a batch of class indexes (int) to a tensor
containing one hot vectors."""
one_hot_tensor = torch.zeros((class_labels.shape[0], nb_classes),
device=device)
f... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(path: str) -> str: # pragma: nocover
"""
This function simply reads contents of the file. It's moved out to a function
purely to simplify testing process.
Args:
path: File to read.
Returns:
content(str): Content of given file.
"""
return open(path).read() | bigcode/self-oss-instruct-sc2-concepts |
def text_to_list(element, delimiter='|'):
"""
Receives a text and a delimiter
Return a list of elements by the delimiter
"""
return element.split(delimiter) | bigcode/self-oss-instruct-sc2-concepts |
def living_expenses(after_tax_income):
"""
Returns the yearly living expenses, which is 5% of the after tax income.
:param after_tax_income: The yearly income after income tax.
:return: The living expenses.
"""
return after_tax_income * 0.05 | bigcode/self-oss-instruct-sc2-concepts |
def comma_separated(xs):
"""Convert each value in the sequence xs to a string, and separate them
with commas.
>>> comma_separated(['spam', 5, False])
'spam, 5, False'
>>> comma_separated([5])
'5'
>>> comma_separated([])
''
"""
return ', '.join([str(x) for x in xs]) | bigcode/self-oss-instruct-sc2-concepts |
def dummy_category(create_category):
"""Create a mocked dummy category."""
return create_category(title='dummy') | bigcode/self-oss-instruct-sc2-concepts |
def is_list_like(arg):
"""Returns True if object is list-like, False otherwise"""
return (hasattr(arg, '__iter__') and
not isinstance(arg, str)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
def extract_tracks(plist: Dict) -> List[Dict[str, str]]:
"""Takes a Dict loaded from plistlib and extracts the in-order tracks.
:param plist: the xml plist parsed into a Dict.
:returns: a list of the extracted track records.
"""
try:
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _source(obj):
"""
Returns the source code of the Python object `obj` as a list of
lines. This tries to extract the source from the special
`__wrapped__` attribute if it exists. Otherwise, it falls back
to `inspect.getsourcelines`.
If neither works, then the empty list is re... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def precip_table_etl_cnrccep(
ws_precip,
rainfall_adjustment=1
):
"""
Extract, Transform, and Load data from a Cornell Northeast Regional
Climate Center Extreme Precipitation estimates csv into an array
Output: 1D array containing 24-hour duration estimate for frequencies 1... | bigcode/self-oss-instruct-sc2-concepts |
def find_9(s):
"""Return -1 if '9' not found else its location at position >= 0"""
return s.split('.')[1].find('9') | bigcode/self-oss-instruct-sc2-concepts |
def normalize_cov_type(cov_type):
"""
Normalize the cov_type string to a canonical version
Parameters
----------
cov_type : str
Returns
-------
normalized_cov_type : str
"""
if cov_type == 'nw-panel':
cov_type = 'hac-panel'
if cov_type == 'nw-groupsum':
cov_... | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_payload(payload):
"""Returns a dict of command data"""
return json.loads(payload.get('data').decode()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def uniform_knot_vector(count: int, order: int, normalize=False) -> List[float]:
""" Returns an uniform knot vector for a B-spline of `order` and `count`
control points.
`order` = degree + 1
Args:
count: count of control points
order: spline order
norm... | bigcode/self-oss-instruct-sc2-concepts |
def process_mmdet_results(mmdet_results, cat_id=1):
"""Process mmdet results, and return a list of bboxes.
:param mmdet_results:
:param cat_id: category id (default: 1 for human)
:return: a list of detected bounding boxes
"""
if isinstance(mmdet_results, tuple):
det_results = mmdet_resu... | bigcode/self-oss-instruct-sc2-concepts |
def get_top_header(table, field_idx):
"""
Return top header by field header index.
:param table: Rendered table (dict)
:param field_idx: Field header index (int)
:return: dict or None
"""
tc = 0
for th in table['top_header']:
tc += th['colspan']
if tc > field_idx:
... | bigcode/self-oss-instruct-sc2-concepts |
def incident_related_resource_data_to_xsoar_format(resource_data, incident_id):
"""
Convert the incident relation from the raw to XSOAR format.
:param resource_data: (dict) The related resource raw data.
:param incident_id: The incident id.
"""
properties = resource_data.get('properties', {})
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def is_gpu_available() -> bool:
"""Check if GPU is available
Returns:
bool: True if GPU is available, False otherwise
"""
return torch.cuda.is_available() | bigcode/self-oss-instruct-sc2-concepts |
def find_ingredients_graph_leaves(product):
"""
Recursive function to search the ingredients graph and find its leaves.
Args:
product (dict): Dict corresponding to a product or a compound ingredient.
Returns:
list: List containing the ingredients graph leaves.
"""
if 'ingredie... | bigcode/self-oss-instruct-sc2-concepts |
def getPathName(path):
"""Get the name of the final entity in C{path}.
@param path: A fully-qualified C{unicode} path.
@return: The C{unicode} name of the final element in the path.
"""
unpackedPath = path.rsplit(u'/', 1)
return path if len(unpackedPath) == 1 else unpackedPath[1] | bigcode/self-oss-instruct-sc2-concepts |
import pipes
def shell_join(command):
"""Return a valid shell string from a given command list.
>>> shell_join(['echo', 'Hello, World!'])
"echo 'Hello, World!'"
"""
return ' '.join([pipes.quote(x) for x in command]) | bigcode/self-oss-instruct-sc2-concepts |
def gen_fasta2phy_cmd(fasta_file, phylip_file):
"""
Returns a "fasta2phy" command <list>
Input:
fasta_file <str> -- path to fasta file
phylip_file <str> -- path to output phylip file
"""
return ['fasta2phy', '-i', fasta_file, '-o', phylip_file] | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_multi_value_operators(string):
"""The Search API will parse a query like `PYTHON OR` as an incomplete
multi-value query, and raise an error as it expects a second argument
in this query language format. To avoid this we strip the `AND` / `OR`
operators tokens from the end of query ... | bigcode/self-oss-instruct-sc2-concepts |
def get_nodes(database):
"""Get all connected nodes as a list of objects with node_id and node_label as elements"""
results = list(database["nodes"].find())
nodes = []
for node in results:
nodes.append({"id": node["_id"], "description": node["label"]})
return nodes | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_code(text):
""" Extracts the python code from the message
Return value: (success, code)
success: True if the code was found, False otherwise
code: the code if success is True, None otherwise
"""
regex = r"(?s)```(python)?(\n)?(.*?)```"
match = re.search(rege... | bigcode/self-oss-instruct-sc2-concepts |
from unittest.mock import Mock
def get_discovered_bridge(bridge_id="aabbccddeeff", host="1.2.3.4", supports_v2=False):
"""Return a mocked Discovered Bridge."""
return Mock(host=host, id=bridge_id, supports_v2=supports_v2) | bigcode/self-oss-instruct-sc2-concepts |
def host_get_id(host):
"""
Retrieve the host id
"""
return host['id'] | bigcode/self-oss-instruct-sc2-concepts |
def is_nds_service(network_data_source):
"""Determine if the network data source points to a service.
Args:
network_data_source (network data source): Network data source to check.
Returns:
bool: True if the network data source is a service URL. False otherwise.
"""
return bool(net... | bigcode/self-oss-instruct-sc2-concepts |
def opacity(token):
"""Validation for the ``opacity`` property."""
if token.type == 'number':
return min(1, max(0, token.value)) | bigcode/self-oss-instruct-sc2-concepts |
def get_default_alignment_parameters(adjustspec):
"""
Helper method to extract default alignment parameters as passed in spec and return values in a list.
for e.g if the params is passed as "key=value key2=value2", then the returned list will be:
["key=value", "key2=value2"]
"""
default_al... | bigcode/self-oss-instruct-sc2-concepts |
def goldstein_price(x):
"""
Goldstein-Price function (2-D).
Global Optimum: 3.0 at (0.0, -1.0).
Parameters
----------
x : array
2 x-values. `len(x)=2`.
`x[i]` bound to [-2, 2] for i=1 and 2.
Returns
-------
float
Value of Goldstein-Price function.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_titles(_stories):
"""
function extract titles from received stories
:param _stories: list of stories including story title, link, unique id, published time
:return: list of titles
"""
# Get the stories titles
titles = []
for story in _stories:
titles.append(story['title']... | bigcode/self-oss-instruct-sc2-concepts |
def rgbToHex(rgb: tuple[int, int, int]) -> str:
""" convert rgb tuple to hex """
return "#{0:02x}{1:02x}{2:02x}".format(rgb[0], rgb[1], rgb[2]) | bigcode/self-oss-instruct-sc2-concepts |
def make_sleep_profile_colnames(df):
"""
Create list of ordered column names for dataframe to be created
from sleep_profile dictionary
"""
colnames = ['Time']
for i in range(11,16):
colnames.append(df.columns[i] + ' MR Sum')
colnames.append(df.columns[i] + ' Avg Sleep')
... | bigcode/self-oss-instruct-sc2-concepts |
def nice_column_names(df):
"""Convenience function to convert standard names from BigQuery to nice names for plotting"""
cols = [
('Open Access (%)', 'percent_OA'),
('Open Access (%)', 'percent_oa'),
('Open Access (%)', 'percent_total_oa'),
('Total Green OA (%)', 'percent_green'... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_FCF(r, T):
"""
Calculate FCF from given information
:param r: Is the rate of inflation
:param T: Is the time in years
:return: No units cost factor
"""
r = r / 100
den = r * ((1 + r) ** T)
num = ((1 + r) ** T) - 1
return den / num | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def write_sqlite_file(plants_dict, filename, return_connection=False):
"""
Write database into sqlite format from nested dict.
Parameters
----------
plants_dict : dict
Has the structure inherited from <read_csv_file_to_dict>.
filename : str
Output filepath; should not exist before function c... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def determine_sentence_speaker(chunk):
"""
Validate for a chunk of the transcript (e.g. sentence) that there is one speaker.
If not, take a majority vote to decide the speaker
"""
speaker_ids = [ word[3] for word in chunk ]
if len(set(speaker_ids)) != 1:
prin... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_liste(count):
"""
Returning a list containing 'count' no. of elements
with random values between 0 and 100 (both inclusive)
"""
#Return a list of len 'count', with random numbers from 0..100
return [random.randint(0, 100) for _ in range(count)] | bigcode/self-oss-instruct-sc2-concepts |
def linear(interval, offset=0):
"""Creates a linear schedule that tracks when ``{offset + n interval | n >= 0}``.
Args:
interval (int): The regular tracking interval.
offset (int, optional): Offset of tracking. Defaults to 0.
Returns:
callable: Function that given the global_step r... | bigcode/self-oss-instruct-sc2-concepts |
def _is_valid_sub_path(path, parent_paths):
"""
Check if a sub path is valid given an iterable of parent paths.
:param (tuple[str]) path: The path that may be a sub path.
:param (list[tuple]) parent_paths: The known parent paths.
:return: (bool)
Examples:
* ('a', 'b', 'c') is a valid ... | bigcode/self-oss-instruct-sc2-concepts |
def get_valid_loss(model, valid_iter, criterion):
"""
Get the valid loss
:param model: RNN classification model
:type model:
:param valid_iter: valid iterator
:type valid_iter: data.BucketIterator
:param criterion: loss criterion
:type criterion: nn.CrossEntropyLoss
:return: valid l... | bigcode/self-oss-instruct-sc2-concepts |
def clean(string):
""" Cleans the string by making the case uniform and removing spaces. """
if string:
return string.strip().lower()
return '' | bigcode/self-oss-instruct-sc2-concepts |
def formatFloat(number, decimals=0):
"""
Formats value as a floating point number with decimals digits in the mantissa
and returns the resulting string.
"""
if decimals <= 0:
return "%f" % number
else:
return ("%." + str(decimals) + "f") % number | bigcode/self-oss-instruct-sc2-concepts |
def deserialize_tuple(d):
"""
Deserializes a JSONified tuple.
Args:
d (:obj:`dict`): A dictionary representation of the tuple.
Returns:
A tuple.
"""
return tuple(d['items']) | bigcode/self-oss-instruct-sc2-concepts |
def plan_window(plan, ending_after, starting_before):
"""
Return list of items in the given window.
"""
window_tasks = []
for task in plan:
if ending_after < task['end'] and task['start'] < starting_before:
window_tasks.append(task)
return window_tasks | bigcode/self-oss-instruct-sc2-concepts |
def helper(A, k, left, right):
"""binary search of k in A[left:right], return True if found, False otherwise"""
print(f'so far ==> left={left}, right={right}, k={k}, A={A}')
#1- base case
if left > right:
# if empty list there is nothing to search
return False
#2- solve the subprob... | bigcode/self-oss-instruct-sc2-concepts |
def override(left, right, key, default):
"""Returns right[key] if exists, else left[key]."""
return right.get(key, left.get(key, default)) | bigcode/self-oss-instruct-sc2-concepts |
def delete_fit_attrs(est):
"""
Removes any fit attribute from an estimator.
"""
fit_keys = [k for k in est.__dict__.keys() if k.endswith('_')]
for k in fit_keys:
del est.__dict__[k]
return est | bigcode/self-oss-instruct-sc2-concepts |
def retrieve_arguments(args):
""" Further parses arguments from CLI based on type and constructs concise object containing
the parameters that will dictate behavior downstream
:param args - arguments retrieved from call to parser.parse_args as part of argparse library
:returns dictionary containing all... | bigcode/self-oss-instruct-sc2-concepts |
def set_voltage(channel: int, value: float):
"""
Sets voltage on channel to the value.
"""
return f"VSET{channel}:{value}" | bigcode/self-oss-instruct-sc2-concepts |
def split_name(name):
"""
Split a name in two pieces: first_name, last_name.
"""
parts = name.split(' ')
if len(parts) == 4 and parts[2].lower() not in ('de', 'van'):
first_name = ' '.join(parts[:2])
last_name = ' '.join(parts[2:])
else:
first_name = parts[0]
last... | bigcode/self-oss-instruct-sc2-concepts |
def jaccard_distance(text1, text2):
""" Measure the jaccard distance of two different text.
ARGS:
text1,2: list of tokens
RETURN:
score(float): distance between two text
"""
intersection = set(text1).intersection(set(text2))
union = set(text1).union(set(text2))
return 1 -... | bigcode/self-oss-instruct-sc2-concepts |
def chunks(_list, n):
"""
Return n-sized chunks from a list.
Args:
_list - A list of elements.
n - Number defining the size of a chunk.
Returns:
A list of n-sized chunks.
"""
return list(map(lambda i: _list[i:i + n], range(0, len(_list), n))) | bigcode/self-oss-instruct-sc2-concepts |
def objective_rule(model):
"""
Maximize the sum of all rewards of activities that are 'picked' (selected)
"""
return sum(model.CHILD_ALLOCATED[cr, ca] * model.child_score[ca] for (cr, ca) in model.cr_ca_arcs) | bigcode/self-oss-instruct-sc2-concepts |
def remove_spaces(string):
""" Remove triple/double and leading/ending spaces """
while ' ' in string:
string = string.replace(' ', ' ')
return string.strip() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import Optional
from pathlib import Path
def check_for_project(path: Union[str, "Path"] = ".") -> Optional["Path"]:
"""Checks for a Brownie project."""
path = Path(path).resolve()
for folder in [path] + list(path.parents):
if folder.joinpath("brownie-config.jso... | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def lighten_rgb(rgb, times=1):
"""Produce a lighter version of a given base colour."""
h, l, s = colorsys.rgb_to_hls(*rgb)
mult = 1.4**times
hls_new = (h, 1 - (1 - l) / mult, s)
return colorsys.hls_to_rgb(*hls_new) | bigcode/self-oss-instruct-sc2-concepts |
def recursive_length(item):
"""Recursively determine the total number of elements in nested list."""
if type(item) == list:
return sum(recursive_length(subitem) for subitem in item)
else:
return 1. | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def numeric_binary_search(ordered_numbers: List[int], search: int) -> int:
"""Simple numeric binary search
Args:
ordered_numbers(List[int]): an ordered list of numbers
search(int): number to find
Returns:
int: found index or -1
"""
assert isinstanc... | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_randints(lower, upper, exclude):
"""Generate a set of unique random numbers in a range (inclusive)."""
numbers = [i for i in range(lower, upper, 1)]
numbers.remove(exclude)
random.shuffle(numbers)
return numbers | bigcode/self-oss-instruct-sc2-concepts |
def knot_insertion_alpha(u, knotvector, span, idx, leg):
""" Computes :math:`\\alpha` coefficient for knot insertion algorithm.
:param u: knot
:type u: float
:param knotvector: knot vector
:type knotvector: tuple
:param span: knot span
:type span: int
:param idx: index value (degree-dep... | bigcode/self-oss-instruct-sc2-concepts |
def pearsonchisquare(counts):
"""
Calculate Pearson's χ² (chi square) test for an array of bytes.
See [http://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
#Discrete_uniform_distribution]
Arguments:
counts: Numpy array of counts.
Returns:
χ² value
"""
np = sum(cou... | bigcode/self-oss-instruct-sc2-concepts |
def common_shape(imgs, axis):
"""
Find smallest height or width of all images.
The value along `axis` will be `None`, the other will be
the smallest of all values
Args:
imgs (list[np.array]): list of images
axis (int): axis images will be concatenated along
Returns:
tup... | bigcode/self-oss-instruct-sc2-concepts |
def convert_image(img, coefs):
"""Sum up image channels with weights from coefs array
input:
img -- 3-d numpy array (H x W x 3)
coefs -- 1-d numpy array (length 3)
output:
img -- 2-d numpy array
Not vectorized implementation.
"""
x = img.shape[0]
y = img.shape[1]
re... | bigcode/self-oss-instruct-sc2-concepts |
def build_context(query, query_config):
"""Build context based on query config for plugin_runner.
Why not pass QueryExecConfig to plugins directly?
Args:
query (str)
query_config (QueryExecConfig)
Returns:
dict str -> str
"""
context = vars(query_config)
context['query'] = query
return c... | bigcode/self-oss-instruct-sc2-concepts |
def index_to_coordinates(string, index):
""" Returns the corresponding tuple (line, column) of the character at the given index of the given string.
"""
if index < 0:
index = index % len(string)
sp = string[:index+1].splitlines(keepends=True)
return len(sp), len(sp[-1]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def binary_str_to_decimal(chars: Iterable[str]) -> int:
"""
Converts binary string to decimal number.
>>> binary_str_to_decimal(['1', '0', '1'])
5
>>> binary_str_to_decimal('101010')
42
"""
return int("".join(chars), base=2) | bigcode/self-oss-instruct-sc2-concepts |
def mean(num_list):
"""
Return the average of a list of number. Return 0.0 if empty list.
"""
if not num_list:
return 0.0
else:
return sum(num_list) / float(len(num_list)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def cnvt_to_var_name(s):
"""Convert a string to a legal Python variable name and return it."""
return re.sub(r"\W|^(?=\d)", "_", s) | bigcode/self-oss-instruct-sc2-concepts |
def quick_sort(collection: list) -> list:
"""
A pure Python implementation of quick sort algorithm
:param collection: a mutable collection of comparable items
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> quick_sort([])
... | bigcode/self-oss-instruct-sc2-concepts |
def pow2(x):
"""Return the square of x
:param float x: input value
:rtype: float
"""
return x*x | 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.