seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_version(name: str, version: str) -> str:
"""
Get the version of a script.
Parameters
----------
name : str
Name of the script.
version : str
Version of the script, in format major.minor.patch.
Returns
-------
str
Script's version.
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
def tag_dictkeys(tag, dictionary):
"""Return the dictionary with tagged keys of the form 'tag.key'"""
tagged = {}
for key, val in dictionary.items():
tagged[tag+'.'+key] = val
return tagged | bigcode/self-oss-instruct-sc2-concepts |
def sort_tuple(tup, n=2):
"""Sort a tuple by the first n values
tup: tuple
input tuple
n : int
values to sort tuple by (default is 2)
Returns
-------
tup : tuple
tuple sorted by the first n values
"""
return tuple(sorted(tup, key=lambda t: t[:n])) | bigcode/self-oss-instruct-sc2-concepts |
def check_description(description, title):
"""
Verifies that the description is within the specified bounds
(20 < x < 20000) and that the description is longer than the
inputted title.
:param description: product description
:param title: product title
:return: True if the description meets... | bigcode/self-oss-instruct-sc2-concepts |
def get_strings(public, private):
"""
Get the string values for a public and private key.
:param public: Public key to convert
:param private: Private key to convert
:type public: rsa.PublicKey
:type private: rsa.PrivateKey
:returns: a tuple (str, str)
:rtype: tuple
"""
retur... | bigcode/self-oss-instruct-sc2-concepts |
def upload_media(request, form_cls, up_file_callback, instance=None, **kwargs):
"""
Uploads media files and returns a list with information about each media:
name, url, thumbnail_url, width, height.
Args:
* request object
* form class, used to instantiate and validate form for upload
* call... | bigcode/self-oss-instruct-sc2-concepts |
def Split_Dataset_B_Res(sub, feature, label, channels):
"""
Split one subject's data to evaluate the results of LOSO-CV on Dataset B.
Args:
sub: leave one subject out.
feature: input fNIRS signals.
label: input fNIRS labels.
channels: fNIRS channels.
Returns:
X_... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_parent_compseg_or_ted_uid(tixi3, xpath):
"""
Finds the uid of the nearest parent which is a component segment or trailing edge device
:param tixi3: TiXI 3 handle
:param xpath: XPath of the element to start the search
"""
end = [it.end() for it in re.finditer('(componentSegmen... | bigcode/self-oss-instruct-sc2-concepts |
def _float(value: str) -> float:
"""Convert string to float value
Convert a string to a floating point number (including, e.g. -0.5960D-01). Whitespace or empty value is set to 0.0.
Args:
value: string value
Returns:
Float value
"""
if value.isspace() or not value:
r... | bigcode/self-oss-instruct-sc2-concepts |
def task_wrapper(task):
"""Task wrapper for multithread_func
Args:
task[0]: function to be wrapped.
task[1]: function args.
Returns:
Return value of wrapped function call.
"""
func = task[0]
params = task[1]
return func(*params) | bigcode/self-oss-instruct-sc2-concepts |
def escape_for_sql_like(string):
"""Function that escapes % or _ symbols provided by user
SQL LIKE syntax summary:
- ``%`` -> match any number of characters
- ``_`` -> match exactly one character
"""
return string.replace('%', '\\%').replace('_', '\\_') | bigcode/self-oss-instruct-sc2-concepts |
import json
import re
def dict_to_jsonl(dict_input):
"""
takes a dict object and turns it into a jsonl doc
"""
jsonl_contents = json.dumps(dict_input)
jsonl_contents = re.sub(f"\n","",jsonl_contents)
return jsonl_contents | bigcode/self-oss-instruct-sc2-concepts |
def parse_desc(tokens):
"""
>>> parse_desc(Tokenizer("0 01BWA Helix Collective 000000Payroll31Mar310315 "))
{'FinancialInstitutionName': 'BWA', 'ProcessDate': '310315', 'ApcaNumber': 0, 'GeneratedBy': 'Helix Collective', 'EntriesD... | bigcode/self-oss-instruct-sc2-concepts |
def addListsElementWise(a, b):
"""Add corresponding elements of two lists.
The two lists do not have to have the same length. Nonexisting elements are assumed to have a value of 0.
A new list is constructed and returned.
"""
if len(b) > len(a):
a, b = b, a
# Now len(a) >= len(b)
r =... | bigcode/self-oss-instruct-sc2-concepts |
def merge_two_dicts(dict1, dict2):
"""
Merges two dictionaries into one
:param dict1: First dictionary to merge
:param dict2: Second dictionary to merge
:return: Merged dictionary
"""
merged_dict = dict1.copy()
merged_dict.update(dict2)
return merged_dict | bigcode/self-oss-instruct-sc2-concepts |
def pretty_tree(x, kids, show):
"""Return a pseudo-graphic tree representation of the object `x` similar to the
`tree` command in Unix.
Type: `(T, Callable[[T], List[T]], Callable[[T], str]) -> str`
It applies the parameter `show` (which is a function of type `(T) -> str`) to get a
textual represe... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def is_f_contig(tensor: torch.Tensor, strict: bool = False) -> bool:
"""Check if a pytorch Tensor is column-contiguous (Fortran order)
Column-contiguity means that the stride of the first dimension (of
a 2D tensor) must be equal to 1.
In case of 1D tensors we just check contiguity
P... | bigcode/self-oss-instruct-sc2-concepts |
def _find_machine(oneandone_conn, instance):
"""
Validates that the machine exists whether by ID or name.
Returns the machine if one was found.
"""
for _machine in oneandone_conn.list_servers(per_page=1000):
if instance in (_machine['id'], _machine['name']):
return _machine | bigcode/self-oss-instruct-sc2-concepts |
def extract_user(event):
"""
:param event: (required) the event from the request
:return: The username of the user who made the request
"""
return event["requestContext"]["authorizer"]["claims"]["cognito:username"] | bigcode/self-oss-instruct-sc2-concepts |
def _bool(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean] | bigcode/self-oss-instruct-sc2-concepts |
def make_s3_key_path(job_config, course = None, filename = None, session = None, mode = None, job_id = None):
"""
Create a key path following MORF's subdirectory organization and any non-null parameters provided.
:param job_config: MorfJobConfig object.
:param course: course slug (string).
:param fi... | bigcode/self-oss-instruct-sc2-concepts |
def get_rare_elements_number(d, n):
"""
Count the number of rare elements
:param d: dictionary to use
:param n: the threshold for rarity
:return: the number of rare elements as a string
"""
i = 0
for k, v in d.items():
if v < n:
i += 1
return str(i) | bigcode/self-oss-instruct-sc2-concepts |
def no_by_per(totalhp, percentage):
"""
rtype: num of `percentage` from total
eg: 1000, 10 -> 10% of 1000 (100)
"""
return totalhp * percentage / 100 | bigcode/self-oss-instruct-sc2-concepts |
def relative_error(U, V, product=None):
"""Compute error between U and V relative to norm of U."""
return (U - V).norm(product) / U.norm(product) | bigcode/self-oss-instruct-sc2-concepts |
def ifg_dates_dc_to_cum(ifg_dates):
"""Given the names of the daisy chain of interfergorams, find the names of the cumulative ones relative to the first acquisition.
Inputs:
ifg_dates | list | names of daisy chain ifgs, in form YYYYMMDD_YYYYMMDD
Returns:
ifg_dates_cum | list | names of cum... | bigcode/self-oss-instruct-sc2-concepts |
def is_none_p(value):
"""Return True if value is None"""
print("is_none_p", value)
return value is None | bigcode/self-oss-instruct-sc2-concepts |
def trend(series, n):
"""Return the running average, minimum and maximum of a series for an n-
element moving window."""
meanvals = []
minvals = []
maxvals = []
running = []
for val in series:
running.append(val)
if len(running) > n:
running.pop(0)
meanval... | bigcode/self-oss-instruct-sc2-concepts |
def isWild(card, wild_numbers):
"""returns true if a card is a wild"""
if card.number in wild_numbers:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def check_string(string: str, chars: list) -> bool:
"""
Returns True if one element of chars is in the string.
:param string: String to check.
:param chars: list of strings to check if one of it is in the string.
:return: bool
"""
return any((char in string) for char in chars) | bigcode/self-oss-instruct-sc2-concepts |
def percentage(value, refer_to):
"""Return the percentage of the reference value, or the value unchanged.
``refer_to`` is the length for 100%. If ``refer_to`` is not a number, it
just replaces percentages.
"""
if value is None or value == 'auto':
return value
elif value.unit == 'px':
... | bigcode/self-oss-instruct-sc2-concepts |
def validate_slug(slug, digits=8):
"""
Return true if a slug is a string and has the correct number of digits.
"""
return isinstance(slug, str) and len(slug) == digits | bigcode/self-oss-instruct-sc2-concepts |
def flat_eq(x, y):
"""
Emulate MATLAB's assignment of the form
x(:) = y
"""
z = x.reshape(1, -1)
z = y
return z.reshape(x.shape) | bigcode/self-oss-instruct-sc2-concepts |
def is_select(status):
"""Returns true if the first word in status is 'select'."""
if not status:
return False
return status.split(None, 1)[0].lower() == "select" | bigcode/self-oss-instruct-sc2-concepts |
def assoc_in(d, keys, value, factory = dict):
""" Update value in a (potentially) nested dictionary
This function was inspired by toolz.update_in and adopted for bazel.
Source:
https://github.com/pytoolz/toolz/blob/master/toolz/dicttoolz.py
Args:
d: dictionary on which to operate
... | bigcode/self-oss-instruct-sc2-concepts |
def add_group(groups_collection, group_name):
"""Adds a new group to the groups collection if it doesn't already exit
:param groups_collection: Mongo collection that maintains groups
:param group_name: Name of group to be added
:return: ObjectID of new group
:return: None if group already exists
... | bigcode/self-oss-instruct-sc2-concepts |
def file_get_contents(filename):
"""
Returns file contents as a string.
"""
with open(filename) as file:
return file.read() | bigcode/self-oss-instruct-sc2-concepts |
def is_contained(a, b): # Multiset: a < b
""" bool: True if list a is fully contained in list b. """
b = b[:]
try:
[b.remove(s) for s in a]
except ValueError as err:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def index_dependent_values(self, chromosome):
"""Test of the GA's ability to improve fitness when the value is index-dependent.
If a gene is equal to its index in the chromosome + 1, fitness is incremented.
"""
# Overall fitness value
fitness = 0
for i, gene in enumerate(chromosome):
... | bigcode/self-oss-instruct-sc2-concepts |
def manhattan_dist(c1, c2):
"""
Compute Manhattan distance between two coordinates
"""
return abs(c1[0] - c2[0]) + abs(c1[1] - c2[1]) + abs(c1[2] - c2[2]) | bigcode/self-oss-instruct-sc2-concepts |
import importlib
import pkgutil
def _walk_modules(path):
"""
Loads a module and all its submodules from the given module path and
returns them. If *any* module throws an exception while importing, that
exception is thrown back.
"""
# Support for namespace packages is added. See PEP 420.
#... | bigcode/self-oss-instruct-sc2-concepts |
def child_fun(current_person):
"""This function checks whether the person has a child or not and works
accordingly.
Parameters:
current_person:
The current Person object.
Returns:
The picked child number and the children list as a tuple.
"""
ch_lst = current_person.get_chil... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Pattern
def _match_root(root, name):
"""
Args:
root (str or re.Pattern): Root.
name (str): File URL or path.
Returns:
bool: True if match.
"""
return (isinstance(root, Pattern) and root.match(name)) or (
not isinstance(root, Pattern) and name.st... | bigcode/self-oss-instruct-sc2-concepts |
def fate_lr_decay(initial_lr, lr_decay, epochs):
""" FATE's learning rate decay equation
Args:
initial_lr (float): Initial learning rate specified
lr_decay (float): Scaling factor for Learning rate
epochs (int): No. of epochs that have passed
Returns:
Scaled... | bigcode/self-oss-instruct-sc2-concepts |
def bin2state(bin, num_bins, limits):
"""
:param bin: index in the discretization
:param num_bins: the total number of bins in the discretization
:param limits: 2 x d ndarray, where row[0] is a row vector of the lower
limit of each discrete dimension, and row[1] are corresponding upper
l... | bigcode/self-oss-instruct-sc2-concepts |
def board_full(board):
"""
Utility function that returns True if the given board is full and False otherwise
Arg board: board - the board you want to check
"""
for row in board:
for piece in row:
if piece == '*': return False;
return True; | bigcode/self-oss-instruct-sc2-concepts |
def always_reversible(iterable):
"""An extension of :func:`reversed` that supports all iterables, not
just those which implement the ``Reversible`` or ``Sequence`` protocols.
>>> print(*always_reversible(x for x in range(3)))
2 1 0
If the iterable is already reversible, this function retur... | bigcode/self-oss-instruct-sc2-concepts |
def assert_single_element(iterable):
"""Get the single element of `iterable`, or raise an error.
:raise: :class:`StopIteration` if there is no element.
:raise: :class:`ValueError` if there is more than one element.
"""
it = iter(iterable)
first_item = next(it)
try:
next(it)
except StopIteration:
... | bigcode/self-oss-instruct-sc2-concepts |
def fasta_split(fasta_str):
"""
Splits a fasta file like:
>sp|P10636|TAU_HUMAN Microtubule-associated protein tau OS=Homo sapiens OX=9606 GN=MAPT PE=1 SV=5
MAEPRQEFEVMEDHAGTYG
SPRHLSNVSST
>ANOTHER_TAU_HUMAN Microtubule-associated protein tau OS=Homo sapiens OX=9606 GN=MAPT PE=1 S... | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_string(length=255, extra_chars=''):
""" Generate a random string of characters.
:param length: Length of generated string.
:param extra_chars: Additional characters to include in generated
string.
"""
chars = string.ascii_letters + extra_chars
re... | bigcode/self-oss-instruct-sc2-concepts |
import time
def timer(input_func):
""" returns the execution time of a function wrapped by this decorator"""
def timed(*args, **kwargs):
start_time = time.time()
result = input_func(*args, **kwargs)
end_time = time.time()
print("{0} took {1:0.5f} secs".format(input_func.__name_... | bigcode/self-oss-instruct-sc2-concepts |
def scan_file(classifier, location):
"""
Run a license and copyright scan on file at `location`,
using golicense-classifier.
Parameters
----------
classifier : LicenseClassifier()
`LicenseClassifier` instance for scanning files
location : str
Location of the file
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def get_line(sample):
"""Build a list of relevant data to be printed.
Args:
sample (dict): an object from project samples
Returns:
list(str): list of relevant data to be printed
"""
return "\t".join(
[
sample.last_status.created.isoformat(),
str(samp... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_host_list(list_of_hosts):
"""Parse the comma separated list of hosts."""
p = set(
m.group(1) for m in re.finditer("\s*([^,\s]+)\s*,?\s*", list_of_hosts))
return p | bigcode/self-oss-instruct-sc2-concepts |
def inv_ensure_4d(x, n_dims):
"""Remove excess dims, inverse of ensure_4d() function."""
if n_dims == 2:
return x[:, 0, 0, :]
if n_dims == 3:
return x[:, :, 0, :]
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
def posix_invocations(trace_graph):
"""Return number of total POSIX API invokations"""
return sum(map(lambda x: x[1], trace_graph.full_paths_dict.items())) | bigcode/self-oss-instruct-sc2-concepts |
async def mistyversion_header(request, handler):
"""Add Misty-Command-Version header
"""
response = await handler(request)
response.headers['Misty-Command-Version'] = 'Current'
return response | bigcode/self-oss-instruct-sc2-concepts |
def labels_to_generate(epitope_files, ppi_files):
"""
Takes 2 lists of files and extracts the chains for which to generate labels.
"""
all_files = epitope_files + ppi_files
chains = []
for f in all_files:
chain = f.split('.')[0].split('_')[-1]
if not chain in chains:
... | bigcode/self-oss-instruct-sc2-concepts |
def elliptic_range(num_pages, current):
"""
Produce a list of numbers from 1 to num_pages and including current.
Long runs of successive numbers will be replaced by "...".
"""
def gap(start, stop):
if stop - start < 3:
return range(start, stop)
return ["..."]
ret = []... | bigcode/self-oss-instruct-sc2-concepts |
def dd_valley_value_map_nb(record, ts):
"""`map_func_nb` that returns valley value of a drawdown."""
return ts[record['valley_idx'], record['col']] | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def part_2(expenses: List[int]) -> int:
"""Find the three entries in expenses that sum to 2020 and return their product.
Args:
expenses: List of integer expense values.
Returns:
Integer product of three entries that sum to 2020.
"""
return {
a * b ... | bigcode/self-oss-instruct-sc2-concepts |
def _quote(data):
"""Prepare a string for quoting for DIGEST-MD5 challenge or response.
Don't add the quotes, only escape '"' and "\\" with backslashes.
:Parameters:
- `data`: a raw string.
:Types:
- `data`: `bytes`
:return: `data` with '"' and "\\" escaped using "\\".
:return... | bigcode/self-oss-instruct-sc2-concepts |
import math
def velocities(course, vel):
"""
Converts target velocities from course and modulus
to vector components Vx and Vy
:param course: target course
:param vel: modulus of target velocity
:return: Vector components Vx and Vy
"""
return round(vel * math.cos(math.radians(course)),... | bigcode/self-oss-instruct-sc2-concepts |
def error_compatibility_score(h1_output_labels, h2_output_labels, expected_labels):
"""
The fraction of instances labeled incorrectly by h1 and h2
out of the total number of instances labeled incorrectly by h1.
Args:
h1_output_labels: A list of the labels outputted by the model h1.
h2_o... | bigcode/self-oss-instruct-sc2-concepts |
def is_json_metadata(text):
"""Is this a JSON metadata?"""
first_curly_bracket = text.find("{")
if first_curly_bracket < 0:
return False
first_equal_sign = text.find("=")
if first_equal_sign < 0:
return True
return first_curly_bracket < first_equal_sign | bigcode/self-oss-instruct-sc2-concepts |
def external_edges(graph, nbunch):
""" Get the edges external to a set of nodes """
return (edge for edge in graph.edges(nbunch) if any(node not in nbunch for node in edge)) | bigcode/self-oss-instruct-sc2-concepts |
def convert_sqlite_version(version):
"""
Return a version converted from the sqlite human version format to the
download version format.
For instance:
>>> convert_sqlite_version('3.36.0')
'3360000'
>>> convert_sqlite_version('3.36.0.2')
'3360002'
See also: https://www.sqlite.org/ve... | bigcode/self-oss-instruct-sc2-concepts |
def new_grid_size(grid, kernel_size, stride=1, padding=0):
""" Calculate new images size after convoling.
Function calculated the size of the grid after convoling an image or feature map. Used formula from:
https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Pa... | bigcode/self-oss-instruct-sc2-concepts |
def convert_timetable(start, end):
"""
Function to convert rows to time
:param start: Starting row number
:param end: Ending row number
:return: Tuple with all correct starting and ending times
"""
timetable = {
1: ("8:30", "9:20"),
2: ("9:20", "10:10"),
3: ("10:30",... | bigcode/self-oss-instruct-sc2-concepts |
def convert_tuples_to_bitstrings(tuples):
"""Given a set of measurement tuples, convert each to a little endian
string.
Args:
tuples (list of tuples): the measurement tuples
Returns:
A list of bitstrings
"""
# Convert from tuples to bitstrings
bitstrings = []
for tuple_i... | bigcode/self-oss-instruct-sc2-concepts |
def chunk(data, index):
"""
Split a string into two parts at the input index.
"""
return data[:index], data[index:] | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_complete_url(url):
"""
验证 url 是否完整
:param url:
:return:
"""
re_result = re.match("http.*", url)
if re_result is None:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_selection(population, fitness, eq):
"""
Selection of the best two candidates given fitness function
:param population: list of numpy array
:param fitness: function to fit
:param eq: params to fitness function
:return: tuple of two more promising individuals (numpy vect... | bigcode/self-oss-instruct-sc2-concepts |
def object_to_dict(xmp):
"""
Extracts all XMP data from a given XMPMeta instance organizing it into a
standard Python dictionary.
"""
dxmp = dict()
if not xmp:
return {}
for item in xmp:
if item[-1]['IS_SCHEMA']:
dxmp[item[0]] = []
else:
dxmp... | bigcode/self-oss-instruct-sc2-concepts |
def round_gls(gls, precision=None):
"""Returns genotype likelihoods rounded to the desired precision level.
Args:
gls: A list of floats. The input genotype likelihoods at any precision.
precision: Positive int. The number of places past the decimal point to
round to. If None, no rounding is performed... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def peer_save_path(current_path: pathlib.Path, append: str) -> pathlib.Path:
"""
get save path of concatenated result.
this path is peer to current prediction file and append string: <prd.name>_<append>.<suffix>
:param current_path: pathlib.Path: current prediction file Path object
... | bigcode/self-oss-instruct-sc2-concepts |
def mult(m, n):
"""
return the smallest multiple of m that is >= n
"""
return m * ((n+m-1) // m) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _tls_trailer_length(
data_length: int,
protocol: str,
cipher_suite: str,
) -> int:
"""Gets the length of the TLS trailer.
WinRM wrapping needs to split the trailer/header with the data but the
length of the trailer is dependent on the cipher suite that was negotiated.
On Win... | bigcode/self-oss-instruct-sc2-concepts |
def fix_alpha(with_alpha, without_alpha):
"""
Given two of the same image, one with an alpha channel and one without, add the alpha
channel back into the image without, and return it.
:param with_alpha:
:param without_alpha:
:return:
"""
alpha_added = with_alpha.copy()
alpha_added[:... | bigcode/self-oss-instruct-sc2-concepts |
def number_day_to_name_day(number):
"""
Receives a number where 0 is sunday and returns the name of the day
:param number:
:return:
"""
weekDay = {0: 'Domingo', 1: 'Segunda', 2: 'Terça', 3: 'Quarta', 4: 'Quinta', 5: 'Sexta', 6: 'Sábado', 7: 'Domingo'}
return weekDay[number] | bigcode/self-oss-instruct-sc2-concepts |
def get_color_commands(indices, colors):
"""Returns postscript coloring string given indices and colors.
- indices: base 1 index of color. NOT BASE 0.
- colors: color name corresponding to color name used to generate
color_map.
- indices and colors must be lists of the same... | bigcode/self-oss-instruct-sc2-concepts |
def is_subset(subset, set):
"""
Determines if 'subset' is a subset of 'set'
:param subset: The subset
:param set: The set
:return: True if 'subset' is a subset of 'set, False otherwise
"""
cpos = 0
for c in set:
if c == subset[cpos]:
cpos += 1 # Found the char
if cpos == le... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def deep_update_dict(first: Dict, other: Dict) -> Dict:
"""
Perform in place deep update of the first dictionary with the values of second
:param first: The dictionary to be updated
:param other: The dictionary to read the updated values
:return: A reference to first dictio... | bigcode/self-oss-instruct-sc2-concepts |
def get_lastkey(path, delimiter="/"):
"""
Return name of the rightmost fragment in path
"""
return path.split(delimiter)[-1] | bigcode/self-oss-instruct-sc2-concepts |
def getColor(isInside):
""" Returns color of points depending on if they're close to rect """
if isInside:
return 'green'
else:
return 'red' | bigcode/self-oss-instruct-sc2-concepts |
def _xml_escape(data):
"""Escape &, <, >, ", ', etc. in a string of data."""
# ampersand must be replaced first
from_symbols = '&><"\''
to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split())
for from_, to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
re... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _make_pretty_usage(infos):
"""
Makes the usage description pretty and returns a formatted string.
Expected input:
func(*) - ...
func(expr[, expr...]) - ...
Expected output:
<table class="table">
<thead>
<tr>
<th style="width:25%">Function</... | bigcode/self-oss-instruct-sc2-concepts |
def compute_II_fr(stretch,muscActivation,species):
""" Compute the firing rates of the II afferent fibers.
Uses the experimetnally derived model devloped by Prochazka (1999 (2)).
Keyword arguments:
stretch -- muscle stretch in mm.
muscActivation -- normalized muscle activation [0 , 1].
"""
bias = 80
xCoef = 1... | bigcode/self-oss-instruct-sc2-concepts |
def get_ep_next(ep_latest, ep_num):
"""
for provided episode name and number return which should be the next episode
Parameters
----------
ep_latest: string
the full name of the episode
ep_num: the current episode number
Returns
-------
: string
the name of the nex... | bigcode/self-oss-instruct-sc2-concepts |
def effective_prior(p_tar, c_miss, c_fa):
"""This function adjusts a given prior probability of target p_targ,
to incorporate the effects of a cost of miss, cmiss, and a cost of false-alarm, cfa.
Args:
p_tar: target prior
c_miss: cost of miss
c_fa: cost of false alarm
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import collections
def _get_odim_root_attributes(nch, grps):
"""Retrieve root attributes according CfRadial2 standard.
Parameters
----------
grps : dict
Dictionary of root hdf5 groups ('how', 'what', 'where')
Returns
-------
attrs : dict
Dictionary of root attributes
... | bigcode/self-oss-instruct-sc2-concepts |
def version_tuple(v):
"""Get an integer version tuple from a string."""
return tuple(map(int, (str(v).split(".")))) | bigcode/self-oss-instruct-sc2-concepts |
def norm(X, n=2):
"""Return the n-norm of vector X"""
return sum([x**n for x in X])**(1/n) | bigcode/self-oss-instruct-sc2-concepts |
def _in_chunks(seq, size):
"""
Return sequence in 'chunks' of size defined by size
"""
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) | bigcode/self-oss-instruct-sc2-concepts |
def coalesce(*fields, **kwargs):
"""
Return a function which accepts a row and returns the first non-missing
value from the specified fields. Intended for use with
:func:`petl.transform.basics.addfield`.
"""
missing = kwargs.get('missing', None)
default = kwargs.get('default', None)
de... | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_desc(rec):
"""
Parses annotations from a sequence description
"""
ann = {}
desc = rec.description
# Nothing to parse.
if rec.id == desc:
return ann, ''
# Attempts to split the description for parsing into JSON
payload = rec.description.split(" ", ma... | bigcode/self-oss-instruct-sc2-concepts |
def node(l, v, r, b):
"""Make an AVL tree node, consisting of a left tree, a value, a
right tree, and the "balance factor": the difference in lengths
between the right and left sides, respectively."""
return (l, v, r, b) | bigcode/self-oss-instruct-sc2-concepts |
def get_best_technical_set(df):
"""Identify set with greatest AUROC in dataframe.
Args:
df (pd Dataframe): must contain 'auroc_mean' and 'full_label'.
Returns:
best_set (str): label of best technical set.
"""
df = df.sort_values(by=['auroc_mean'], ascending=False,
... | bigcode/self-oss-instruct-sc2-concepts |
def uM_to_mgml(species_mws, species_concs, scale=1000000):
"""
Args:
species_mws: (dict) For example {'enzyme_1' : 33000, 'substrate_1' : 150}
species_concs: (dict) For example {'enzyme_1' : 10, 'substrate_1' : 10000}
scale: (int) The scale we are working on. 1=M, 1000=mM, 1000,000=uM.... | bigcode/self-oss-instruct-sc2-concepts |
def load(f):
"""
read a file into a string
"""
fh = open(f)
text = fh.read()
fh.close()
return text | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_params(f):
"""
Returns parameters and default values to class constructor
Example:
get_params(_classifier['RandomForestClassifier'])
>>
{'n_estimators': 100,
'criterion': 'gini',
...
'ccp_alpha': 0.0,
... | 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.