seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_token_segments(labels, word_ids):
"""
Function to extract correctly formatted answers
Input: array of labels (can be predicted labels, or true labels)
Output: array of tuples; (start index of answer, length of answer)
"""
prev_word_id = None
labels_stats = []
for idx, label ... | bigcode/self-oss-instruct-sc2-concepts |
def _etsz(rn, g, tmean, u2, vpd, es_slope, psy, cn, cd):
"""Standardized Reference ET [mm] (Eq. 1)
Parameters
----------
rn : scalar or array_like of shape(M, )
Net radiation [MJ m-2 d-1 or MJ m-2 h-1].
g : scalar or array_like of shape(M, )
Ground heat flux [MJ m-2 d-1 or MJ m-2 h-... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def is_v4(address):
"""Determines if the supplied address is a valid IPv4 address"""
try:
socket.inet_pton(socket.AF_INET, address)
return True
except socket.error:
return False | bigcode/self-oss-instruct-sc2-concepts |
def year_cv_split(X, year_range):
"""Split data by year for cross-validation for time-series data.
Makes data from each year in the year_range a test set per split, with data
from all earlier years being in the train split.
"""
return [
((X["year"] < year).to_numpy(), (X["year"] == year).to... | bigcode/self-oss-instruct-sc2-concepts |
def is_list_of_valid_elem(value, elem_validator):
""" Is the given value a list whose each element is checked by elem_check to be True?
:param value: The value being checked
:type value: Any
:param elem_validator: The element checker
:type elem_validator: Any -> bool
:return: True if the given v... | bigcode/self-oss-instruct-sc2-concepts |
def return_period_earth(energy_mttnt):
"""
Return period of Asteroid/Comet of a given energy (Megatons TNT) in Years.
:param energy_mttnt: Energy in Megatons TNT
:returns: Return period of given energy level in years
:Reference: EarthImpactEffect.pdf, Equation 3*
"""
return 109 * (energy_mt... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def _table_cell(items: Iterable[str]) -> str:
"""Make a row of table cell."""
return '|' + '|'.join(f" {t} " for t in items) + '|' | bigcode/self-oss-instruct-sc2-concepts |
def triangle_up_to(*, index=None, value=None):
"""
[NP] Returns all triangle numbers up to the `index`-th member, or until the value exceeds
`value`.
:param index: integer
:param value: integer
:returns: list of integers, with the desired triangle sequence numbers
"""
assert index is no... | bigcode/self-oss-instruct-sc2-concepts |
def identity(x):
"""Return exactly what was provided."""
return x | bigcode/self-oss-instruct-sc2-concepts |
def get_widths_balancer(widths, minmax_ratio=0.02):
"""
Given a list of positive numbers, find a linear function, such that when applied to the numbers, the maximum value
remains the same, and the minimum value is minmax_ratio times the maximum value.
:param widths: list of numbers
:param minmax_rat... | bigcode/self-oss-instruct-sc2-concepts |
def factorials(number: int, iteratively=True) -> int:
"""
Calculates factorials iteratively as well as recursively. Default iteratively. Takes linear time.
Args:
- ``number`` (int): Number for which you want to get a factorial.
- ``iteratively`` (bool): Set this to False you want... | bigcode/self-oss-instruct-sc2-concepts |
def mean_percentage_error(y_true, y_pred):
"""Compute the mean percentage error (MPE).
Parameters
----------
y_true : array-like, shape (n_samples,)
Ground truth (correct) target values.
y_pred : array-like, shape (n_samples,)
Estimated target values.
Returns
-------
m... | bigcode/self-oss-instruct-sc2-concepts |
def match_prio_rule(cz, pr: dict) -> bool:
"""Match a priority rule to citizenlab entry"""
for k in ["category_code", "cc", "domain", "url"]:
if pr[k] not in ("*", cz[k]):
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def estimated_bigram_probability(bigram, unigram_dict, bigram_dict):
""" estimate the probability of bigram (= (syll_1,syll_2)) by:
(count (syll_1,syll_2)) / (count syll_1)
"""
# set the count to zero
count = 0
# check if bigram is actually in our dict
if bigram in bigram_dict:
# i... | bigcode/self-oss-instruct-sc2-concepts |
def monkeypatch_readline(request, monkeypatch, readline_param):
"""Patch readline to return given results."""
def inner(line, begidx, endidx):
if readline_param == "pyrepl":
readline = "pyrepl.readline"
else:
assert readline_param == "readline"
readline = "rea... | bigcode/self-oss-instruct-sc2-concepts |
def _is_idempotence_error(status_code, errors, context):
"""
Determines if an idempotence error has occurred based on the status code, errors and context
"""
return status_code == 409 \
and context is not None \
and context.idempotence_key is not None \
and len(errors) == 1 \
... | bigcode/self-oss-instruct-sc2-concepts |
def format_verify_msg(status):
"""Format validation message in color"""
OK = '\033[92m OK \033[0m'
FAIL = '\033[91mFAIL\033[0m'
if status:
return OK
else:
return FAIL | bigcode/self-oss-instruct-sc2-concepts |
import re
def golang_duration_to_seconds(d: str) -> int:
"""
Convert values like "276h41m7s" to number of seconds
"""
add = ""
for c in ["s", "m", "h"]:
if d.endswith(c):
break
add += "0" + c
d += add
hms = [int(x) for x in re.split(r"\D", d)[:-1]]
res = hm... | bigcode/self-oss-instruct-sc2-concepts |
def split_chain(chain):
"""
Split the chain into individual certificates for import into keystore
:param chain:
:return:
"""
certs = []
if not chain:
return certs
lines = chain.split('\n')
cert = []
for line in lines:
cert.append(line + '\n')
if line =... | bigcode/self-oss-instruct-sc2-concepts |
def class_labels(column):
"""
Takes in target column and creates list of binary values. 1 (>=0.5) being in the
positive class (toxic), 0 (<0.5) being in the negative class (Not toxic)
"""
class_label = []
for row in column:
if row < 0.5:
class_label.append(0)
else... | bigcode/self-oss-instruct-sc2-concepts |
def _slugify(text: str) -> str:
"""Turns the given text into a slugified form."""
return text.replace(" ", "-").replace("_", "-") | bigcode/self-oss-instruct-sc2-concepts |
def deformat_var_key(key: str) -> str:
"""
deformat ${key} to key
:param key: key
:type key: str
:return: deformat key
:rtype: str
"""
return key[2:-1] | bigcode/self-oss-instruct-sc2-concepts |
import glob
def _GetSequentialFileName(base_name):
"""Returns the next sequential file name based on |base_name| and the
existing files."""
index = 0
while True:
output_name = '%s_%03d' % (base_name, index)
if not glob.glob(output_name + '.*'):
break
index = index + 1
return output_name | bigcode/self-oss-instruct-sc2-concepts |
def normalize(expr):
"""Pass through n-ary expressions, and eliminate empty branches.
Variadic and binary expressions recursively visit all their children.
If all children are eliminated then the parent expression is also
eliminated:
(& [removed] [removed]) => [removed]
If only one child is ... | bigcode/self-oss-instruct-sc2-concepts |
def get_package(config):
"""
Returns the package associated with this device
Args:
config (dictionary): configuration dictionary
Return:
(string) package
Raises:
Nothing
"""
#split the device string with "-" and get the second value
package = config["devi... | bigcode/self-oss-instruct-sc2-concepts |
def stations_by_river(stations):
"""Takes a list of MonitoringStation
objects and maps each station object (value) to its
respective river (key).
"""
station_map = {}
for station in stations:
if station.river in station_map:
station_map[station.river].add(station)
els... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha1_hex_file(filepath, max_bytes=None):
"""
Returns the SHA1 of a given filepath in hexadecimal.
Opt-args:
* max_bytes. If given, reads at most max_bytes bytes from the file.
"""
sha1 = hashlib.sha1()
f = open(filepath, 'rb')
try:
if max_bytes:
... | bigcode/self-oss-instruct-sc2-concepts |
def load_categories(file_name):
"""
Loads the category index from file. Each category label is
the name of a class specified on a separate line. The entry order
is the index of the class.
"""
labels = []
with open(file_name) as f:
labels = f.read().splitlines()
categories = {}
... | bigcode/self-oss-instruct-sc2-concepts |
def as_choice(as_list):
"""
Creates a dropdown list of authorization servers
"""
element = "<select name=\"authzsrv\">"
for name in as_list:
element += "<option value=\"%s\">%s</option>" % (name, name)
element += "</select>"
return element | bigcode/self-oss-instruct-sc2-concepts |
def mean(num_list):
"""
Calculates the mean of a list of numbers
Parameters
----------
num_list: list (int or float)
Returns
-------
ret: int or float
The mean of the list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
"""
try:
return sum(nu... | bigcode/self-oss-instruct-sc2-concepts |
import socket
def _get_socket_constants(prefix):
"""Create a dictionary mapping socket module constants to their names."""
return {getattr(socket, n): n for n in dir(socket) if n.startswith(prefix)} | bigcode/self-oss-instruct-sc2-concepts |
def desi_target_from_survey(survey):
""" Return the survey of DESI_TARGET as a function of survey used (cmx, sv1, sv2, sv3, main)."""
if survey == 'special':
# to avoid error, return one of the column, SV2_DESI_TARGET should be full of 0.
return 'SV2_DESI_TARGET'
if survey == 'cmx':
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_date_file_name(extension):
"""
Format 'now' datetime and create file name
with a given extension like this: 'YYYY_MM_DD hh_mm_ss.ext'
"""
return "{}.{}".format(datetime.now().replace(microsecond=0), extension).replace(":", "_") | bigcode/self-oss-instruct-sc2-concepts |
import select
import errno
def eintr_retry_call(func, *args, **kwargs):
"""
Handle interruptions to an interruptible system call.
Run an interruptible system call in a loop and retry if it raises EINTR.
The signal calls that may raise EINTR prior to Python 3.5 are listed in
PEP 0475. Any calls t... | bigcode/self-oss-instruct-sc2-concepts |
def unique_fitnesses(population: list) -> int:
""" Calculates the number of unique fitnesses in the population
Args:
population (list): The list of individual candidate solutions
Returns:
int: The number of unique fitnesses in the population
"""
fitnesses = [individual.fitness for ... | bigcode/self-oss-instruct-sc2-concepts |
def are_equal_nodes(n1, n2, underspecified=True):
"""Returns True if nodes n1 and n2 have the same predicate and sortinfo. If underspecified,
allow underspecification."""
if underspecified:
if n1.is_less_specific(n2) or n2.is_less_specific(n1):
return True
return n1.pred == n2.pred a... | bigcode/self-oss-instruct-sc2-concepts |
def _do_decoding(s, encoding):
"""A function to decode a bytes string, or return the object as-is."""
try:
return s.decode(encoding)
except UnicodeError:
raise
except (AttributeError, TypeError):
return s | bigcode/self-oss-instruct-sc2-concepts |
def enum_to_list(enum):
"""Enum to list."""
return [enum_ele.value for enum_ele in enum] | bigcode/self-oss-instruct-sc2-concepts |
def clean_update_item_string(string):
"""
Removes "(" and ")" parentheses from a string
Args:
string(str): entry
Returns:
str: string with parens removed
"""
return str(string.replace("(", "").replace(")", "")) | bigcode/self-oss-instruct-sc2-concepts |
def ascii_distance(first, second):
"""
returns the positive distance between the ascii values of input characters
assume: inputs are valid single letters
e.g. inputs ("a", "b") should return 1,
inputs ("b", "a") should return 1 too (postive distance)
"""
return abs(ord(first)-ord(second)... | bigcode/self-oss-instruct-sc2-concepts |
def GenerateFractionSamples(x, w, frac=0.50):
"""
Randomly samples fraction of the events from given features and weight.
Args:
x : panda.DataFrame
dataframe that contains the features for training.
w : panda.DataFrame
dataframe that contains the MC event weight.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
from typing import Optional
def get_dict_from_cu_inst_result_file(cu_inst_result_file: str) -> Dict[str, List[Dict[str, Optional[str]]]]:
"""Parses the information contained in cu_inst_result_file into a dictionary of dictionaries,
ordered by dependency type and... | bigcode/self-oss-instruct-sc2-concepts |
def wrap(x, m, M):
"""Wraps ``x`` so m <= x <= M; but unlike ``bound()`` which
truncates, ``wrap()`` wraps x around the coordinate system defined by m,M.\n
For example, m = -180, M = 180 (degrees), x = 360 --> returns 0.
Args:
x: a scalar
m: minimum possible value in range
M: max... | bigcode/self-oss-instruct-sc2-concepts |
def _getMenuIndex(values, current, defaultIndex = 1):
"""
Retrieves the menu index corresponding to the current value selected amongst values.
If the value is invalid, returns the defaultIndex.
"""
try:
# Note: menu index is 1-based.
return values.index(current) + 1
except:
... | bigcode/self-oss-instruct-sc2-concepts |
from zipfile import ZipFile
def extract_shp(path):
"""Return a geopandas-compatible path to the shapefile stored in a zip archive.
If multiple shapefiles are included, return only the first one found.
Parameters
----------
path : Path
Path to zip archive holding shapefile.
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha1_20(data):
"""Return the first 20 bytes of the given data's SHA-1 hash."""
m = hashlib.sha1()
m.update(data)
return m.digest()[:20] | bigcode/self-oss-instruct-sc2-concepts |
def prod(l):
"""
l: iterable of numbers.
returns: product of all numbers in l
"""
p = 1
for i in l: p *= i
return p | bigcode/self-oss-instruct-sc2-concepts |
def find_subseq_in_seq(seq, subseq):
"""Return an index of `subseq`uence in the `seq`uence.
Or `-1` if `subseq` is not a subsequence of the `seq`.
The time complexity of the algorithm is O(n*m), where
n, m = len(seq), len(subseq)
from https://stackoverflow.com/questions/425604/best-way-to-determ... | bigcode/self-oss-instruct-sc2-concepts |
import lzma
import gzip
def get_open_function(path):
"""Choose an open function based on the file's extension."""
if path.endswith('xz'):
return lzma.open
elif path.endswith('gz'):
return gzip.open
return open | bigcode/self-oss-instruct-sc2-concepts |
def set_weierstrass_eq(*, a=1, b=1):
"""Return equation that defines Weierstrass curve. """
def wei_eq(x, y):
return y ** 2 == x ** 3 + a * x + b
return wei_eq | bigcode/self-oss-instruct-sc2-concepts |
def topological_sort(g):
"""
Returns tuple for a directed graph where:
- First element is a boolean that is set to True if graph contains a cycle
- Second element is an array of vertices in topological order if graph has no cycles,
or None otherwise
"""
visited = set()
removed = set... | bigcode/self-oss-instruct-sc2-concepts |
def cutlabel(s, cuts):
"""Cuts a string s using a set of (n, label) cuts.
Returns a list of (sub, label) pairs.
If there was an initial part before the first cut, then it has a label of None.
If there are no cuts, returns s as a single element, with label None.
"""
cuts = sorted(cuts)
# no c... | bigcode/self-oss-instruct-sc2-concepts |
def issequence(obj):
"""returns True if obj is non-string iterable (list, tuple, ect)"""
return getattr(obj, '__iter__', False) | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_module_path_from_type(py_type) -> str:
"""
Gets full module path + class name by the given class type
Parameters
----------
cls: python type
Class you want to get full module path for
Returns
-------
String representation of full module path like module... | bigcode/self-oss-instruct-sc2-concepts |
def rotate_patches_90deg(patches):
"""
Rotate patch dictionary as if original image is rotated by 90-degree
CCW.
"""
def rot_pos(i, j):
"""
Board Coordinates:
i
9 ... 1
------ 1 j
| | ...
------ 9
"""
return (10 - ... | bigcode/self-oss-instruct-sc2-concepts |
def one_max(phenome):
"""The bare-bones one-max function."""
return sum(phenome) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def parse_multi_command(command: str, commands_out: List[int]) -> dict:
"""
Given a list of commands separated by semicolons (;), this simply separates
the commands into individual ones.
This is useful for workflows that require different commands at different
steps in a w... | bigcode/self-oss-instruct-sc2-concepts |
def get_device_mac(run_command_fn, dev_name, netns_name=None):
"""Find device MAC address"""
if netns_name:
command_prefix = "ip netns exec %s " % netns_name
else:
command_prefix = ""
(output, _) = run_command_fn("%scat /sys/class/net/%s/address" %
(comm... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_relvaldata_id(file):
"""Returns unique relvaldata ID for a given file."""
run_id = re.search('R\d{9}', file)
run = re.search('_RelVal_([\w\d]*)-v\d__', file)
if not run:
run = re.search('GR_R_\d*_V\d*C?_([\w\d]*)-v\d__', file)
if run_id and run:
return (run_id.gro... | bigcode/self-oss-instruct-sc2-concepts |
def swapbytes(bytes_in):
"""Swaps a list of bytes to conform with TI's documentation
Example:
input = [0x0f, 0x00]
output = swapbytes(input)
print output
>>> [0x00, 0x0f]
Args:
bytes_in (2 element list): a list of bytes to swap
Returns:
list: The swapped... | bigcode/self-oss-instruct-sc2-concepts |
def get_columns(X):
"""
Select columns to work with
:param X: imported training data
:return: all columns, numerical columns, categorical columns
"""
numerical_cols = [col for col in X.columns if X[col].dtype in ['int64', 'float64']]
categorical_cols = [col for col in X.columns if X[col].dt... | bigcode/self-oss-instruct-sc2-concepts |
def shellquote(text):
"""Quote a string literal for /bin/sh."""
return "'" + text.replace("'", "'\\''") + "'" | bigcode/self-oss-instruct-sc2-concepts |
def checkUniqueness(some_list):
"""
Verifies that every entry in a list is unique. If it is not, it returns
non-unique values.
"""
unique_list = dict([(x,[]) for x in some_list]).keys()
repeated_entries = [u for u in unique_list
if len([s for s in some_list if s == u])... | bigcode/self-oss-instruct-sc2-concepts |
def encode_categorical(df):
"""
Compresses the size of the dataframe by changing column data type to minimum required size
that can accommodate the values. This is done only for categorical columns.
If a numeric column is expected to have very few values, change that to categorical first
and then us... | bigcode/self-oss-instruct-sc2-concepts |
def extendShape(shape):
"""Add dummy dimensions to make ``shape`` 3D.
:raises NotImplementedError: If ``shape`` is neither 1, 2 or 3D.
:param np.ndarray | list | tuple shape: Shape.
:return: 3D shape.
:rtype: tuple
"""
if len(shape) == 1:
return shape[0], 1, 1
if len(shape) =... | bigcode/self-oss-instruct-sc2-concepts |
def is_on_intersection(intersection, coord):
"""
Determines if coordinates is within intersection
:param intersection: intersection object
:param coord: coordinates to test
:type intersection: Intersection
:type coord: Coordinates
:return: True if the coord is within the intersection. Fals... | bigcode/self-oss-instruct-sc2-concepts |
def is_vectorized_oper(dims):
"""Is a vectorized operator."""
return (
isinstance(dims, list) and
isinstance(dims[0], list)
) | bigcode/self-oss-instruct-sc2-concepts |
def get_set_bits_count(number: int) -> int:
"""
Count the number of set bits in a 32 bit integer
>>> get_set_bits_count(25)
3
>>> get_set_bits_count(37)
3
>>> get_set_bits_count(21)
3
>>> get_set_bits_count(58)
4
>>> get_set_bits_count(0)
0
>>> get_set_bits_count(256)... | bigcode/self-oss-instruct-sc2-concepts |
def get_img_to_cap_dict(filename):
"""
Opens the file storing image to caption mappings.
Creates a dictionary and adds the mappings as
key-value pairs to it.
Args:
filename: the name of the file storing image to caption mappings
Returns:
img_to_cap_dict: the dictionary storing image to caption mappings
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def encode_state(fs, fluent_map):
""" Convert a FluentState (list of positive fluents and negative fluents) into
an ordered sequence of True/False values.
It is sometimes convenient to encode a problem in terms of the specific
fluents that are True or False in a state, but other times it is easier (or ... | bigcode/self-oss-instruct-sc2-concepts |
def reply(read=20, write=20):
"""Return the kwargs for creating the Reply table."""
return {
'AttributeDefinitions': [
{
'AttributeName': 'Id',
'AttributeType': 'S'
},
{
'AttributeName': 'ReplyDateTime',
... | bigcode/self-oss-instruct-sc2-concepts |
def escape(line):
"""Escapes special LaTeX characters by prefixing them with backslash"""
for char in '#$%&_}{':
line = [column.replace(char, '\\'+char) for column in line]
return line | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_script_path(script_name: str):
"""
Retrieves script path where name is matching {{script_name}}.
"""
p = Path(__file__).parents[1]
script_path = str(Path(p, "assets/scripts", script_name))
return script_path | bigcode/self-oss-instruct-sc2-concepts |
def remove_suffixes(text: str, suffixes:list) -> str:
"""Removes pre-defined suffixes from a given text string.
Arguments:
text: Text string where suffixes should be removed
suffixes: List of strings that should be removed from the end of the text
Returns:
text: Text string with re... | bigcode/self-oss-instruct-sc2-concepts |
def run_and_return_first_line(run_lambda, command):
"""Runs command using run_lambda and returns first line if output is not empty"""
rc, out, _ = run_lambda(command)
if rc != 0:
return None
return out.split("\n")[0] | bigcode/self-oss-instruct-sc2-concepts |
def load_template(config):
"""Return text of template file specified in config"""
with open(config['template'], 'r') as template_file:
return template_file.read() | bigcode/self-oss-instruct-sc2-concepts |
def norm_shape(shape):
"""
Normalize numpy array shapes so they're always expressed as a tuple,
even for one-dimensional shapes.
Parameters
shape - an int, or a tuple of ints
Returns
a shape tuple
"""
try:
i = int(shape)
return (i,)
except TypeError:
... | bigcode/self-oss-instruct-sc2-concepts |
def batch_size(y_true, y_pred):
"""Count the number of items in the current batch."""
return y_true.shape[0] | bigcode/self-oss-instruct-sc2-concepts |
import time
def convert_atom_timestamp_to_epoch(text):
"""Helper function to convert a timestamp string, for instance
from atom:updated or atom:published, to milliseconds since Unix epoch
(a.k.a. POSIX time).
`2007-07-22T00:45:10.000Z' ->
"""
return str(int(time.mktime(time.strptime(text.spli... | bigcode/self-oss-instruct-sc2-concepts |
def find_field(d, candidates):
"""
Given a dict and a list of possible keys, find the first key
which is included into this dict. Throws ValueError if not found.
"""
for c in candidates:
if c in d:
return c
raise ValueError(f"Can't find any of: {candidates}") | bigcode/self-oss-instruct-sc2-concepts |
def __renumber(dictionary):
"""Renumber the values of the dictionary from 0 to n
"""
count = 0
ret = dictionary.copy()
new_values = dict([])
for key in dictionary.keys():
value = dictionary[key]
new_value = new_values.get(value, -1)
if new_value == -1:
new_va... | bigcode/self-oss-instruct-sc2-concepts |
def get_container_type(full_name: str) -> type:
"""
get a new type to be used as a container
Args:
full_name (str): full name to distinguish from other types.
Returns:
type: a new type
"""
cls_name = "".join([name.capitalize() for name in full_name.split(".")])
return type... | bigcode/self-oss-instruct-sc2-concepts |
def leadingzero(number, minlength):
"""
Add leading zeros to a number.
:type number: number
:param number: The number to add the leading zeros to.
:type minlength: integer
:param minlength: If the number is shorter than this length than add leading zeros to make the length correct.
:retur... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _find_json(db_dir):
"""Search with tags.
Args:
db_dir (str): Directory path which has database files.
Returns:
(list): List of json file path.
"""
p = Path(db_dir)
json_list = list(p.glob("**/*.json"))
json_list.sort()
return json_list | bigcode/self-oss-instruct-sc2-concepts |
def ConvertToInterval(timestamp):
"""Converts a datetime timestamp to a time interval for a cron job.
Args:
timestamp: a datetime.datetime object
Returns:
A value between 0 and 55 corresponding to the interval the timestamp
falls in. In this calculation, 12am on Monday is interval 0 and each
int... | bigcode/self-oss-instruct-sc2-concepts |
def flops_to_string(flops):
"""Converts flops count to a human-readable form"""
flops_str = ''
if flops // 10 ** 9 > 0:
flops_str = str(round(flops / 10. ** 9, 2)) + 'GMac'
elif flops // 10 ** 6 > 0:
flops_str = str(round(flops / 10. ** 6, 2)) + 'MMac'
elif flops // 10 ** 3 > 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def replace_final_line(edited_lines):
"""Replace final line internal tutorial link with external links."""
expected_final_line = (
"For a more thorough introduction,"
" check out the :ref:`tutorial`.\n"
)
new_final_line = (
"You can find the complete documentation"
"\ninc... | bigcode/self-oss-instruct-sc2-concepts |
def _create_padded_message(message: str) -> str:
"""Create padded message, used for encrypted responses."""
extra = len(message) % 16
return (16 - extra) * "0" + message | bigcode/self-oss-instruct-sc2-concepts |
def basic_stats(db):
"""Collect basic statistics to be fed to output functions"""
rps = len(list(db['rp'].keys()))
users = len(list(db['users'].keys()))
logins = db['logins']
return {"rps": rps, "users": users, "logins": logins} | bigcode/self-oss-instruct-sc2-concepts |
def strip_chrom(chrom):
"""
Remove Chr or chr from the chromosome id
:param chrom: String
:return: String
"""
if 'chr' in chrom.lower():
return chrom[3:]
else:
return chrom | bigcode/self-oss-instruct-sc2-concepts |
def _get_user_display_name(user):
"""Return a human-friendly display name for a user."""
# An anonymous user has no display name
if user.is_anonymous:
return ''
# Form display name by concatenating first and last names and stripping whitespace
display_name = user.get_full_name().strip()
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def fragment_list(tot_len, n_frags):
"""
A little function to help trouble shoot list_chunker. Creates a list of lists
by randomly fragmenting range(tot_len) into n_frags list
Args:
tot_len: the total number of elements in the lists
n_frags: the number of lists
Retu... | bigcode/self-oss-instruct-sc2-concepts |
def _time_last_active(cluster_summary, steps):
"""When did something last happen with the given cluster?
Things we look at:
* cluster's ``CreationDateTime`` (always set)
* cluster's ``ReadyDateTime`` (i.e. when bootstrapping finished)
* step's ``CreationDateTime`` for any step
* step's ``Start... | bigcode/self-oss-instruct-sc2-concepts |
import re
def format_imports(text):
"""
Takes a string of text and formats it based on rule 3 (see docs).
"""
# rule to find consective imports
regex4 = r"^import[\s\w]+?(?=from|^\s*$)"
# this subsitution will happen with a function
def subst4(match_obj):
pattern = r"import (\w+)"... | bigcode/self-oss-instruct-sc2-concepts |
def rev_vid(image):
"""
Performs reverse video filter on input image.
:param image: an ndarray for a single-layer greyscale image,
where each element corresponds to a pixel.
:return: An ndarray that is the reverse video of input
"""
inverted = 255 - image
return inverted | bigcode/self-oss-instruct-sc2-concepts |
def get_central_meridian(srs):
"""
Get the central meridian of the projection
Parameters
----------
srs : object
OSR spatial reference system
Returns
-------
: float
central meridian
"""
return srs.GetProjParm('central_meridian', 0.0) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Callable
from typing import Any
def _dict_from_terse_tabular(
names: List[str],
inp: str,
transformers: Dict[str, Callable[[str], Any]] = {})\
-> List[Dict[str, Any]]:
""" Parse NMCLI terse tabular output into a lis... | bigcode/self-oss-instruct-sc2-concepts |
def snake2pascal(string: str):
"""String Convert: snake_case to PascalCase"""
return (
string
.replace("_", " ")
.title()
.replace(" ", "")
) | bigcode/self-oss-instruct-sc2-concepts |
def taille(arbre):
"""Renvoie la taille de l'arbre"""
if arbre is None:
return 0
else:
return 1 + taille(arbre.get_gauche()) + taille(arbre.get_droite()) | bigcode/self-oss-instruct-sc2-concepts |
def event_callback(callback, **kw):
"""
Add keyword arguments to the event callback.
"""
return lambda evt: callback(evt,**kw) | 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.