seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import logging
def validate_config(config):
"""
Validate the user's config. Any errors get logged. If there are 1 or more
errors, False is returned.
:param config: The configuration dictionary to validate
:return: Whether or not the number of errors in the config was 0
"""
expected_value... | bigcode/self-oss-instruct-sc2-concepts |
def not_valid(peer_id, doc_id):
"""
There are some summaries full of dashes '-' which are not easy to be handled
:param peer_id: The peer id of the author
:param doc_id: The id of corresponding document
:return: Bool True or False whether or not the summary is valid
"""
return True if (peer... | bigcode/self-oss-instruct-sc2-concepts |
def samplevar_dataset_to_varcope(samplevar_dataset, sample_size):
"""Convert "sample variance of the dataset" (variance of the individual
observations in a single sample) to "sampling variance" (variance of
sampling distribution for the parameter).
Parameters
----------
samplevar_dataset : arra... | bigcode/self-oss-instruct-sc2-concepts |
def get_pfcwd_config_attr(host_ans, config_scope, attr):
"""
Get PFC watchdog configuration attribute
Args:
host_ans: Ansible host instance of the device
config_scope (str): 'GLOBAL' or interface name
attr (str): config attribute name, e.g., 'detection_time'
Returns:
co... | bigcode/self-oss-instruct-sc2-concepts |
def __rename_column(df, old_name, new_name):
"""
Renames a column in a pandas dataframe
:param df: pandas dataframe
:param old_name:
:param new_name:
:return: data frame with renamed column
"""
return df.rename(index=str, columns={old_name: new_name}) | bigcode/self-oss-instruct-sc2-concepts |
import json
def translate_xiaomi_aqara_contact(topic, data, srv=None):
"""Translate the Xiaomi Aqara's contact sensor JSON data to a
human-readable description of whether it's open or closed."""
payload = json.loads(data["payload"])
if "contact" in payload:
if payload["contact"]:
r... | bigcode/self-oss-instruct-sc2-concepts |
def __repr__(self):
"""A custom repr for targetdb models.
By default it always prints pk, name, and label, if found. Models can
define they own ``__print_fields__`` as a list of field to be output in the
repr.
"""
fields = ['pk={0!r}'.format(self.pk)]
for ff in self.__print_fields__:
... | bigcode/self-oss-instruct-sc2-concepts |
def range_of_lst(lst):
"""
calculates the range of a given list
:param lst: list of numbers
:return: max-min
"""
return max(lst) - min(lst) | bigcode/self-oss-instruct-sc2-concepts |
def _seedOffsetForAlgo(tree, algo):
"""Internal function for returning a pair of indices for the beginning of seeds of a given 'algo', and the one-beyond-last index of the seeds."""
for ioffset, offset in enumerate(tree.see_offset):
if tree.see_algo[offset] == algo:
next_offset = tree.see_of... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def market_is_active(market: Dict) -> bool:
"""
Return True if the market is active.
"""
# "It's active, if the active flag isn't explicitly set to false. If it's missing or
# true then it's true. If it's undefined, then it's most likely true, but not 100% )"
# See http... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def navigate_part_one(commands: List[Tuple[str, int]]) -> Tuple[int, int]:
"""Navigate and return the horizontal position and depth."""
horizontal: int = 0
depth: int = 0
for command, units in commands:
if command == 'forward':
horiz... | bigcode/self-oss-instruct-sc2-concepts |
def is_child_uri(parent_uri: str, child_uri: str) -> bool:
"""Return True, if child_uri is a child of parent_uri.
This function accounts for the fact that '/a/b/c' and 'a/b/c/' are
children of '/a/b' (and also of '/a/b/').
Note that '/a/b/cd' is NOT a child of 'a/b/c'.
"""
return (
bool... | bigcode/self-oss-instruct-sc2-concepts |
def is_scalar(x):
"""
>>> is_scalar(1)
True
>>> is_scalar(1.1)
True
>>> is_scalar([1, 2, 3])
False
>>> is_scalar((1, 2, 3))
False
>>> is_scalar({'a': 1})
False
>>> is_scalar({1, 2, 3})
False
>>> is_scalar('spam')
True
"""
try:
len(x)
except... | bigcode/self-oss-instruct-sc2-concepts |
def format_generic_string(event_value, attribute):
"""
Creates a filter format string for a generic attribute.
:param str event_value: String that is used to generate the filter string.
:param str attribute: The attribute that is used in the filter.
:return: A string that can be used in a LQL filte... | bigcode/self-oss-instruct-sc2-concepts |
def _invert_dict(orig_dict):
"""
Inverting Python dictionary keys and values: Many to one --> One to many
Args:
- orig_dict: Dictionary desired to invert.
+ type: dict
Return:
- Inverted dictionary
+ type: dict
"""
return_dict = {}
for v, k in orig_dic... | bigcode/self-oss-instruct-sc2-concepts |
import time
def _expired(ts, lifetime=84600000):
"""
return True if a timestamp is considered expired
lifetime is default 23.5 hours
"""
return (int(time.time()) * 1000) - ts >= lifetime | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterator
from pathlib import Path
from typing import Optional
import re
def _filter_by_include_exclude(
notebooks: Iterator[Path],
include: Optional[str],
exclude: Optional[str],
) -> Iterator[str]:
"""
Include files which match include, exclude those matching exclude.
note... | bigcode/self-oss-instruct-sc2-concepts |
def undo_rescale_voxel_tensor(rescaled_voxel_tensor):
"""Takes a voxel tensor with values in [-1, 1] and rescales them to [0, 1].
Args:
rescaled_voxel_tensor: A single voxel tensor after rescaling (values in [-1, 1]).
Returns:
voxel_tensor: A single voxel tensor with values in [0, 1].
... | bigcode/self-oss-instruct-sc2-concepts |
def url_has_param(url, param):
"""Checks whether a URL contains specified parameter."""
url = str(url)
return any(x in url for x in [f'?{param}=', f'&{param}=']) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def ComputeMD5Hex(byte_str):
"""Compute MD5 hash of "byte_str" and return it encoded as hex string."""
hasher = hashlib.md5()
hasher.update(byte_str)
return hasher.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def initialized_coroutine(function):
"""Function decorator to automatically initialize a coroutine."""
def _wrapper(*args, **kw):
coroutine = function(*args, **kw)
coroutine.send(None)
return coroutine
return _wrapper | bigcode/self-oss-instruct-sc2-concepts |
def cdf_UPL(x, a, beta):
"""
Cumulative function for untruncated power law.
pdf(x) = (beta-1)/a * (a/x)^beta
for x >= a
"""
F = 1-(a/x)**(beta-1)
return F | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def get_log_marginal_joint(generative_model, guide, discrete_latent, obs, num_particles):
"""Estimate log p(z_d, x) using importance sampling
Args:
generative_model
guide
discrete_latent
[*discrete_shape, *shape, *dims]
OR
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _is_a_glob(a_string):
"""
Return True or False depending on whether a_string appears to be a glob
"""
pattern = re.compile(r'[\*\[\]\{\}\?]')
return bool(pattern.search(a_string)) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_hash_str(linking_identifier: str, salt_str: str) -> str:
"""
Given a string made of concatenated patient information, generate
a hash for this string to serve as a "unique" identifier for the
patient.
"""
hash_obj = hashlib.sha256()
to_encode = (linking_identifi... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def needed_columns_are_in_df(to_check: List, to_interrogate: List) -> bool:
"""
True if all of to_check values are in to_interrogate, else False
"""
if all(x in to_interrogate for x in to_check):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def take(items, indices):
"""
Selects a subset of a list based on a list of indices.
This is similar to np.take, but pure python.
Args:
items (list): an indexable object to select items from
indices (Sequence): sequence of indexing objects
Returns:
iter or scalar: subset o... | bigcode/self-oss-instruct-sc2-concepts |
def _getShapeSize(df, shape_name_str):
"""
Get the arbitrary shape size with its shape name.
Args:
df: tuple-(df_CompartmentData, df_NodeData, df_ReactionData, df_ArbitraryTextData, df_ArbitraryShapeData).
shape_name_str: str-the shape name.
Returns:
shape_size_list: list... | bigcode/self-oss-instruct-sc2-concepts |
def issubset(left, right):
"""A subset relation for dictionaries"""
return set(left.keys()) <= set(right.keys()) | bigcode/self-oss-instruct-sc2-concepts |
def full_house(dice):
"""
Score the dice based on rules for FULL_HOUSE.
"""
points = 0
dice.sort()
first = dice[0]
last = dice[-1]
num_first = dice.count(first)
num_last = dice.count(last)
if num_first >= 2 and num_last >= 2 and num_first + num_last == len(dice):
points =... | bigcode/self-oss-instruct-sc2-concepts |
def add_input_args(parser):
"""Add parser arguments for input options."""
parser.add_argument('--image', metavar='<image>', type=str, required=False, default='./doc/valid_test.png', help='Path of input image.')
parser.add_argument('--video', metavar='<video>', type=str, required=False, default='./doc/valid_... | bigcode/self-oss-instruct-sc2-concepts |
def uniq(dup_list):
"""Remove duplicated elements in a list and return a unique list
Example: [1,1,2,2,3,3] #=> [1,2,3]
"""
return list(set(dup_list)) | bigcode/self-oss-instruct-sc2-concepts |
import struct
def unpack_int(st):
"""unpack 2 bytes little endian to int"""
return int(struct.unpack('<h', st[0:2])[0]) | bigcode/self-oss-instruct-sc2-concepts |
import uuid
import re
def html_id_safe(text: str) -> str:
"""
Makes a string that can be made into an HTML id and referenced easily
"""
if not text:
return str(uuid.uuid4())
text = re.sub("[^0-9A-Za-z]", "-", text)
text = re.sub("_{2,}", "-", text)
if not text[0].isalpha():
... | bigcode/self-oss-instruct-sc2-concepts |
def getDim(scale,supercell):
"""
Helper function for to determine periodicity of a crystal, used in
various functions
inputs
--------
scale (float): The ratio of final and initial network size
supercell (int): The supercell size used to generate the new
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def _read_matrix_shape(file_path: str):
""" Reads and returns the shape (rows, columns) from the matrix stored in
the given file.
"""
with open(file_path, 'rb') as f:
rows = struct.unpack('<i', f.read(4))[0]
cols = struct.unpack('<i', f.read(4))[0]
return rows... | bigcode/self-oss-instruct-sc2-concepts |
def get_token_auth_header(request):
"""Obtains the Access Token from the Authorization Header
"""
auth = request.META.get("HTTP_AUTHORIZATION", None)
parts = auth.split()
token = parts[1]
return token | bigcode/self-oss-instruct-sc2-concepts |
def max_norm(p):
"""
Computes the max norm (infinity norm) of a polynomial.
:param p: the polynomial
:return: a tuple containing the monomial degrees of the largest coefficient and the coefficient
"""
max_degs = None
max_coeff = 0
for degs, coeff in p.dict().items():
if abs(coeff... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def build_param_error(name: str, value: Any, description: str) -> dict:
"""Return a dictionary describing a parameter error.
Can be used in build_error as detail.
Schema:
{
'parameter': {
'name': name of a parameter
'value': value of the paramete... | bigcode/self-oss-instruct-sc2-concepts |
def create_cluster_logical_device_ids(core_id, switch_id):
"""
Creates a logical device id and an OpenFlow datapath id that is unique
across the Voltha cluster.
The returned logical device id represents a 64 bits integer where the
lower 48 bits is the switch id and the upper 16 bits is the core id... | bigcode/self-oss-instruct-sc2-concepts |
def find_prime_factors(n):
"""Return prime factors of n"""
p_factors = []
current = n
test = 2
while test <= current:
if not current%test:
p_factors.append(test)
current = current // test
test = 2
else:
test += 1
return p_factors | bigcode/self-oss-instruct-sc2-concepts |
def parse_args(parser):
"""
Parse commandline arguments.
"""
parser.add_argument('-i', '--input-file', type=str, default="text.txt", help='full path to the input text (phareses separated by new line)')
parser.add_argument('-o', '--output', type=str, default="outputs", help='output folder to save aud... | bigcode/self-oss-instruct-sc2-concepts |
def fasta(sequences):
"""Builds a FASTA record of extracted sequences.
This function expects either a list of Synthase objects (mode='synthase')
or a dictionary of extracted domains, keyed on synthase header (mode='domains').
"""
# Entire Synthase objects were extracted
if isinstance(sequences,... | bigcode/self-oss-instruct-sc2-concepts |
def describe_humidity(humidity):
"""Convert relative humidity into wet/good/dry description."""
if 30 < humidity <= 75:
description = "good"
elif humidity > 75:
description = "wet"
else:
description = "dry"
return description | bigcode/self-oss-instruct-sc2-concepts |
def autoSize(image, resolution=1920):
"""Determines the size of an image by setting the largest side to the size of the resolution"""
if image.width >= image.height:
size = (resolution, round((resolution / image.width) * image.height))
else:
size = (round((resolution / image.height) * image.... | bigcode/self-oss-instruct-sc2-concepts |
def build_cgi_env(req):
"""
Utility function that returns a dictionary of
CGI environment variables as described in
http://hoohoo.ncsa.uiuc.edu/cgi/env.html
"""
req.add_cgi_vars()
env = req.subprocess_env.copy()
if req.path_info and len(req.path_info) > 0:
env["SCRIPT_NAME"] = ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def open_json(fname: str) -> dict:
"""open json story book and return as dict."""
with open(f"./data/json/{fname}.json", "r") as fh:
return json.load(fh) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Union
def fizzbuzz_list() -> List[Union[int, str]]:
"""Create a list 1-100
---
- Multiples of 3 and 5: FizzBuzz
- Multiples of 3: Fizz
- Multiples of 5: Buzz
- Else: integer
"""
out: List[Union[int, str]] = []
for i in range(100):
... | bigcode/self-oss-instruct-sc2-concepts |
def get_strand_bias(sample, variants):
"""Based on method 1 (SB) of Guo et al., 2012
If there a denominator would be 0, there is no valid result and this will
return None. This occurs when there are no reads on one of the strands, or
when there are no minor allele reads."""
# using same variable names as in p... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def string_contains_any_of_args(string: str, args: List[str]) -> bool:
"""
Return whether array contains any of a group of args.
:param string: String being checked.
:param args: Args being analyzed.
:return: True if any args are found in the string.
"""
return any... | bigcode/self-oss-instruct-sc2-concepts |
def additional_file(remote, local):
"""
Create step additional file
:param remote: the remote file of the additional file
:type remote: string
:param local: the local file of the additional file
:type local: string
:return:
:rtype map
"""
return {
'remote': remote,
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def check_sequential(
reference: List[str],
update: List[str]
) -> bool:
"""Helper to check if update continues sequence.
Helps to check if updated dates are all in sequence.
Args:
reference (List[str]): Reference list of dates to be updated.
updat... | bigcode/self-oss-instruct-sc2-concepts |
def test_equal_i(x0, x1):
""" Test for exact equality. """
return x0 == x1 | bigcode/self-oss-instruct-sc2-concepts |
def get_odds_desc(count):
"""
This method returns a list of the first 'count' odd numbers in descending
order. e.g count = 3 should return [5,3,1]
"""
return list(reversed(range(1,count*2,2))) | bigcode/self-oss-instruct-sc2-concepts |
def group_by(seq, f):
""" A proper groupby that doesn't require sorted input. Output is a dict,
rather than an interator
>>> group_by([1,2,3,4,5], mod_two)
{0: [2, 4], 1: [1, 3, 4]}
"""
ret = {}
[ret.setdefault(f(i), []).append(i) for i in seq]
return ret | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def config_item_list(value: str, convert=str) -> List[Any]:
"""
Convert a comma separated string into a list
"""
return [convert(x) for x in value.split(',')] | bigcode/self-oss-instruct-sc2-concepts |
def gen_key_refId(dashboardId, panelId, refId):
"""generate the key for finding the right sqlClient object,
using the given (dashboard, panel, sql-id)"""
return "-".join([str(dashboardId), str(panelId), refId]) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def fock_bin(n, k):
"""
Return all the possible :math:`n`-length binary where :math:`k` of :math:`n` digitals are set to 1.
Parameters
----------
n : int
Binary length :math:`n`.
k : int
How many digitals are set to be 1.
Returns
-------
res :... | bigcode/self-oss-instruct-sc2-concepts |
def make_mysql_url(username: str, password: str, dbname: str,
driver: str = "mysqldb", host: str = "localhost",
port: int = 3306, charset: str = "utf8") -> str:
"""
Makes an SQLAlchemy URL for a MySQL database.
"""
return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def get_duplicates(song_list):
"""Finds all duplicates in a list.
Args:
song_list: A list of "song by artist" strings which is the
return list of find_similar_songs.
Returns:
A list of all items found more than once in the input list.
"""
duplic... | bigcode/self-oss-instruct-sc2-concepts |
def get_attributes(obj, names):
"""Return attributes dictionary with keys from `names`.
Object is queried for each attribute name, if it doesn't have this
attribute, default value None will be returned.
>>> class Class:
... pass
>>> obj = Class()
>>> obj.attr = True
>>> obj.value =... | bigcode/self-oss-instruct-sc2-concepts |
def create_list_attr_operation(var_attribute_list_name):
"""Return request string for a single operation to create an attribute of type array/list."""
return '{"op":"CreateAttributeValueList","attributeName":"' + var_attribute_list_name + '"},' | bigcode/self-oss-instruct-sc2-concepts |
def get_value_str(value, type_val):
"""Convert the value from the csv file to the correct str according to the type
Parameters
----------
value : str
value to convert
type_val : str
Type to convert to
Returns
-------
value : str
Value updated to match the type
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def count_ngrams(text, n):
"""
:param text: text
:param n: n of n-gram
:return: Counter objects for n-grams in the text
"""
ngrams = [text[i:i + n] for i in range(len(text) - n)]
return Counter(ngrams) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def format_generated_timestamp(dt: datetime) -> str:
"""Return standard phrase for the date and time the report is generated"""
dt_as_text = dt.astimezone().strftime('%c %Z')
return f"generated on {dt_as_text}" | bigcode/self-oss-instruct-sc2-concepts |
def remove_header_lines(lines):
"""Return list of lines without the header."""
lines = lines[2:]
if lines and lines[0] == "\n":
lines = lines[1:]
return lines | bigcode/self-oss-instruct-sc2-concepts |
def get_digits(s):
"""
Get digits in the given string, cast to int
:param s: input string
:return: int from string
"""
return int(''.join([c for c in s if c.isdigit()])) | bigcode/self-oss-instruct-sc2-concepts |
def concat_strings(string_list):
"""
Concatenate all the strings in possibly-nested string_list.
@param list[str]|str string_list: string(s) to concatenate
@rtype: str
>>> list_ = 'cat'
>>> concat_strings(list_)
'cat'
>>> list_ = ['cat', 'dog']
>>> concat_strings(list_)
'catdog... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def pad_tokens(tokens: List[List[int]], pad_value: int = 0) -> List[List[int]]:
"""pad a batch of tokens to fixed maximum lengh using `pad_value`.
Args:
tokens: list of list of tokens of varying lengths.
pad_value: padding value. Defaults to 0.
Example:
>>... | bigcode/self-oss-instruct-sc2-concepts |
def is_url(checkpoint):
"""Check whether the checkpoint is a url or not.
"""
is_url = ('https://storage.googleapis.com' in checkpoint)
return is_url | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
import copy
def create_lookup_table(
list_of_dicts: List[Dict[str, Any]], lookup_key
) -> Dict[str, List[Any]]:
""" Takes a list of dictionaries and converts it into a dictionary of dictionaries indexed by a specified key"""
payload =... | bigcode/self-oss-instruct-sc2-concepts |
import typing
def get_owner_and_repo(location: str) -> typing.Tuple[str, str]:
"""
Get the owner and repo name from a location string.
Parameters
----------
location : str
The location string.
Returns
-------
owner : str
The owner of the repo.
repo : str
T... | bigcode/self-oss-instruct-sc2-concepts |
def remove_invalid(string: str) -> str:
"""
Removes characters that Windows doesn't allow in filenames from the specified string
:param s: string to remove characters from
:return: the given string without invalid characters
"""
string = string.replace('"', "'")
for invalid_char in ["\\", "/... | bigcode/self-oss-instruct-sc2-concepts |
def extract_pathnames_from_log(filename, prefix_filter=""):
"""
Returns a list of pathnames from a GEOS-Chem log file.
This can be used to get a list of files that should be
downloaded from gcgrid or from Amazon S3.
Args:
-----
filename : str
GEOS-Chem standard log file
... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_table_cell(col, x):
"""
Parse 1 table cell. If col is 0, left margin - 1 should be kept for hierarchical data.
:param col: col index
:param x: data in cell
:return: int, float or str
"""
try:
return int(x)
except ValueError:
pass
try:
return float(x... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Any
from typing import Tuple
import itertools
def pairwise(iterable: Iterable[Any],
zip_function=itertools.zip_longest, **kwargs) -> Iterable[Tuple[Any, Any]]:
"""s -> (s0,s1), (s1,s2), (s2, s3), ...
Args:
iterable: Iterable to iterate over ... | bigcode/self-oss-instruct-sc2-concepts |
def feats_at_batch(stensor, batch_id):
"""get features of sparse tensor at batch id
Args:
- tensor (Sparse Tensor)
- batch_id (int)
Returns:
- (Tensor)
"""
mask = stensor.indices[:, 0] == batch_id
return stensor.features[mask] | bigcode/self-oss-instruct-sc2-concepts |
def remove_comment_lines(a):
"""Return a copy of array with comments removed.
Lines starting with '--' (but not with '---') are removed.
"""
r = []
for s in a:
if s.strip().startswith('--') and not s.strip().startswith('---'):
pass
else:
r.append(s)
retur... | bigcode/self-oss-instruct-sc2-concepts |
def get_event_id(reading_path):
"""
Returns events ids from specified REA file
:param reading_path: path to REA file
:return: event ID
"""
with open(reading_path) as file:
for line in file:
line = line.strip()
if len(line) > 73:
title = line[0:6]
... | bigcode/self-oss-instruct-sc2-concepts |
def base_lm(hparams):
"""Adds base hparams for LM."""
# Language model.
hparams.add_hparam("lm_type", "left2right")
hparams.add_hparam("lm_num_layers", 2)
hparams.add_hparam("lm_num_residual_layers", 1)
# Language model training and loss.
hparams.add_hparam("lm_do_train", False)
hparams.add_hparam("lm... | bigcode/self-oss-instruct-sc2-concepts |
def _safe_get(obj, key, default=None):
"""This acts like obj.get(key, default), except that if obj[key] exists but
is None, we still return default rather than the accessed result. Also, if
obj happens to be None, we return default rather than raising an exception.
To see the difference, suppose obj = ... | bigcode/self-oss-instruct-sc2-concepts |
def edit_distance(word1, word2, sequence_type, max_distance = None):
"""Returns the Levenshtein edit distance between a string from
two words word1 and word2, code drawn from
http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python.
The number is the number of operations... | bigcode/self-oss-instruct-sc2-concepts |
def is_comment(line: str) -> bool:
"""
Return True if the given line is a comment, False otherwise.
"""
return line.startswith('#') | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_numeric_gradient(f, x, dLdf=None, h=1e-7):
"""
Compute the numeric gradient of f at x using a finite differences
approximation. We use the centered difference:
df f(x + h) - f(x - h)
-- ~= -------------------
dx 2 * h
Function can also expand this ea... | bigcode/self-oss-instruct-sc2-concepts |
def find_similar_chars_n(str1, str2):
"""Returns a string containing only the characters found in both strings
Complexity: O(N)
"""
return ''.join(sorted([char1 for char1 in str1 if char1 in str2])) | bigcode/self-oss-instruct-sc2-concepts |
def Btu_lbR2Wh_kgK(x): # By mass
"""Btu/(lbm-R) -> Wh/(kg-K)"""
return 1.1632*x | bigcode/self-oss-instruct-sc2-concepts |
def get_all_predecessors(graph, node, start_node=0):
"""
Find all predecessor nodes of node in graph, given the
start_node.
Parameters
----------
graph: nx.DiGraph
node: abc.hashable
start_node: abc.hashable
"""
predecessors = [node]
while True:
pre_node = list(graph... | bigcode/self-oss-instruct-sc2-concepts |
def kelvin2celsius(kelvin):
"""
Convert temperature in degrees Kelvin to degrees Celsius.
:param kelvin: Degrees Kelvin
:return: Degrees Celsius
:rtype: float
"""
return kelvin - 273.15 | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
import click
def calculate_file_md5(filepath, blocksize=2 ** 20):
"""Calculate an MD5 hash for a file."""
checksum = hashlib.md5()
with click.open_file(filepath, "rb") as f:
def update_chunk():
"""Add chunk to checksum."""
buf = f.read(blocksize)
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def pretty(event):
"""Prettify an event for printing.
:param event: Dictionary of Eiffel event.
:type event: dict
:return: Preffy json string.
:rtype: str
"""
return json.dumps(event, indent=4, sort_keys=True) | bigcode/self-oss-instruct-sc2-concepts |
def payoff_lotto(x, y):
"""
Returns tuple of normalized (sum == 1) values of (losses, draws, wins).
"""
losses, draws, wins = 0, 0, 0
for x_i in x:
for y_i in y:
if x_i < y_i:
losses += 1
elif x_i == y_i:
draws += 1
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def subtract_one(n):
"""Subtracts 1 from n
>>> subtract_one(5)
4
>>> subtract_one(3)
2
"""
return n-1 | bigcode/self-oss-instruct-sc2-concepts |
def agwEnglishPlural(string, numOf, suffix="s"):
"""You pass in a string like "squid" and a number
indicating how many squid there are. If the number
is one, then "squid" is returned, otherwise "squids"
is returned."""
if 1 == numOf:
return string
else:
return string + suffix
... | bigcode/self-oss-instruct-sc2-concepts |
def nist_num(nist_data):
"""Converts a NIST style data point to a point.
Parameters
----------
nist_data : str
A nist data point.
Returns
-------
d : float or complex
a data point.
"""
nd = nist_data
while ('(' in nd) or (')' in nd):
nd_pre = nd.partiti... | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def rgb2hsv(rgb):
"""Convert a 4-d RGB tensor to the HSV counterpart.
Here, we compute hue using atan2() based on the definition in [1],
instead of using the common lookup table approach as in [2, 3].
Those values agree when the angle is a multiple of 30°,
otherwise they m... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(x, y):
"""A function to merge two dictionaries, making it easier for us to make modality specific queries
for dwi images (since they have variable extensions due to having an nii.gz, bval, and bvec file)
Parameters
----------
x : dict
dictionary you want merged with y
... | bigcode/self-oss-instruct-sc2-concepts |
import locale
def cell_format(data):
"""Formats the data to put in a table cell."""
if isinstance(data, int):
# Add commas to integers.
return locale.format_string("%d", data, grouping=True)
elif isinstance(data, float):
# Add commas to floats, and round to 2 decimal places.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_lock_status_flags(lock_status_value):
"""
Decode a lock status value provided as a hex string (like '0880'),
returning an array of strings representing the parsed bits into
textual described flags.
"""
flags = []
try:
status_value = bytearray.fromhex(lock_status_value)
if not status_value:... | bigcode/self-oss-instruct-sc2-concepts |
def follows(trace, distance=1):
"""Returns a mapping (aka. dict) from pairs of activities to frequency.
A pair (a, b) is part of the mapping if activity b directly follows activity a,
in any of the traces.
Parameters
----------
distance: int
Distance two activities have to be appart to ... | bigcode/self-oss-instruct-sc2-concepts |
def get_kqshift(ngkpt, kshift, qshift):
"""Add an absolute qshift to a relative kshift."""
kqshiftk = [ kshift[i] + qshift[i] * ngkpt[i] for i in range(3) ]
return kqshiftk | 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.