seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def flatten_list(_list):
""" [(1,2), (3,4)] -> [1, 2, 3, 4]"""
return sum([list(item) for item in _list], []) | bigcode/self-oss-instruct-sc2-concepts |
def validate_byr(birth_year: str) -> bool:
"""byr (Birth Year) - four digits; at least 1920 and at most 2002."""
return len(birth_year) == 4 and int(birth_year) >= 1920 and int(birth_year) <= 2002 | bigcode/self-oss-instruct-sc2-concepts |
def is_restart_command(command_text: str) -> bool:
"""
>>> is_restart_command("restart")
True
>>> is_restart_command("restart game")
True
>>> is_restart_command("take lamp")
False
"""
return command_text.startswith("restart") | bigcode/self-oss-instruct-sc2-concepts |
def _strip(string):
"""
Removes unicode characters in string.
"""
return "".join([val for val in string if 31 < ord(val) < 127]) | bigcode/self-oss-instruct-sc2-concepts |
def measurement_ids_and_names(experiment_proto):
"""List all measurement IDs and names for an experiment.
Results are sorted by measurement ID.
Args:
experiment_proto: selection_pb2.Experiment describing the experiment.
Returns:
measurement_ids: tuple of integer IDs for each measurement.
column_n... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def noclook_last_seen_to_dt(noclook_last_seen):
"""
Returns noclook_last_seen property (ex. 2011-11-01T14:37:13.713434) as a
datetime.datetime. If a datetime cant be made None is returned.
"""
try:
dt = datetime.strptime(noclook_last_seen, '%Y-%m-%dT%H:%M:%S.%... | bigcode/self-oss-instruct-sc2-concepts |
def split_dataframe(df, chunk_size):
"""
splits a pandas dataframe into a list of sub-dataframes by size of chunk_size
"""
df = df.iloc[::-1] #reverse the dataframe
chunks = list()
for i in range(len(df)): #for amount of days in df
if len(df[i:i+chunk_size]) is chunk_size:
... | bigcode/self-oss-instruct-sc2-concepts |
def _is_dunder(name):
"""Returns True if name is a __dunder_variable_name__."""
return len(name) > 4 and name.startswith('__') and name.endswith('__') | bigcode/self-oss-instruct-sc2-concepts |
def get_matching_items_from_dict(value, dict_name):
"""
Return all items in a dict for which the label matches the provided value.
@param value: the value to match
@param dict_name: the dict to look in
"""
matches = [dict_name[x]["items"]
for x in dict_name if x.lower() == value]... | bigcode/self-oss-instruct-sc2-concepts |
def build_entity(key, value):
"""
build_entity return a dict that can be passed back to rasa as an entity
using the given string key and value
"""
return {"entity": key, "value": value, "start": 0, "end": 0} | bigcode/self-oss-instruct-sc2-concepts |
def to_float(nmb: str):
"""
convert numbers from rinex files to python floats
rinex floats can either be:
4.391254341941D-09
4.391254341941E-09
that is, the scientific notation can use the ´E´ or ´D´ char
"""
try:
flt = float(nmb)
except ValueError:
nmb = nmb... | bigcode/self-oss-instruct-sc2-concepts |
def get_vertical_layers_centroids_list(vert_layers):
""" Returns a list with points that are the centroids of the heads of all vertical_layers_print_data. The head
of a vertical_layer is its last path. """
head_centroids = []
for vert_layer in vert_layers:
head_centroids.append(vert_layer.head_c... | bigcode/self-oss-instruct-sc2-concepts |
def read(path, as_single_string=False):
"""Read the file at the path and return its contents as a list or string."""
the_file = open(path, 'r')
if as_single_string:
contents = the_file.read()
else:
contents = the_file.readlines()
the_file.close()
return contents | bigcode/self-oss-instruct-sc2-concepts |
def _observed_name(field, name):
"""Adjust field name to reflect `dump_to` and `load_from` attributes.
:param Field field: A marshmallow field.
:param str name: Field name
:rtype: str
"""
# use getattr in case we're running against older versions of marshmallow.
dump_to = getattr(field, 'du... | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates(nonunique):
"""Remove duplicate values in a list.
Args:
nonunique (list) - a list of values
Returns:
a list of the unique values in the nonunique list
Example:
unique_values(['a', 'a', 'b', 'c']) --> ['a', 'b', 'c']
"""
un... | bigcode/self-oss-instruct-sc2-concepts |
def is_grayscale(image):
"""
Check if given image is in grayscale color space.
:param image: checked image
:return: result of the check (boolean value)
"""
GRAYSCALE_DIMENSION_COUNT = 2
return len(image.shape) == GRAYSCALE_DIMENSION_COUNT | bigcode/self-oss-instruct-sc2-concepts |
def Dutch_Flag(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
Adapted from https://en.wikipedia.org/wiki/Dutch_national_flag_problem
"""
#Null input
if input_list == None:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_filepath(video_id):
"""
Returns the filepath of the video in the clevrer directory
Args:
video_id(int): The id of the video obtained from the json
Returns:
filepath(string): the path from the dataset directory to the video
Ex: image_00000-01000/video_00428
"""
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def _to_list(scalar_or_iter):
"""Convert scalars and iterables to list.
Parameters
----------
scalar_or_iter : str or list
Returns
-------
list
Examples
--------
>>> _to_list("a")
['a']
>>> _to_list(["b"])
['b']
"""
return (
... | bigcode/self-oss-instruct-sc2-concepts |
def construct_runtime_cache_folder(runtime_cache_prefix, ios_version):
"""Composes runtime cache folder from it's prefix and ios_version.
Note: Please keep the pattern consistent between what's being passed into
runner script in gn(build/config/ios/ios_test_runner_wrapper.gni), and what's
being configured for ... | bigcode/self-oss-instruct-sc2-concepts |
def get_dhl_tweet(df, dhl_acc):
"""
Get Tweets by DHL associated accounts
Parameters
----------
df : pandas.core.frame.DataFrame
Tweets data.
dhl_acc : list
List of Twitter account usernames associated with DHL.
Returns
-------
pandas.core.frame.DataFrame
Fi... | bigcode/self-oss-instruct-sc2-concepts |
def gen_link(name, visual=None, collision=None):
"""
Generates (as a string) the complete urdf element sequence for a `link`
element. This is essentially a string concatenation operation.
If `collision` is not provided, a duplicate of `visual` will be used
instead.
:param name: Name of the lin... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compose_projection_matrix(K, M):
"""
Compose intrinsics (K) and extrinsics (M) parameters to get a projection
matrix
"""
return torch.matmul(K[:, :3], M) | bigcode/self-oss-instruct-sc2-concepts |
def add_ul(text, ul):
"""Adds an unordered list to the readme"""
text += "\n"
for li in ul:
text += "- " + li + "\n"
text += "\n"
return text | bigcode/self-oss-instruct-sc2-concepts |
def gen_var_info(var_names: list,
zip_var_name: str = "uZipVars",
offset_name: str = "offset",
enum_name: str = "VAR",
enum_prefix: str = "U",
use_const: bool = True,
enum_start_idx: int = 0,
enum_var_... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def next_page_checker(
page: dict
) -> Optional[str]:
"""This is the parser for checking "nextParams" from react page data for automatic paging in get*Iter function.
Arguments:
page (:class:`dict`) : Page data from get(Comments, Posts, etc..)
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def merge_tensors(tensor_objects, non_tensor_objects, tensor_flags):
"""
Merge two lists (or tuples) of tensors and non-tensors using a mapping of positions in merged list (or tuple).
Parameters:
tensor_objects (list/tuple): Tensors to merge.
non_tensor_objects (list/tuple): Non-tensors to m... | bigcode/self-oss-instruct-sc2-concepts |
import base64
import six
def base64_encode(text):
"""Base 64 encodes the UTF-8 encoded representation of the text. In Python
2 either a byte string or Unicode string can be provided for the text
input. In the case of a byte string, it will be interpreted as having
Latin-1 encoding. In Python 3 only a ... | bigcode/self-oss-instruct-sc2-concepts |
def no_op(*args, **kwargs):
"""
No-op function to serve as default ``get_runtime_attrs``.
"""
return None | bigcode/self-oss-instruct-sc2-concepts |
def computeFraction( poi_messages, all_messages ):
""" compute the fraction of messages to/from a person that are from/to a POI """
fraction = 0
if poi_messages == 'NaN' or all_messages == 'NaN':
fraction = 'NaN'
else:
fraction = float(poi_messages)/all_messages
return fraction | bigcode/self-oss-instruct-sc2-concepts |
def CheckForSize(collection, expected_size, equal_flag, unequal_flag,
unexpectedly_empty_flag=None):
"""Check conditions for collection size.
Args:
collection: A collection can be a list, set or dictionary.
expected_size: The expected size.
equal_flag: The value to return if the collec... | bigcode/self-oss-instruct-sc2-concepts |
def numseqstr(seq, sep=',', fmt='%0.2f'):
"""Takes a number sequence or single number and prints it using the given separator and format."""
def gets(s):
"""Returns a number formatting string using fmt if a number, else str() version"""
try: # number
return fmt % s
except Typ... | bigcode/self-oss-instruct-sc2-concepts |
def _increment_list_counter(ilvl2count, ilvl: str) -> int:
# noinspection SpellCheckingInspection
"""
Increase counter at ilvl, reset counter at deeper levels.
:param ilvl2count: context['numId2count']
:param ilvl: string representing an integer
:return: updated count at ilvl.
updates c... | bigcode/self-oss-instruct-sc2-concepts |
def merge_dicts(list_of_dicts):
"""Merge multipe dictionaries together.
Given any number of dicts, shallow copy and merge into a new dict,
precedence goes to key value pairs in latter dicts.
Args:
dict_args (list): a list of dictionaries.
Returns:
dict
"""
merge_dict = {}... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def apply_ners(query, ners):
"""
Applies each NER model passed in `ners` on `query`, taking the union set of their predictions.
Ignores various types of entities not useful for the business case.
"""
ignore = ['CARDINAL', 'DATE', 'MONEY', 'ORDINAL', 'PERCENT', 'QUANTITY... | bigcode/self-oss-instruct-sc2-concepts |
def get_ids(data):
"""
Extracts dataset IDs.
:param data: The input data
:return: IDs
"""
ids = []
for i in data:
ids.append(i.ID)
return ids | bigcode/self-oss-instruct-sc2-concepts |
def _convert_space_to_shape_index(space):
"""Map from `feature` to 0 and `sample` to 1 (for appropriate shape indexing).
Parameters
----------
space : str, values=('feature', 'sample')
Feature or sample space.
Returns
-------
return : int, values=(0, 1)
Index location of th... | bigcode/self-oss-instruct-sc2-concepts |
def next_recipe_digits(cur_recipe):
"""Calculate next recipe, based on the cur_recipe."""
if cur_recipe == 0:
return [0]
digits = []
while cur_recipe > 0:
digits.append(cur_recipe % 10)
cur_recipe = cur_recipe // 10
return digits[::-1] | bigcode/self-oss-instruct-sc2-concepts |
import re
def IsGCESlave(slavename):
"""Returns (bool): Whether |slavename| is hosted on GCE.
Args:
slavename: The hostname of the slave.
"""
# The "-c2" suffix indicates that a builder is in GCE (as opposed to
# in the Chrome Golo, which has a -m2 suffix).
return bool(re.search(r'-c\d+$', slavename)... | bigcode/self-oss-instruct-sc2-concepts |
def pesos_ady(grafo,vertice):
"""Dado un grafo y un vertice devuelve un diccionario con los vertices adyacentes
como clave y el peso de la arista como valor"""
diccionario = {}
adyacentes = grafo.ver_a_adyacentes(vertice)
for a in adyacentes:
diccionario[a[0]] = a[1]
return diccionario | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import requests
def get_request(url: str, headers: Optional[dict] = None, params: Optional[dict] = None):
"""Return response if request is successful and in JSON format"""
try:
response = requests.get(url, headers=headers, params=params).json()
except:
return
... | bigcode/self-oss-instruct-sc2-concepts |
def get_ncattrs(obj):
"""
Returns ncattrs of a netcdf object as a dictionary
:param obj: Object to collect ncattrs from
:return: dictionary representation of those ncattrs
"""
out = {}
for key in obj.ncattrs():
value = obj.getncattr(key)
if hasattr(value, 'tolist'):
... | bigcode/self-oss-instruct-sc2-concepts |
def trans_ledu(ledu):
"""
Translates the level of education code to a human-readable string
"""
retStr = 'unknown or unsupplied'
if ledu == 'p_se':
retStr = 'Ph.D. in STEM'
elif ledu == 'p_oth':
retStr = 'Ph.D. in non-STEM field'
elif ledu == 'm':
retStr = 'Masters or... | bigcode/self-oss-instruct-sc2-concepts |
def z_score(data2d, axis=0):
"""Standarize the mean and variance of the data axis Parameters.
:param data2d: DataFrame to normalize.
:param axis: int, Which axis to normalize across. If 0, normalize across rows,
if 1, normalize across columns.
:Returns: Normalized DataFrame. No... | bigcode/self-oss-instruct-sc2-concepts |
def boolean(value):
"""Parse the string "true" or "false" as a boolean (case insensitive).
Also accepts "1" and "0" as True/False (respectively). If
the input is from the request JSON body, the type is already a native
python boolean, and will be passed through without further parsing."""
if type(va... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _linkify_usernames(text):
"""Slack wants @usernames to be surrounded in <> to be highlighted."""
return re.sub(r'(?<!<)(@[\w_]+)', r'<\1>', text) | bigcode/self-oss-instruct-sc2-concepts |
def difference(first, other, epsilon=0.005):
"""
Calculate the difference between two dictionaries. The difference is
defined as all the values for the keys that are in both ``dict`` and
``other`` which differ. For floating point numbers, the value ``epsilon``
is used to define difference, so two fl... | bigcode/self-oss-instruct-sc2-concepts |
def cut_lc(df, min=-30, max=150):
"""Short summary.
Parameters
----------
df : Pandas DataFrame
The dataframe containing the photometry of all events.
min : float
The minimum phase (relative to trigger) at which to truncate photometry.
max : float
The maximum phase (rel... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import List
import ast
def tests_from_file(path: Path, base: str) -> List[str]:
"""
Returns all the tests in the given file, in format
expected as arguments when running the tests.
e.g.
file_stem
file_stem.TestFunctionality
file_stem.TestFun... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_repositories(repos_file):
"""
Load repository yaml
"""
if repos_file:
try:
file_descriptor = open(repos_file, 'r', encoding='utf-8')
except IOError as error:
print("Error: open file {} failed", repos_file, error)
return None
... | bigcode/self-oss-instruct-sc2-concepts |
def observations(ax, data, label='Observations', future=False, **kwargs):
"""
Plot observed values.
:param ax: The plot axes.
:param data: The NumPy array containing the observation data.
:param label: The label for the observation data.
:param future: Whether the observations occur after the f... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_accuracy(predictions, labels):
""" Compute the frequency that the label belongs to the predicted set
Args:
predictions (tensor): a batch of topk predictions with shape [batch_size] or [batch_size, k]
labels (tensor): a batch of labels with shape [batch_size]
... | bigcode/self-oss-instruct-sc2-concepts |
def format_timedelta(time_delta):
"""
Convert a datetime.timedelta to str format
example output: "0h:0m:18s"
Parameters
----------
time_delta: datatime.timedelta
Returns
-------
str: formatted timedelta
"""
d = {}
d["hours"], rem = divmod(time_delta.seconds, 3600)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Any
def snd(tup: Tuple[Any, Any]) -> Any:
""" Return second member of tuple """
return tup[1] | bigcode/self-oss-instruct-sc2-concepts |
def create_grant(grant_create_request): # noqa: E501
"""Create a grant
Create a grant with the specified name # noqa: E501
:param grant_create_request:
:type grant_create_request: dict | bytes
:rtype: GrantCreateResponse
"""
return 'do some magic!' | bigcode/self-oss-instruct-sc2-concepts |
def mark_metadata(metadata, subcollection, selposts):
"""
Mark all posts corresponding to the current subcollection criteria.
This is done in the form of a label in the subcollection column.
"""
for post in selposts:
postindex = metadata[metadata.filename == post].index[0]
metadata.s... | bigcode/self-oss-instruct-sc2-concepts |
def charOffsetToTuples(charOffset):
""" Splits a comma separated list of character offsets into tuples of integers.
Keyword arguments:
charOffset -- a string in the format "0-2,5-20"
Returns:
A list of tuples of two integers each
"""
tuples = []
ranges = charOffset.split(",")
f... | bigcode/self-oss-instruct-sc2-concepts |
def is_empty_line(line):
"""
Returns true if a given line is empty.
str -> bool
"""
return len(line) == 0 | bigcode/self-oss-instruct-sc2-concepts |
def add_slash(url):
"""Add a slash at the end of URL if the slash is not already presented."""
if url and not url.endswith('/'):
url += '/'
return url | bigcode/self-oss-instruct-sc2-concepts |
def getDayOfMonth(date):
"""Extracts the day of the month from a date. The first day of the
month is day 1.
Args:
date (Date): The date to use.
Returns:
int: An integer that is representative of the extracted value.
"""
return date.day | bigcode/self-oss-instruct-sc2-concepts |
import csv
def into_dict(fIn,delimiter=","):
"""
Read data from file into a dictionary. By default
first element of each row is assigned to the key
and the second element is assigned to the value.
Parameters
----------
fIn : str
Path to input file
delimeter : str (optional)
... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_percent(perc):
"""Parse percentile"""
return float(perc[:-1]) / 100 | bigcode/self-oss-instruct-sc2-concepts |
def _escapeArg(arg):
"""Escape the given command line argument for the shell."""
#XXX There is a probably more that we should escape here.
return arg.replace('"', r'\"') | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_name(name):
"""Checks that GitHub user's name is valid"""
return name and len(name) >= 3 and ' ' in name | bigcode/self-oss-instruct-sc2-concepts |
def build_call(*args):
"""
Create a URL for a request to the OEC API.
Args:
*args (str): strings to be appended to the API call.
Returns:
str: url for the API request.
"""
call_url = 'https://legacy.oec.world/'
for val in args:
call_url += str(val) + '/'
return ... | bigcode/self-oss-instruct-sc2-concepts |
def get_json(nifti_path):
"""
Get associated JSON of input file
"""
return nifti_path.replace(".nii.gz", ".json").replace(".nii", ".json") | bigcode/self-oss-instruct-sc2-concepts |
def add_score_line(line: str, value: str) -> str:
"""
String formatting for scoreboard sidebar
:param line: score text
:param value: score
:return: str - formatted score
"""
base_str = f"{line}{value}".center(20)
return_str = '┃' + base_str[1:-1] + '┃'
return return_str | bigcode/self-oss-instruct-sc2-concepts |
def split_data(test_size, df):
"""
Split data into training and testing sets
INPUT:
test_size - size of testing data in ratio (default = 0.2)
df - cleaned and processed dataframe
OUTPUT:
train - training data set
test - testing data set
"""
test_size = test_size
training_si... | bigcode/self-oss-instruct-sc2-concepts |
def augment_segmentation_map(self, segmentation_map, hooks=None):
"""
Augment a single segmentation map.
Parameters
----------
segmentation_map : (H,W,C) ndarray or (H,W) ndarray
The segmentation map to augment.
Expected dtypes are integer-likes, e.g. int32.
hooks : None or ia.... | bigcode/self-oss-instruct-sc2-concepts |
def seabed2aliased(seabed, rlog, tpi, f, c=1500,
rmax={18:7000, 38:2800, 70:1100, 120:850, 200:550}):
"""
Estimate aliased seabed range, given the true seabed range. The answer will
be 'None' if true seabed occurs within the logging range or if it's beyond
the detection limit of the... | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_name(obj):
"""
Creates a unique name (hopefully) of producer and product.
"""
return obj['producer'].lower() + "_" + obj['product'].lower().replace('/', ' ') | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_sha256(b):
"""
Args:
b (:class:`bytes` or :class:`str`): sequence to be hashed
Returns:
:class:`bytes`: sha256 hash
"""
return hashlib.sha256(
b if isinstance(b, bytes) else b.encode('utf-8')
).digest() | bigcode/self-oss-instruct-sc2-concepts |
def extended_euclidean(a, b):
"""Extended Euclidean algorithm. Return s, t and r such that r = gcd(a, b)
and s * a + t * b = r"""
prev_r, r = a, b
prev_s, s = 1, 0
prev_t, t = 0, 1
while r != 0:
q = prev_r // r
prev_r, r = r, prev_r - q * r
prev_s, s = s, prev_s - q * s
... | bigcode/self-oss-instruct-sc2-concepts |
def sendController(msg, q):
"""Communicate with connected controller
Arguments:
msg {str} -- Message to be sent
q {socket.socket} -- Controller's socket
Returns:
int -- Error Code:
0) Error
1) Success
"""
try:
q.send(msg)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import get_origin
def _is_type_alias(obj: object) -> bool:
"""Determines whether the given object is (likely) a type alias."""
return get_origin(obj) is not None | bigcode/self-oss-instruct-sc2-concepts |
def get_source_attributes(source):
"""
Retreives a dictionary of source attributes from the source class
:param source:
Seismic source as instance of :class:
`openquake.hazardlib.source.base.BaseSeismicSource`
:returns:
Dictionary of source attributes
"""
return {"id": s... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_column_defaults(table):
""" Extract column default value for each column.
If column lacks default, set default to NULL.
Returns: a map(column_name, default_value)
"""
defaults = dict()
regex1 = re.compile(r'default\s+(\(|"|\')(.*)(?=(\)|"|\'))')
regex2 = re.compi... | bigcode/self-oss-instruct-sc2-concepts |
def process_one_file(k, a, filename):
"""Return a set of species over thresholds."""
with open(filename) as f:
f.readline()
species = set()
for line in f:
tkns = [tkn.strip() for tkn in line.split('\t')]
abund, _, _, kmers, _, _, _, rank, taxa_name = tkns
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def custom_color(x: int) -> Callable[[], str]:
"""Return an escape string for a color by it's number.
param:
x:
The color code (between 0 and 255).
returns:
Formatted escape sequence for a color
"""
return lambda: "38;5;" + str(x) + "m" | bigcode/self-oss-instruct-sc2-concepts |
def get_connectors(pipe):
"""Get the connector elements of a pipe."""
connector_set = pipe.ConnectorManager.Connectors
connectors = [connector for connector in connector_set.GetEnumerator()]
assert len(connectors) == 2
return connectors | bigcode/self-oss-instruct-sc2-concepts |
def isControlTimestampChanged(prev, latest):
"""\
Checks whether a new (latest) Control Timestamp is different when compared to a old (previous) Control Timestamp.
Note that this does not check equivalency (if two Control Timestamps represent the same mapping between Wall clock time and content time)
... | bigcode/self-oss-instruct-sc2-concepts |
def too_big(dataset, start, end, dim = 300, cutoff = 620000):
"""
Calculates if a batch consisting of dataset[start:end] is too big based on cutoff. This can be used for constructing dynamic batches.
"""
sizes = [len(x) for x in dataset[start:end]['embeddings']]
max_size = max(sizes)
dim = dim
... | bigcode/self-oss-instruct-sc2-concepts |
def separate_file_from_parents(full_filename):
"""Receives a full filename with parents (separated by dots)
Returns a duple, first element is the filename and second element
is the list of parents that might be empty"""
splitted = full_filename.split('.')
file = splitted.pop()
parents = splitted... | bigcode/self-oss-instruct-sc2-concepts |
def v_sub(v, w):
"""Performs componentwise subtraction on two vectors. Returns a list."""
return [vi - wi for vi, wi in zip(v, w)] | bigcode/self-oss-instruct-sc2-concepts |
def generate_filename(blob_name: str, message_index: int) -> str:
"""Strip the file type suffix from the blob name, and append message index."""
fname = blob_name.split("/")[-1]
fname, _ = fname.rsplit(".", 1)
return f"{fname}-{message_index}" | bigcode/self-oss-instruct-sc2-concepts |
def _is_type(t):
"""
Factory for a type checking function of type ``t`` or tuple of types.
"""
return lambda x: isinstance(x.value, t) | bigcode/self-oss-instruct-sc2-concepts |
def calc_diff(prev, curr):
"""Returns percentage difference between two values."""
return ((curr - prev) / prev * 100.0 if prev != 0 else float("inf") *
abs(curr) / curr if curr != 0 else 0.0) | bigcode/self-oss-instruct-sc2-concepts |
def k2e(k, E0):
"""
Convert from k-space to energy in eV
Parameters
----------
k : float
k value
E0 : float
Edge energy in eV
Returns
-------
out : float
Energy value
See Also
--------
:func:`isstools.conversions.xray.e2k`
"""
return ((1... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Any
from typing import List
def unique_list(seq: Iterable[Any]) -> List[Any]:
"""
Returns a list of all the unique elements in the input list.
Args:
seq: input list
Returns:
list of unique elements
As per
http://stackoverflow.co... | bigcode/self-oss-instruct-sc2-concepts |
def resource_from_path(path):
"""Get resource name from path (first value before '.')
:param path: dot-separated path
:return: resource name
"""
index = path.find('.')
if index == -1:
return path
return path[:index] | bigcode/self-oss-instruct-sc2-concepts |
def make_numeric_labels(class_set):
"""Generates numeric labels (to feed external tools) for a given set of strings"""
return { cls : idx for idx, cls in enumerate(class_set) } | bigcode/self-oss-instruct-sc2-concepts |
def proj(A,B):
"""Returns the projection of A onto the hyper-plane defined by B"""
return A - (A*B).sum()*B/(B**2).sum() | bigcode/self-oss-instruct-sc2-concepts |
import csv
def writeCSV(file,data,cols = None):
"""
Write CSV file with data typically supplied as a list or np.arrays.
:param file: file or name of file,
:type file: file or str
:param data: list of numpy.array or two dimensional numpy.array
:type data: list of numpy.array or two dimensiona... | bigcode/self-oss-instruct-sc2-concepts |
def parametrized(decorator):
"""
Decorator for easily defining parametrized decorators. Should be used like this:
@parametrized
def my_decorator(func, *args, **kwargs):
@wraps
def _my_decorator(*args_, **kwargs_):
# At this point args and kwargs are decorator parameters whil... | bigcode/self-oss-instruct-sc2-concepts |
def make_scenario_name_nice(name):
"""Make a scenario name nice.
Args:
name (str): name of the scenario
Returns:
nice_name (str): nice name of the scenario
"""
replacements = [
("_", " "),
(" with", "\n with"),
("fall", ""),
("spring", ""),
... | bigcode/self-oss-instruct-sc2-concepts |
def lookup_by_href_or_nickname(href, nickname, find_function):
"""
Helper to retrieve items by href or nickname
:param href (optional): String of the item href
:param nickname (optional): String of the item nickname
:param find_function: The function to use to find by nickname
:return: String o... | bigcode/self-oss-instruct-sc2-concepts |
def dictify(some_named_tuple):
"""
Convert Named Tuple to dictionary
:param some_named_tuple: collections.namedtuple()
:return:dict,
"""
return dict((s, getattr(some_named_tuple, s)) for s in some_named_tuple._fields) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _IsTaskKillError(stderr):
"""Returns whether the stderr output of taskkill indicates it failed.
Args:
stderr: the string error output of the taskkill command
Returns:
True iff the stderr is considered to represent an actual error.
"""
# The taskkill "reason" string indicates why it f... | bigcode/self-oss-instruct-sc2-concepts |
def binary_search(numbers, number):
"""Binary search
Locates the number in the list of sorted numbers. Looks at the middle element, and proceeds recursively to the left
or to the right, depending on whether the number was smaller or bigger, respectively
Returns the position of the found number, or the... | bigcode/self-oss-instruct-sc2-concepts |
def minmax_element(iterable, first=0, last=None, key=None):
"""
Find and return the minimum and maximum element in an iterable range.
Parameters
----------
iterable: an iterable object with __get_item__
first: first element to check
last: one past last element to check. None will check unti... | 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.