seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def latest_date_between(date_1, date_2):
"""Utility function to compare the dates and return latest date."""
if date_1 > date_2:
return date_1
else:
return date_2 | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_random_input(seed, n):
"""Generates a list with n uint8 numbers."""
random.seed(a=seed)
return [random.randint(0, 255) for _ in range(n)] | bigcode/self-oss-instruct-sc2-concepts |
import typing
def _assert_str(item: typing.Any) -> str:
"""Check that item is a string."""
assert isinstance(item, str)
return item | bigcode/self-oss-instruct-sc2-concepts |
def create_GAN_hparams(generator_hidden_layers=[30, 30], discriminator_hidden_layers=[30, 30], learning_rate=None,
epochs=100, batch_size=32, activation='relu',
optimizer='Adam', loss='mse', patience=4, reg_term=0, generator_dropout=0,
discriminator_d... | bigcode/self-oss-instruct-sc2-concepts |
def acid_installed(request):
"""
Acid is installed.
Args:
request: Pytest request.
Returns:
bool: Acid installed
"""
return request.config.getoption("--installed") | bigcode/self-oss-instruct-sc2-concepts |
def sindex(string, row, col):
"""Get index of the character at `row`/`col` in `string`.
:Parameters:
- `row`: row number, starting at 1.
- `col`: column number, starting at 1.
:Returns: ``i``, starting at 0 (but may be <1 if row/col<0)
:Note: This works for text-strings with '\... | bigcode/self-oss-instruct-sc2-concepts |
def mag_cut(mag, low, high):
"""
Define a high and low value and flag the
values that fall within those boundaries
"""
isGood = 0
if mag <= high and mag >= low:
isGood = 1
return isGood | bigcode/self-oss-instruct-sc2-concepts |
def find_integer(f):
"""Finds a (hopefully large) integer such that f(n) is True and f(n + 1) is
False.
f(0) is assumed to be True and will not be checked.
"""
# We first do a linear scan over the small numbers and only start to do
# anything intelligent if f(4) is true. This is because it's ve... | bigcode/self-oss-instruct-sc2-concepts |
def format_table_row_single(lbl, label, value):
""" Format table row string representing a single value (two cells:
label, value)
Input:
- lbl: Short/abbreviated label string
- label: Full label string
- value: Value at specified label (type agnostic)
Output: String to be used ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _remove_multiple_spaces(text: str) -> str:
"""Remove multiple white spaces.
e.g. "The koala is angry !"
Args:
text (str): The text.
Returns:
str: CLeaned text.
"""
return re.sub(' +', ' ', text) | bigcode/self-oss-instruct-sc2-concepts |
def hasPTC(sequence):
"""
Determines whether a PTC exits in a sequence
Arguments:
sequence (str): IMGT gapped sequence in frame 1.
Returns:
int: negative if not PTCs, position of PTC if found.
"""
ptcs = ("TAA", "TGA", "TAG", "TRA", "TRG", "TAR", "TGR", "TRR")
for i in range(0... | bigcode/self-oss-instruct-sc2-concepts |
def gens(x):
"""
Return the generators of ``x``.
EXAMPLES::
sage: R.<x,y> = SR[]
sage: R
Multivariate Polynomial Ring in x, y over Symbolic Ring
sage: gens(R)
(x, y)
sage: A = AbelianGroup(5, [5,5,7,8,9])
sage: gens(A)
(f0, f1, f2, f3, f4)
... | bigcode/self-oss-instruct-sc2-concepts |
async def pull_content_from_unit_file(unit, path: str) -> str:
"""Pull the content of a file from one unit.
Args:
unit: the Juju unit instance.
path: the path of the file to get the contents from.
Returns:
the entire content of the file.
"""
action = await unit.run(f"cat {p... | bigcode/self-oss-instruct-sc2-concepts |
def write_csv(paths, headers):
"""
Takes in an array of .csv paths and appends them all together using
python fucntions. This allows us to pull in a large dataset, relying
on disk space, while preserving limited system memory.
"""
csv_out = "consolidated.csv"
csv_merge = open(csv_out, "w")
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def dateFormat(timestamp):
"""
Format timestamp (nb of sec, float) into a human-readable date string
"""
formatStr = '%a %b %d, %Y - %H:%M'
try:
return datetime.fromtimestamp(int(timestamp) or 86400).strftime(formatStr)
except OSError as e:
return ... | bigcode/self-oss-instruct-sc2-concepts |
def extract_items(topitems_or_libraryitems):
"""Extracts a sequence of items from a sequence of TopItem or LibraryItem objects."""
list = []
for i in topitems_or_libraryitems:
list.append(i.get_item())
return list | bigcode/self-oss-instruct-sc2-concepts |
def save_cluster(cluster):
"""Save cluster's units and origin
Parameters
----------
cluster : class
StarCluster
Returns
-------
cluster.units, cluster.origin : str
units and origin of StarCluster
History:
-------
2018 - Written - Webb (UofT)
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
def _compress_list(l):
"""Removes consecutive duplicate elements from |l|.
>>> _compress_list([])
[]
>>> _compress_list([1, 1])
[1]
>>> _compress_list([1, 2, 1])
[1, 2, 1]
"""
result = []
for e in l:
if result and result[-1] == e:
continue
result.append(e)
return result | bigcode/self-oss-instruct-sc2-concepts |
def rotate_inertia(rotation_matrix, inertia):
"""Returns an inertia tensor expressed in a reference frame which has
been rotated with respect to the frame the inertia tensor is currently
expressed in.
Parameters
----------
rotation_matrix : numpy.matrix, shape(3,3)
Three-dimensional rot... | bigcode/self-oss-instruct-sc2-concepts |
def get_tolerance_min_max(value, expected_tolerance):
"""
Get minimum and maximum tolerance range
Args:
value(int): value to find minumum and maximum range
expected_tolerance ('int'): Expected tolerance precentage
Returns:
minimum and maximum value of tol... | bigcode/self-oss-instruct-sc2-concepts |
def _fill_deque_by_initial_value(
deque_obj, initial_value, buffer_size):
"""
Fill the deque object with the initial value.
Parameters
----------
deque_obj : collections.deque
The deque object to add to.
initial_value : int or float
Initial value to be referenced.
bu... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def heaviside(X):
"""
A pytorch-differentiable version of the Heaviside function
.. math::
H\\left(x\\right) = \\frac{\\operatorname{sign}(x) + 1)}{2}
Args:
X: tensor input
"""
return (torch.sign(X) + 1.0) / 2.0 | bigcode/self-oss-instruct-sc2-concepts |
def distance(a, b):
"""Simple distance between two 1D arrays"""
return ((a - b) ** 2).sum() ** (0.5) | bigcode/self-oss-instruct-sc2-concepts |
def evaluate(v1, v2, operator):
"""Evaluation function for two values and an operator.
Args:
v1 (obj): object one
v2 (obj): object two
operator (string): operator that is being used
Returns:
bool: result of the equation v1 operator v2
"""
if operator == '==':
... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_model(file_name):
"""Loads the specified pickle file.
Parameters
----------
file_name : str
The location the pickle file.
Returns
-------
dict
The dictionary inside the pickle.
"""
with open(file_name, "rb") as model_file:
return p... | bigcode/self-oss-instruct-sc2-concepts |
def nx_edge_data_weight(edge_u, edge_v, edge_data):
"""Return custom edge data value to be used as a callback by nx."""
if edge_data.get("hop"):
return edge_data["hop"]
return 1 | bigcode/self-oss-instruct-sc2-concepts |
def avg_Q(q_S, q_D):
"""
Return total transmission capacity of station, assuming transmission evenly distributed over hexagonal cell
Parameters
----------
q_S : float
channel capacity in Mbps
q_D : float
data demand rate in Mbps
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def read_text(abspath, encoding="utf-8"):
"""
Read string from a file.
:type abspath: str
:type encoding: str
:rtype: str
"""
with open(abspath, "rb") as f:
return f.read().decode(encoding) | bigcode/self-oss-instruct-sc2-concepts |
def _prepare_params(dirty_params, prefix=None):
"""Prepares parameters to be sent to challonge.com.
The `prefix` can be used to convert parameters with keys that
look like ("name", "url", "tournament_type") into something like
("tournament[name]", "tournament[url]", "tournament[tournament_type]"),
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_RA_Dec(ra_string, dec_string):
"""Convert input RA and Dec strings to floats
Parameters
----------
ra_string : str
String containing RA information. Can be in the form 10:12:13.2
or 10h12m13.2s
dec_string : str
String containing Declination informatio... | bigcode/self-oss-instruct-sc2-concepts |
def version_tuple_to_string(evrTuple):
"""
Convert a tuple representing a package version to a string.
@param evrTuple: A 3-tuple of epoch, version, and release.
Return the string representation of evrTuple.
"""
(e, v, r) = evrTuple
s = ""
if e not in [0, '0', None]:
s += ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_version(version):
"""Parse version string and return version date integer."""
try:
if "-" in version:
return int(version.split("-", 1)[0])
except TypeError:
return version | bigcode/self-oss-instruct-sc2-concepts |
def unicode_to_hex(unicode_string):
"""
Return a string containing the Unicode hexadecimal codepoint
of each Unicode character in the given Unicode string.
Return ``None`` if ``unicode_string`` is ``None``.
Example::
a => U+0061
ab => U+0061 U+0062
:param str unicode_string: ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_operator_name(spec):
"""
Gives operator name from YAML short hand naming format
"""
components = spec.split("_")
name = "".join(x[:1].upper() + x[1:] for x in components)
if spec.endswith("dataset"):
return name
return name + "Operator" | bigcode/self-oss-instruct-sc2-concepts |
def format_float_as_percentage(value):
"""Format float value as a percentage string."""
return f"{value:.0%}" | bigcode/self-oss-instruct-sc2-concepts |
def _GetValue(skey, tlist):
"""Get data for subfield code skey, given the subfields list."""
for (subkey, subval) in tlist:
if skey == subkey:
return subval
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
import string
def run(text: str, mode: str) -> str:
"""
Remove the numbers/punctuation from a text.
:param text: a text to process
:param mode: the mode of processing
- n: remove numbers
- p: remove punctuation
- np: remove numbers and punctuation
:return: the pr... | bigcode/self-oss-instruct-sc2-concepts |
def item_bias(df, movie_id):
"""Calculate item bias: average rating for all items minus the items average rating"""
return df.loc[df['movie_id'] == movie_id, 'rating'].mean() - df['rating'].mean() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def boolean_array_to_integer(values: List[bool]) -> int:
"""Converts a boolean array to integer by interpretting it in binary with LSB 0 bit numbering.
Args:
values (List[bool]): The list of booleans to convert.
Returns:
int: The interpretted integer.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def unpickle_object(save_path):
"""
Unpickle object saved to save_path location
Parameters:
-- save_path (str) : path to pickled object
Returns:
-- obj : pickled object
"""
infile = open(save_path, 'rb')
obj = pickle.load(infile)
infile.close()
retu... | bigcode/self-oss-instruct-sc2-concepts |
from functools import wraps
def check_field_is_empty(field_name):
"""Returns decorator that bypasses cleaning for empty fields.
"""
def decorator(fun):
"""Decorator that checks if a field is empty if so doesn't do the cleaning.
Note Django will capture errors concerning required fields that are empty.... | bigcode/self-oss-instruct-sc2-concepts |
def get_injected_files(personality):
"""Create a list of injected files from the personality attribute.
At this time, injected_files must be formatted as a list of
(file_path, file_content) pairs for compatibility with the
underlying compute service.
"""
injected_files = []
for item in pers... | bigcode/self-oss-instruct-sc2-concepts |
def exec_fn(func):
"""Executes given function, returns {error,result} dict"""
try:
return {'result': func()}
except Exception as error: # pylint: disable=broad-except
return {'error': str(error)} | bigcode/self-oss-instruct-sc2-concepts |
def predict(x_test, feature_names):
"""
Prediction is positive if the student has negative
to math and portuguese in the 3rd period
:param x_test:
:param feature_names:
:return: list of predictions correspondent to the x_test
"""
predictions = []
# get index of target columns
m... | bigcode/self-oss-instruct-sc2-concepts |
def cases_fou(col,lig):
"""Retourne la liste des indices (col,lig) des cases où peut se
déplacer un fou positionné sur la case (col, lig)
Ex: fou en (2,3)
- - - - - - - - - -
| x |
| x x |
| x x |
| F |
| x x |
| x ... | bigcode/self-oss-instruct-sc2-concepts |
def getInternalIntfList(ch):
"""
Takes a chute object and uses the key:networkInterfaces to return a list of the internal
network interfaces that will exist in the chute (e.g., eth0, eth1, ...)
Returns:
A list of interface names
None if networkInterfaces doesn't exis... | bigcode/self-oss-instruct-sc2-concepts |
def list_replace(subject_list, replacement, string):
"""
To replace a list of items by a single replacement
:param subject_list: list
:param replacement: string
:param string: string
:return: string
"""
for s in subject_list:
string = string.replace(s, replacement)
return str... | bigcode/self-oss-instruct-sc2-concepts |
def get_transpositions(sequence):
""" Given a series of pitch names (no flats or sharps - just abcdefg),
return a list of the 7 possible transpositions of the melody. This is used
when generating an elastic search query to look for all transpositions of a
user specified pitch sequence.
The URL for ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_options(options, return_list=True):
""" Parse dictionary/json of options, and return arg list for xtb """
cmd_options = []
for key, value in options.items():
if value is not None:
txt = f"--{key} {value}"
else:
txt = f"--{key}"
cmd_options.append... | bigcode/self-oss-instruct-sc2-concepts |
def get_date_time_from_timestamp(timestamp):
"""Get the date time from a timestamp.
The timestamp must have the following format:
'year.month.day.hour.minutes'
Example:
'2017.12.20.10.31' -> '2017/12/20 10:31'
"""
date_time_string = timestamp
sp = timestamp.split('.')
if len(sp) >= ... | bigcode/self-oss-instruct-sc2-concepts |
def HINGED_PROPERTIES(ELEMENTS):
"""
This function creates an array with the hinge properties per node.
Input
ELEMENTS | Elements properties | Py Numpy array
| Node 0 ... Node (N_NODES - 1), Material ID, |
| Geometry ID, Hinge ID n... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Union
from typing import Sequence
def prepare_register_list(register_dict: Dict[str, Union[bool, Sequence[int]]]):
"""
Canonicalize classical addresses for the payload and ready MemoryReference instances
for serialization.
This function will cast keys that a... | bigcode/self-oss-instruct-sc2-concepts |
def is_succeeded(status, **_):
"""For when= function to test if a pod has succeeded."""
return status.get('phase') == 'Succeeded' | bigcode/self-oss-instruct-sc2-concepts |
def l1_norm(vals):
"""Calculate the L1 norm of a vector."""
if len(vals)==0:
return []
try:
# If inputs are awesomediff.variable objects:
return sum([abs(v.val) for v in vals])
except:
return sum([abs(v) for v in vals]) | bigcode/self-oss-instruct-sc2-concepts |
def ParseUrl(url):
"""Parses a URL string according to RFC 1738.
Note: We allow '/' character in 'user', so we can specify workgroup of smb
user.
Args:
url: An URL string.
Returns:
A dict with optional keys 'scheme', 'user', 'password', 'host', 'port', and
'urlpath'.
"""
result = {}
schem... | bigcode/self-oss-instruct-sc2-concepts |
def sort_ongoing_wars(wars: list) -> list:
"""
Sort a provided list of wars for ongoing wars.
:param wars: A list of wars to be iterated through. Objects must contain "turnsleft" and "winner" keys.
:return: A list of active wars.
"""
return [war for war in wars if int(war["turnsleft"]) > 0 and ... | bigcode/self-oss-instruct-sc2-concepts |
def gradient_correction(inputs, grads):
"""
Transforms vectors g=[g1,g2] and i=[i1,i2] into h=[h1, h2]
where h2 = 1/2 * 1/(i2 + 1/g2) and h1 = 2 * h2 * (g1/g2 - i1)
:param inputs: a tensor of inputs with shape ``batch_shape + [num_data]``,
:param grads: a tensor of gradients with shape ``batch_shap... | bigcode/self-oss-instruct-sc2-concepts |
def gray_encode(i):
"""Gray encode the given integer."""
return i ^ (i >> 1) | bigcode/self-oss-instruct-sc2-concepts |
def get_tweet_node(graph, status):
"""
Search for a Tweet node in the graph matching this status, and return it
if it exists (otherwise None).
"""
return graph.nodes.match("Tweet", tweet_id=status.id).first() | bigcode/self-oss-instruct-sc2-concepts |
def get_field_errors(validation_error, field_name):
"""
Return an individual field's validation error messages.
:type validation_error: Django ValidationError
:type field_name: str
:rtype: list
"""
error_dict = validation_error.error_dict
assert field_name in error_dict
return error... | bigcode/self-oss-instruct-sc2-concepts |
import time
import select
def read_all(end, stream, append):
"""Read all buffered lines from a stream."""
while not end or time.time() < end:
line = stream.readline()
if not line:
return True # Read everything
# Strip \n at the end if any. Last line of file may not have on... | bigcode/self-oss-instruct-sc2-concepts |
def process_activities(activities_str: str) -> list:
"""
Split activities as a pipe-separated string into a list of activities.
"""
activities_split = activities_str.split(" | ")
# Ignore row of no activities, which will be a single null string after
# splitting.
if len(activities_split) ==... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dict(a, b):
""" merge dict a, b, with b overriding keys in a """
c = a.copy()
c.update(b)
return c | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import requests
def _find_city(ip: str) -> Optional[str]:
"""
Uses ip-api to find the city in which an IP address is located.
:param ip: the ip address to geolocate
:return: the city where theIP address is located or None
"""
geo_ip_url = "http://ip-api.com/json/... | bigcode/self-oss-instruct-sc2-concepts |
import six
def canonicalize_input_bounds(input_bounds):
"""Converts string constant 'none' representing unspecified bound into None.
Args:
input_bounds: The input_min or input_max hyperparameter of
`tfl.layers.Linear` layer.
Returns:
A list of [val, val, ...] where val can be a float or None, or... | bigcode/self-oss-instruct-sc2-concepts |
import platform
def verify(p):
"""Wait for executable to exit and verify status."""
try:
out, err = p.communicate()
except Exception as e:
raise Exception("Error running %s: %s", p.args, e)
if p.returncode:
raise Exception("""%s exit code %s
vvvvvvvvvvvvvvvv
%s
^^^^^^^^^^^^^^^^... | bigcode/self-oss-instruct-sc2-concepts |
def get_motion(obj_idx, frame_idx, motion_trajectory):
"""Returns the motion of a specified object at a specified frame."""
motion = motion_trajectory[frame_idx]['objects'][obj_idx]
return motion | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_parent_folder_name(path):
"""
:param str path: The full path to the file or folder.
:return str: The parent folder name.
Returns the parent folder name, given a full path.
"""
return str(pathlib.Path(path).parent) | bigcode/self-oss-instruct-sc2-concepts |
def band_select(bands):
"""
Return image/mask pair where spectral bands in image have been selected as a list.
Parameters
----------
bands : list
Spectral bands, defined with respect to input's final dimension.
Returns
-------
apply_transform : func
Transformation for i... | bigcode/self-oss-instruct-sc2-concepts |
def get_processed_comment_sequence(comment_subtokens):
"""Returns sequence without tag string. Tag strings are excluded for evaluation purposes."""
if len(comment_subtokens) > 0 and comment_subtokens[0] in ['@param', '@return']:
return comment_subtokens[1:]
return comment_subtokens | bigcode/self-oss-instruct-sc2-concepts |
import re
def find_and_replace(line, substitutions):
"""
Function performs find and replace on a string given a dictionary of
substitution criteria. (Designed to be a sed-like command that can replace
multiple strings in a single pass)
Parameters
----------
line : str
line of text... | bigcode/self-oss-instruct-sc2-concepts |
import json
def create_json(fname, data):
""" Create JSON file
:param fname: Name of the file to be saved
:param data: Array or dictionary to be converted to JSON
"""
with open(fname, 'w') as outfile:
json.dump(data, outfile, indent=2, separators=(',', ': '))
return True | bigcode/self-oss-instruct-sc2-concepts |
def retrieve(result_queue, queue_size):
""" Retrieve results from a shared queue.
"""
results = []
while queue_size:
results.append(result_queue.get())
queue_size -= 1
return results | bigcode/self-oss-instruct-sc2-concepts |
def validate_string(datum, **kwargs):
"""
Check that the data value is string
Parameters
----------
datum: Any
Data being validated
kwargs: Any
Unused kwargs
"""
return isinstance(datum, str) | bigcode/self-oss-instruct-sc2-concepts |
import re
def section_heads(value):
"""
Search through a block of text and replace <p><b>text</b></p>
with <h4 class="section-head">text</h4
"""
value = re.sub(r'<p>\w*<b>(.+?)</b>\w*</p>', u'<h4 class="section-head">\\1</h4>', value)
return value | bigcode/self-oss-instruct-sc2-concepts |
def outer_subspace_product(subspace1: list, subspace2: list, reverse: bool = False) -> list:
"""
Forms the outer (cartesian) product of two subspaces which are both aligned
with the comp. basis.
:param subspace1: list, list containing the computational basis vectors which
spa... | bigcode/self-oss-instruct-sc2-concepts |
def denary2BinaryStr(n, l=8):
"""
Convert denary integer n to binary string bs, left pad to length l
"""
bs = ''
if n < 0: raise ValueError("must be a positive integer")
if n == 0: return '0'
while n > 0:
bs = str(n % 2) + bs
n = n >> 1
return bs.rjust(l,'0') | bigcode/self-oss-instruct-sc2-concepts |
def test_value_generator(total_rows, row_number, previous_row_values):
"""
test function for generating column values
Returns
_______
int
the row number plus the previous row value (or zero if it's the first)
"""
return row_number + len(previous_row_values) | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def cleandoc(docstring):
"""Clean documentation string (docstring) per PEP 257 rules.
Args:
docstring: supplied docstring.
Returns:
Clean docstring.
Note:
This is just a wrapper around ``inspect.cleandoc``.
"""
return inspect.cleandoc(docstring) | bigcode/self-oss-instruct-sc2-concepts |
def get_data_from_films_locations_file(path):
"""
Return data with location and year of every film in file
(str) -> dict
ex. dict1['2020'] = {location1: {film1, ...}, location2: {film2, ...}}
"""
film_locations_data = {}
with open(path, encoding='utf-8', errors='ignore') as f:
for l... | bigcode/self-oss-instruct-sc2-concepts |
def str_to_nat(s):
"""Convert string to natural number."""
return ord(s) - ord("a") | bigcode/self-oss-instruct-sc2-concepts |
def check_deps(sent):
"""
Checks that each dependency link refer to an existing word id
Args: list of tuples (ln, word objs)
Return: list of tuples (ln, word objs) with false head
"""
headless_words = []
ids = [word.nid for ln, word in sent]
for ln, word in sent:
# on zappe les c... | bigcode/self-oss-instruct-sc2-concepts |
def get_activating_points(trace, rcon_alpha):
"""
Returns a list of time instances where the trace is activated by RCon ⍺
:param trace: One trace (a list of states in time)
:param rcon_alpha: A proposition indicating the ⍺ of the RCon
:return: a list of time instances where the trace is activated
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def create_hash(text):
"""
Runs hashing function from hashlib
:param text: text to hash
:return: hash value of text
"""
return hashlib.sha256(text.encode('utf-8')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def get_patch_values(patch, path):
"""Get the patch values corresponding to the specified path.
If there are multiple values specified for the same path
(for example the patch is [{'op': 'add', 'path': '/name', 'value': 'abc'},
{'op': 'add', 'path': '/name', 'value': 'bca'}])... | bigcode/self-oss-instruct-sc2-concepts |
def freq(a=0):
""" Processor frequency """
return 240*1000000 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Mapping
from typing import Any
import inspect
def _invoke(f: Callable, kwargs: Mapping[str, Any]) -> Any:
"""
Invoke the given function with a given dictionary of keyword arguments, silently ignoring any extra arguments.
"""
signature = inspect.signature(... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dols(dol1, dol2):
"""
Merge two dictionaries of lists.
"""
result = dict(dol1, **dol2)
result.update((k, dol1[k] + dol2[k])
for k in set(dol1).intersection(dol2))
return result | bigcode/self-oss-instruct-sc2-concepts |
def removeCharacterRelations(cname: str) -> str:
"""Return a query to remove all of a character's relations."""
return (f"DELETE FROM appears_in "
f"WHERE cname='{cname}';"
) | bigcode/self-oss-instruct-sc2-concepts |
def datazoom(is_datazoom_show=False,
datazoom_type='slider',
datazoom_range=None,
datazoom_orient='horizontal',
**kwargs):
"""
:param is_datazoom_show:
It specifies whether to use the datazoom component.
:param datazoom_type:
datazoom type... | bigcode/self-oss-instruct-sc2-concepts |
def utf8_decoder(s):
""" Decode the unicode as UTF-8 """
if s is None:
return None
return s.decode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def nonnegative_int(argument):
"""
Check for a nonnegative integer argument; raise ``ValueError`` if not.
(Directive option conversion function.)
"""
value = int(argument)
if value < 0:
raise ValueError('negative value; must be positive or zero')
return value | bigcode/self-oss-instruct-sc2-concepts |
def mk_endpoint_config(prj, endpoint_name, model_name):
""" Return endpoint config creation parameters. """
return {
"EndpointConfigName": prj.full_job_name(endpoint_name) + "-config",
"ProductionVariants": [
{
"VariantName": prj.full_job_name(model_name) + "-variant-... | bigcode/self-oss-instruct-sc2-concepts |
def chebyshev(dx, dy):
""" Chebyshev distance. """
return max(dx, dy) | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def get_networkx_func (func_name, seed=0, **kwargs):
"""
Uses 'func_name' graph generator of NetworkX library to create a NetworkX
graph which can be used as topology.
"""
nx_func = getattr(importlib.import_module("networkx"), func_name)
generated_graph = nx_func(seed=seed, **kwargs)
r... | bigcode/self-oss-instruct-sc2-concepts |
def loadTab5File(sc, pathToSampleFile):
"""
Loads a Tab5-formatted file into an RDD. The file is loaded using the Hadoop File API so we can create an RDD
based on the tab5 format: [name]\t[seq1]\t[qual1]\t[seq2]\t[qual2]\n
Args:
sc: A Spark context
pathToSampleFile: A valid Hadoop file p... | bigcode/self-oss-instruct-sc2-concepts |
def o_counter(listy):
"""
Input: A list of numbers.
Ouptut: The number of entries in a list, using the len function.
"""
return (len(listy)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def toggle_page_menu(menu: Iterable) -> dict:
"""
Toggle page menu by updating CSS style for menu container.
Parameters
----------
menu: list of menu items
Return value
------------
style: CSS style for container
"""
if not menu:
return {'d... | bigcode/self-oss-instruct-sc2-concepts |
def get_model_fn(model, train=False):
"""Create a function to give the output of the score-based model.
Args:
model: The score model.
train: `True` for training and `False` for evaluation.
Returns:
A model function.
"""
def model_fn(x, labels):
"""Compute the output of the score-based model... | bigcode/self-oss-instruct-sc2-concepts |
def option_to_clblast(x):
"""Translates an option name to a CLBlast data-type"""
return {
'layout': "Layout",
'a_transpose': "Transpose",
'b_transpose': "Transpose",
'ab_transpose': "Transpose",
'side': "Side",
'triangle': "Triangle",
'diagonal': "Diagonal... | 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.