seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def parse_none_or_string(value):
""" This function is primarily used to parse command-line arguments. Whenever
the string 'None' is passed, it will return it as None, otherwise it will return
whatever it was passed as a string.
"""
if value == 'None':
return None
return value | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def about_package(init_posixpath: pathlib.Path) -> dict:
"""
Return package information defined with dunders in __init__.py as a dictionary, when
provided with a PosixPath to the __init__.py file.
"""
about_text: str = init_posixpath.read_text()
return {
entry.split(" = ... | bigcode/self-oss-instruct-sc2-concepts |
def divide_to_keys(dict_all_embeddings):
"""
Distinguish between types of embedding methods - ours and state-of-the-art
:param dict_all_embeddings: dict of all embeddings
:return: Names of our methods, names of state-of-the-art methods
"""
keys_ours = []
keys_state_of_the_art = []
keys =... | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
def get_valid_urls(url, break_url):
"""
Get valid urls from sitemap.xml. Note: only links after group-49 are valid for download.
- url: the link to stemap.xml
- break_url: the url link to the group-49
>>> url = "https://apkpure.com/sitemap.xml... | bigcode/self-oss-instruct-sc2-concepts |
def get_correlation_values(cors, r, c):
"""
Gets correlation between properties r and c for all files
Parameters
----------
cors : list
propertiess correlations per file
r : int
first property index
c : int
second property index
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def get_vendor_from_mac(mac):
"""Get the vendor from the MAC using an API"""
url = "https://mac2vendor.com/api/v4/mac/"
mac_str = "".join(mac.split(":")[:3])
try:
r = requests.get(url + mac_str)
response = json.loads(r.text)
if not response["success"... | bigcode/self-oss-instruct-sc2-concepts |
def next_name(container, key):
"""
Given a container object and some key prefix, yield the next key with the
given prefix that is not contained into container.
"""
if key not in container:
return key
for i in range(1, 1000):
test = f"{key}_{i}"
if test not in container:
... | bigcode/self-oss-instruct-sc2-concepts |
def measurement_exists(cur, project_key, id):
"""
Check whether the measurement exists in the database in the given project.
"""
measurement = cur.execute(
"SELECT * FROM measurements WHERE id=? AND projects_key=?", (id, project_key)
).fetchone()
if not measurement:
return False... | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def divide2(a, b):
"""Return a/b.
If b = 0, raise a warning and return the NaN ("Not a Number") value."""
if b == 0:
warnings.warn("Division by zero !")
return float("nan")
else:
return a/b | bigcode/self-oss-instruct-sc2-concepts |
import torch
def clip_linear(values, a, b):
"""Clip values to [-1, 1]
Input:
- values(torch tensor): values to be clipped
- a (float): coefficient
- b (float): intersection
Output: (torch tensor) clipped values
"""
return torch.clamp(values * a + b, -1, 1) | bigcode/self-oss-instruct-sc2-concepts |
def to_camel_case(snake_str):
"""
Converts snake_string to camelCase
:param str snake_str:
:returns: str
"""
components = snake_str.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | bigcode/self-oss-instruct-sc2-concepts |
import typing
import textwrap
def WrapText(text: str, length: int) -> typing.List[str]:
"""
A function that wraps text.
Parameters
----------
text : str
The text to wrap.
length : int
The length to wrap the text at.
Returns
-------
typing.List[str]
A list ... | bigcode/self-oss-instruct-sc2-concepts |
def data_split(dataset, n_test_set=30):
"""
split data into train and test sets
Arguments:
----------
dataset: pd.DataFrame
- time series dataset
n_test_set: int
- the last n data points
Returns:
--------
X_train : pd.DataFrame
- training set
X_test : pd... | bigcode/self-oss-instruct-sc2-concepts |
import re
def match_first(string, prefix_infos, key):
"""Match string against each regex. Return first match, or None"""
for prefix_info in prefix_infos:
regex = prefix_info.get(key)
if regex:
match = re.match(regex, string)
if match:
prefix_info["match... | bigcode/self-oss-instruct-sc2-concepts |
def sign(x):
"""
Returns the sign of x.
:param x:
:return:
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
import re
def grep(regex, output):
"""Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the exp... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_enrollment_record_data() -> dict:
"""Helper method for generating data for an EnrollmentRecord"""
return {
"csp_user_uuid": uuid.uuid4(),
"first_name": "Bob",
"last_name": "Testington",
} | bigcode/self-oss-instruct-sc2-concepts |
import torch
def to_onehot(indices: torch.Tensor, num_classes: int) -> torch.Tensor:
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...) and of type uint8. Output's device is equal to the
input's device`.
"""
onehot = torch.zeros... | bigcode/self-oss-instruct-sc2-concepts |
import random
def block_permutation(preserve_symmetry = True):
"""Choose order to rearrange rows or columns of blocks."""
if preserve_symmetry:
return random.choice([[0,1,2],[2,1,0]])
result = [0,1,2]
random.shuffle(result)
return result | bigcode/self-oss-instruct-sc2-concepts |
def first_char_is_number(text):
"""Check if string starts with a number."""
return text[0].isdigit() | bigcode/self-oss-instruct-sc2-concepts |
def extract_authors(pubs):
"""Get list of author IDs from a list of namedtuples representing
publications.
"""
l = [x.author_ids.split(";") for x in pubs if isinstance(x.author_ids, str)]
return [au for sl in l for au in sl] | bigcode/self-oss-instruct-sc2-concepts |
def no_perf_degrad(optimzed_time: float, non_optimized_time: float, rtol: float = 5e-2) -> bool:
"""Assert no performance degradation.
Args:
optimzed_time (float): [description]
non_optimized_time (float): [description]
rtol (float, optional): Max tolerant runtime degradation. Defaults ... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_model_colnames(model_colnames):
"""
From a dict that maps model name to a list of field names, generate a list with string elements `<module>.<field>`.
"""
flat_colnames = []
for modelname, colnames in model_colnames.items():
flat_colnames.extend([modelname + '.' + c for c in col... | bigcode/self-oss-instruct-sc2-concepts |
def line_plot(ax, x, ys, labels=None, styles=None, param_dict=None):
"""
A helper function to make a line graph
Parameters
----------
ax : Axes
The axes to draw to
x : array
The x data
ys : array
The y data
labels : list
The ys labels
param_dict : di... | bigcode/self-oss-instruct-sc2-concepts |
def _intersect(a, b):
"""Returns the Intersection of two sets.
Returns common elements of two iterables
._intersect("apples", "oranges") returns "aes"
Args:
a, b: iterables that can be compared
Returns:
list of common elements between the two input iterables
"""
retu... | bigcode/self-oss-instruct-sc2-concepts |
def jenkins_api_query_build_statuses(jenkins_url):
"""Construct API query to Jenkins (CI)."""
return "{url}/api/json?tree=builds[result]".format(url=jenkins_url) | bigcode/self-oss-instruct-sc2-concepts |
import torch
import copy
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList(copy.deepcopy(module) for _ in range(num_copies)) | bigcode/self-oss-instruct-sc2-concepts |
def integer_if_integral(x):
"""Convert a float to int if it can be represented as an int"""
return int(x) if x == int(x) else x | bigcode/self-oss-instruct-sc2-concepts |
def proportion_of_energy_delivered(sim):
""" Calculate the percentage of total energy delivered over total energy requested.
Args:
sim (Simulator): A Simulator object which has been run.
Returns:
float: Proportion of total energy requested which was delivered during the simulation.
"""... | bigcode/self-oss-instruct-sc2-concepts |
def d(d):
"""Decode the given bytes instance using UTF-8."""
return d.decode('UTF-8') | bigcode/self-oss-instruct-sc2-concepts |
def profile_key(prof):
"""Get the sort key for profiles."""
if prof == 'core':
return (0, prof)
return (1, prof) | bigcode/self-oss-instruct-sc2-concepts |
def identify(rod, x, y):
"""Adds chip ids (chip_x, chip_y) to the key for a rod
Args:
rod: dict of (x, y): [values]
x: x coordinate that identifies the source chip
y: y coordinate that identifies the source chip
Returns:
dict: {(chip_x, chip_y, x, y): [values]}
... | bigcode/self-oss-instruct-sc2-concepts |
def datagenerator_affine(gen,test = False):
"""
Datagenerator for the affine network (both stages)
Args:
gen: an image generator, loading the image, indicator, loss placeholders and landmarks
test: True in case we test the function
Returns:
generator to train the affine networ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def get_value_len(dct: Dict[Any, Any]) -> Dict[Any, int]:
"""Get length of each dictionary value.
Args:
dct: Python `dict()` object.
Returns:
`dict()` object.
Example:
>>> status_codes = {
200: ['google.com', 'so... | bigcode/self-oss-instruct-sc2-concepts |
def plant_pm_heat_rates(annual_gen_fuel_923):
"""
Calculate the heat rate by plant, prime mover, and fuel type. Values are saved
as a dictionary.
Parameters
----------
annual_gen_fuel_923 : dataframe
Data from the 923 generation and fuel use table. Heat rate for each row should
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_nested_tuple(tup):
""" Hash a nested tuple to hexadecimal """
return hashlib.md5(repr(sorted(tup)).encode('utf8')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def get_icon_detail(icon_details):
"""
Iterate over icon details from response.
This method is used in "risksense-get-apps" command.
:param icon_details: Icon details from response.
:return: List of required icon detail dictionary.
"""
return [{
'Type': icon_detail.get('type', ''),
... | bigcode/self-oss-instruct-sc2-concepts |
def _maybe_parse_as_library_copts(srcs):
"""Returns a list of compiler flags depending on `main.swift`'s presence.
Builds on Apple platforms typically don't use `swift_binary`; they use
different linking logic (https://github.com/bazelbuild/rules_apple) to
produce fat binaries and bundles. This means t... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def get_parameters_from_path(store, paths, **kwargs):
"""
Gets parameters from the specified paths and combines them
into one dictionary. Values that are the same WILL be overwritten.
Arguments:
store {EC2ParameterStore} -- The AWS Parameter Store you wish t... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def construct_diag(x):
"""
Constructs a diagonal matrix based on batched data. Solution found here:
https://stackoverflow.com/questions/47372508/how-to-construct-a-3d-tensor-where-every-2d-sub-tensor-is-a-diagonal-matrix-in-p
Do note that it only considers the last axis.
:param x: The... | bigcode/self-oss-instruct-sc2-concepts |
def dim(self):
"""Return the dimensionality of the ambient space."""
return self.shape[-1] | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_id(length: int = 8) -> str:
"""Sample a random string to use for job id."""
return "".join(random.sample(string.ascii_letters + string.digits, length)) | bigcode/self-oss-instruct-sc2-concepts |
def param_uses_64bits(param):
"""Returns True iff a syscall parameter description corresponds
to a 64-bit type."""
param = param.strip()
# First, check that the param type begins with one of the known
# 64-bit types.
if not ( \
param.startswith("int64_t") or param.startswith("uint64_t"... | bigcode/self-oss-instruct-sc2-concepts |
def contingency(set1,set2,all_genes):
"""Creates contingency table for gene enrichment
set1: Set of genes (e.g. regulon)
set2: Set of genes (e.g. i-modulon)
all_genes: Set of all genes
"""
tp = len(set1 & set2)
fp = len(set2 - set1)
tn = len(all_genes - set1 - set2)
... | bigcode/self-oss-instruct-sc2-concepts |
def lastFrameFromSegmentLength(dist, first_frame, length):
"""Retrieves the index of the last frame for our current analysis.
last_frame should be 'dist' meters away from first_frame in terms of distance traveled along the trajectory.
Args:
dist (List[float]): distance along the trajectory, incr... | bigcode/self-oss-instruct-sc2-concepts |
def lyrics_to_frequencies(wordlist):
"""
wordlist (list): list of words (strings) of song lyrics
Returns a dictionary mapping different lyrics words to their frequencies or number of occurences
"""
myDict = {}
for word in wordlist:
if word in myDict:
myDict[word] += 1
... | bigcode/self-oss-instruct-sc2-concepts |
import time
def get_timestamp(date_time):
"""
Create a `timestamp` from a `datetime` object. A `timestamp` is defined
as the number of milliseconds since January 1, 1970 00:00. This is like
Javascript or the Unix timestamp times 1000.
"""
return time.mktime(date_time.timetuple()) * 1000 | bigcode/self-oss-instruct-sc2-concepts |
def getattr_deep(obj, attrs):
"""
Like getattr(), but checks in children objects
Example:
X = object()
X.Y = childobject()
X.Y.variable = 5
getattr(X, 'Y.variable') -> AttributeError
getattr_deep(X, 'Y.variable') -> 5
:param obj: object
:param attrs: attribu... | bigcode/self-oss-instruct-sc2-concepts |
def chunk_file(fname, *, limit=5000, start_num=0):
"""
This function is inexorably tied to extras.fetch_eddb.jq_post_process.
Importantly jq doesn't wrap in list brackets or end in ','
Take any file with fname. Chunk that file out with limit lines per file.
Each chunk will be written to a file with... | bigcode/self-oss-instruct-sc2-concepts |
def get_base_url(parsed):
"""Convert a parsed URL back to string but only include scheme, netloc, and path, omitting query."""
return parsed.scheme + "://" + parsed.netloc + parsed.path | bigcode/self-oss-instruct-sc2-concepts |
import re
def css_colour(s):
"""Is string a valid CSS colour."""
m = re.match(r'^(?:[0-9a-fA-Z]{3}){1,2}$', s)
return m is not None | bigcode/self-oss-instruct-sc2-concepts |
def to_str(text, session=None):
"""
Try to decode a bytestream to a python str, using encoding schemas from settings
or from Session. Will always return a str(), also if not given a str/bytes.
Args:
text (any): The text to encode to bytes. If a str, return it. If also not bytes, convert
... | bigcode/self-oss-instruct-sc2-concepts |
def get_regression_predictions(input_feature, intercept, slope):
"""
Purpose: Compute predictions
Input : input_feature (x), intercept (w0), slope (w1)
Output : Predicted output based on estimated intercept, slope and input feature
"""
predicted_output = intercept + slope * input_feature
re... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def rand_string(numOfChars):
"""
Generates a string of lowercase letters and numbers.
That makes 36^10 = 3 x 10^15 possibilities.
If we generate filenames randomly, it's harder for people to guess filenames
and type in their URLs directly to bypass permissions.
"""... | bigcode/self-oss-instruct-sc2-concepts |
def always_str_list(list_or_str):
"""Makes sure list_or_str is always a tuple or list
Parameters
----------
list_or_str: str or str iterable (tuple, list, ...)
Parameter to set as iterable if single str.
Returns
-------
Iterable
Iterable equivalent to list_or_str."""
if... | bigcode/self-oss-instruct-sc2-concepts |
def find_faces_at_edges(faces):
"""
For each edge on the mesh, find the two faces that share the edge.
Parameters
----------
faces : list of lists of three integers
the integers for each face are indices to vertices, starting from zero
Returns
-------
faces_at_edges : dictionar... | bigcode/self-oss-instruct-sc2-concepts |
def get_id_from_urn(urn):
"""
Return the ID of a given Linkedin URN.
Example: urn:li:fs_miniProfile:<id>
"""
return urn.split(":")[3] | bigcode/self-oss-instruct-sc2-concepts |
def datetime_encode(obj):
"""Encode a datetime."""
return obj.isoformat() | bigcode/self-oss-instruct-sc2-concepts |
def derivative_sigmoid(y: int) -> float:
"""Calculate the derivative of the sigmoid function
Args:
y (int): the output of the sigmoid function of x
Returns:
float: the output of the derivative sigmoid function
"""
return y * (1 - y) | bigcode/self-oss-instruct-sc2-concepts |
def get_header(context, header_name):
"""Return all response header values that've been set for header_name."""
return [header[1] for header in context.headers if header[0] == header_name] | bigcode/self-oss-instruct-sc2-concepts |
def calculate_ngram_freqs_solution(ngrams):
"""Calculate the frequency of a subsequent word given a sequence of ngrams
:param ngrams: [['i', 'will', 'be'], ['will', 'be', 'leaving'], ['be', 'leaving', 'florida']]
"""
freqs = {}
for ngram in ngrams:
# Differentiate successor (= lastWord) ... | bigcode/self-oss-instruct-sc2-concepts |
import math
import torch
def simpleLambda(x, scale, sigma=1.0):
"""
De-noising by Soft-thresholding. Author: David L. Donoho
:param x: one block of wavelet coefficients, shape [num_nodes, num_hid_features] torch dense tensor
:param scale: the scale of the specific input block of wavelet coefficients,... | bigcode/self-oss-instruct-sc2-concepts |
def sort(data):
"""
Sort list of reminders by time (oldest first).
"""
return sorted(data, key=lambda k: (k['time'])) | bigcode/self-oss-instruct-sc2-concepts |
def find_gvfs(lineages, gvf_list):
"""This function searches for gvf files in a directory which have
filenames that contain specified lineage names.
:param lineages: Pangolin lineages to include in the report
:type lineages: list of strings
:param gvf_list: directory to search for gvf files
:typ... | bigcode/self-oss-instruct-sc2-concepts |
def __int_to_bool(records: dict) -> dict:
"""Convert integer values to Boolean values."""
for k, v in records.items():
if isinstance(v, int):
records[k] = bool(v)
return records | bigcode/self-oss-instruct-sc2-concepts |
def CalculateForecastStats(matched, available, possible=None):
"""Calculate forecast percentage stats.
Args:
matched: The number of matched impressions.
available: The number of available impressions.
possible: The optional number of possible impressions.
Returns:
The percentage of impressions t... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def is_existent_file(potential_file: Path) -> bool:
"""Assess if a Path points to a file that exists."""
return potential_file.exists() and potential_file.is_file() | bigcode/self-oss-instruct-sc2-concepts |
def int_to_str_add_zeros(number):
"""
Turn an int to a sting and make sure it has 6 digit (add zeros before if
needed)
"""
if type(number) != int:
print("File number should be an integer.\n")
if number < 0:
print("File number can't be negative.\n")
elif number > 999999:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_norm(torch_tensor, dim=0, order=2):
"""Get the norm of a 2D tensor of the specified dim
Parameters
----------
torch_tensor : torch.tensor
2-dimensional torch tensor
dim : int, optional
order : float, optional
Returns
-------
torch_tensor : a 1-dimensi... | bigcode/self-oss-instruct-sc2-concepts |
def potencia(base, exponente):
"""
(num, num) -> num
Calclula la potencia dada una base y un exponente
>>> potencia(2,3)
8
>>> potencia(2,8)
256
>>> potencia(5,3)
125
:param base: la base de la operacion
:param exponente: la cantidad de veces que se debe multiplicar por si... | bigcode/self-oss-instruct-sc2-concepts |
def get_variables(models):
"""get variables of all models
Args:
models: dict containing all the models available
Returns:
variables: variables of all models
"""
variables = []
for model in models.keys():
variables += models[model].variables
return variables | bigcode/self-oss-instruct-sc2-concepts |
def params_to_lists(params):
"""Dictionaries are more convenient for storing and working with the parameters of the gaussians and lorentzians,
but leastsq wants the initial parameters as a list (as far as I can tell...). This will take a list of dictionaries
and convert it to a single list according to the ... | bigcode/self-oss-instruct-sc2-concepts |
import logging
import traceback
import time
def retry(tries, delay=1, backoff=2):
"""A retry decorator with exponential backoff.
Functions are retried when Exceptions occur.
Args:
tries: int Number of times to retry, set to 0 to disable retry.
delay: float Initial sleep time in seconds.
backoff: f... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def gather_word_outputs(outputs):
"""
'outputs' is a list of 'output' of each GPU. As a reminder, each 'output' is a 3-tuple where:
- output[0] is the last_hidden_state, i.e a tensor of shape (batch_size, sequence_length, hidden_size).
- output[1] is the pooler_output, i.e. a tens... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def decypher_date(datestr):
""" Turn 12/17/2016 style dates that Goodgle sheets gives us
and convert into a datetime object
"""
split = datestr.split('/')
return datetime(int(split[2]), int(split[0]), int(split[1])) | bigcode/self-oss-instruct-sc2-concepts |
def merge(a: list, b: list) -> list:
"""Merges two sorted lists into one sorted list"""
i = 0
j = 0
result = []
while i < len(a) and j < len(b):
if a[i] < b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
while i < ... | bigcode/self-oss-instruct-sc2-concepts |
def find_closest_index(L,t):
"""
Find the index of the closest value in a list.
Input:
L -- the list
t -- value to be found
Output:
index of the closest element
"""
beginning = 0
difference = abs(L[0] - t)
best = 0
end = len(L)
while beginning < end:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_attrib(xml_obj, attrib):
"""Get an arbitrary XML attribute"""
return xml_obj.attrib[attrib] | bigcode/self-oss-instruct-sc2-concepts |
import ast
def make_arg(key, annotation=None):
"""Make an ast function argument."""
arg = ast.arg(key, annotation)
arg.lineno, arg.col_offset = 0, 0
return arg | bigcode/self-oss-instruct-sc2-concepts |
def get_max_len(files_list):
"""Get the length of the file with the longest filename"""
ret = 0
if len(files_list) > 0:
filename_lengths = [len(x) for x in files_list]
max_len = max(filename_lengths)
ret = max_len
return ret | bigcode/self-oss-instruct-sc2-concepts |
def _artifact_display_versions(versions):
"""Return a list of artifact versions for display purposes.
This is slightly different than the 'versions' property of the artifact, as
it is reverse-sorted (newest at the top) and also enumerated so that while
it's reversed, the numbers still indicate chronolo... | bigcode/self-oss-instruct-sc2-concepts |
def replace_with_median(col, value_to_replace):
"""Replaces a dummy number with the median of the other numbers in the column.
Parameters
----------
col : Pandas DataFrame column with numeric values
value_to_replace : Dummy value that needs to be replaced
Returns
---... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_datetime(dict_date):
""" Convert json date entry to datetime.
:param dict_date: Date as retrieved from kanka in the format "YYYY-mm-dd HH:MM:SS.000000"
:type dict_date: string
:return: Date converted to python datetime object
:rtype: datetime.datetime
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clear_path_string(s):
"""
Simple function that removes chars that are not allowed in file names
:param s: path_string
:return: cleaned_path_string
"""
return (re.sub('[^a-zA-Z]+', '#', s)).lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
def format_validation_errors(validation_errors: Dict[str, List[str]]) -> str:
"""Return marshmallow validation errors formatted as a single string."""
return ', '.join(
'{}: {}'.format(key, value[0])
for key, value in validation_errors.items()
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def load_data(path_to_csv, num_samples=None):
"""
Read the csv file given and return the path to images and steering angles
"""
image_path = []
steering_angle = []
with open(path_to_csv, "r", newline='') as f:
recorded_data = csv.reader(f, delimiter=',', quotechar='|')
... | bigcode/self-oss-instruct-sc2-concepts |
def get_c(layer_configs):
"""Find input channels of the yolo model from layer configs."""
net_config = layer_configs['000_net']
return net_config.get('channels', 3) | bigcode/self-oss-instruct-sc2-concepts |
def get_format(s):
"""
Returns the Open Babel format of the given string.
Note: It is primitive, distinguishes only xyz, smiles, inchi formats.
>>> print(get_format('C'))
smi
>>> print(get_format('InChI=1S/H2O/h1H2'))
inchi
>>> print(get_format(get_xyz('C')))
xyz
"""
frm = 'u... | bigcode/self-oss-instruct-sc2-concepts |
def get_first_word(tabbed_info):
"""
Get the first word in a sentence, this is useful when
we want to get file type, for instance,
>> get_first_word('bigBed 6 +') will return 'bigBed'
:param tabbed_info: the string (e.g. 'bigBed 6 +')
:returns: the first word in the string
"""
return tab... | bigcode/self-oss-instruct-sc2-concepts |
def iscircular(linked_list):
"""
Determine whether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
if linked_list.head == None:
return False
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_network_mask(raw_address) -> List[int]:
"""
Return a network mask from the given raw address.
>>> get_network_mask('0.0.0.0/8')
[255, 0, 0, 0]
>>> get_network_mask('0.0.0.0/9')
[255, 128, 0, 0]
>>> get_network_mask('0.0.0.0/32')
[255, 255, 255, 255]
... | bigcode/self-oss-instruct-sc2-concepts |
def find_subscript_name(subscript_dict, element):
"""
Given a subscript dictionary, and a member of a subscript family,
return the first key of which the member is within the value list.
If element is already a subscript name, return that
Parameters
----------
subscript_dict: dictionary
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def csv_dict_reader(file_obj):
"""
Read a CSV file using csv.DictReader
"""
return csv.DictReader(file_obj, delimiter=',') | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pdist(vectors):
"""
vectors shape: (batch_size, k-dimensions)
compute the Euclidean distance between any two pairs.
using formula distance = ||A - B||^2 = A'A + B'B - 2A'B
note: A, B represent vector, respectively. A' denotes transpose of A
:param vectors: embeddings of batch_... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
from typing import Callable
def is_before(time: datetime, now: Callable[[], datetime]=datetime.now) -> Callable[[], bool]:
"""
:param time: A time
:param now: A function to use to get the current time (defaults to datetime.now)
:return: A predicate that checks if the curr... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_index_time(index_timestamp, separator='.'):
""" Gets the time of the index.
:param index_timestamp: A string on the format YYYY.MM.DD[.HH]
:return The creation time (datetime) of the index.
"""
try:
return datetime.strptime(index_timestamp, separator.... | bigcode/self-oss-instruct-sc2-concepts |
def solution(array):
"""
Computes number of distinct values in an array.
"""
# Sets only have distinct values
# and creating a set from a list has a good time complexity, as it uses hash tables
return len(set(array)) | bigcode/self-oss-instruct-sc2-concepts |
def tokenize(s, keep_punctuation=(), drop_punctuation=(), delimiter=' ',
add_start=True, add_end=True):
"""Tokenizes a sentence
Args:
s (str): the sentence
keep_punctuation (tuple): contains the punctuation to keep
drop_punctuation (tuple): contains the punctuation to drop
... | bigcode/self-oss-instruct-sc2-concepts |
def create_extra_dimensions_stats(customer_records_by_extra_dim):
"""Groups entry records by customer_id and extra_dimension.
Args:
customer_records_by_extra_dim: Tuple containing a tuple of customer_id
and extra_dimension and a list of transaction records related to
that combin... | bigcode/self-oss-instruct-sc2-concepts |
def db2lin(value):
"""Convert logarithimic units to linear
>>> round(db2lin(10.0), 2)
10.0
>>> round(db2lin(20.0), 2)
100.0
>>> round(db2lin(1.0), 2)
1.26
>>> round(db2lin(0.0), 2)
1.0
>>> round(db2lin(-10.0), 2)
0.1
"""
return 10**(value / 10) | 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.