seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import mpmath
def mode(p, b, loc=0, scale=1):
"""
Mode of the generalized inverse Gaussian distribution.
The mode is:
p - 1 + sqrt((p - 1)**2 + b**2)
loc + scale -------------------------------
b
"""
p = mpmath.mpf(p)
b = mpmath.m... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def kl_divergence_mc(
q_distrib: torch.distributions.Distribution, p_distrib: torch.distributions.Distribution, z: torch.Tensor
):
"""Elementwise Monte-Carlo estimation of KL between two distributions KL(q||p) (no reduction applied).
Any number of dimensions works via broadcasting and correc... | bigcode/self-oss-instruct-sc2-concepts |
def _get_test_type(item):
"""
Gets the test type - unit, functional, integration, based on the directory that the test is in.
"""
return item.nodeid.split('/')[1] | bigcode/self-oss-instruct-sc2-concepts |
def _dummy_get_parameter(tree_info, extra_config):
"""
Dummy function used to return parameters (TreeEnsemble converters already have parameters in the right format)
"""
return tree_info | bigcode/self-oss-instruct-sc2-concepts |
def bubble_sort(a: list):
"""Optimized Bubble sort that return sorted list with O(n^2) complexity"""
a, n = a.copy(), len(a)
for _ in range(n):
is_swap = False
for i in range(1, n):
if a[i-1] > a[i]:
is_swap = True
a[i-1], a[i] = a[i], a[i-1]
... | bigcode/self-oss-instruct-sc2-concepts |
def calc_bfdp(bf, prior):
"""
Calculate BFDP for a single gene per Wakefield, AJHG, 2007
"""
# Wakefield phrases prior as probability of no effect, so we need to invert
prior = 1 - prior
po = prior / (1 - prior)
bftpo = bf * po
bfdp = bftpo / (1 + bftpo)
return bfdp | bigcode/self-oss-instruct-sc2-concepts |
def fnsplit(fn):
"""/path/fnr.x -> (/path/fnr, x) when possible. Non-str treated as None."""
if not (isinstance(fn, str) and fn):
return (None, None)
fn = fn.strip()
if not fn:
return (None, None)
x = fn.rfind('.')
if x == -1:
return fn, None
return (fn[:x], fn[x:]) | bigcode/self-oss-instruct-sc2-concepts |
def pluralize(s, count):
#===============================================================================
"""
Return word with 's' appended if the count > 1.
"""
if count > 1:
return '%ss' % s
return s | bigcode/self-oss-instruct-sc2-concepts |
def isfile_s3(bucket, key: str) -> bool:
"""Returns T/F whether the file exists."""
objs = list(bucket.objects.filter(Prefix=key))
return len(objs) == 1 and objs[0].key == key | bigcode/self-oss-instruct-sc2-concepts |
def filepaths(filesets):
""" Return a list of filepaths from list of FileSets """
filepaths = []
for fs in filesets:
filepaths += fs.files
return filepaths | bigcode/self-oss-instruct-sc2-concepts |
def agent_slot(occupants, a_id, t):
"""Return the slot agent with id a_id occupied in round t,
or -1 if a_id wasn't present in round t"""
agents = occupants[t]
if a_id in agents:
return agents.index(a_id)
else:
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def __ensure_suffix(t, suffix):
""" Ensure that the target t has the given suffix. """
tpath = str(t)
if not tpath.endswith(suffix):
return tpath+suffix
return t | bigcode/self-oss-instruct-sc2-concepts |
def _numlines(s):
"""Returns the number of lines in s, including ending empty lines."""
# We use splitlines because it is Unicode-friendly and thus Python 3
# compatible. However, it does not count empty lines at the end, so trick
# it by adding a character at the end.
return len((s + 'x').splitline... | bigcode/self-oss-instruct-sc2-concepts |
def get_second_offset(time):
"""
Get second offset from time.
@time: Python time object in 24 hour format.
"""
return time.hour * 3600 + time.minute * 60 + time.second | bigcode/self-oss-instruct-sc2-concepts |
def num(s):
"""
convert a string to integer or float
:param s: a string of number
:return: an int or float type number
"""
try:
return int(s)
except ValueError:
return float(s)
else:
raise ValueError('Expected integer or floating point number.') | bigcode/self-oss-instruct-sc2-concepts |
def normalize_typename(typename: str) -> str:
"""
Drop the namespace from a type name and converts to lower case.
e.g. 'tows:parks' -> 'parks'
"""
normalized = typename
if ":" in typename:
normalized = typename.split(":")[1]
return normalized.lower() | bigcode/self-oss-instruct-sc2-concepts |
def xyzw2wxyz(xyzw):
"""Convert quaternions from XYZW format to WXYZ."""
x, y, z, w = xyzw
return w, x, y, z | bigcode/self-oss-instruct-sc2-concepts |
def check_related_lot_status(tender, award):
"""Check if related lot not in status cancelled"""
lot_id = award.get('lotID')
if lot_id:
if [l['status'] for l in tender.get('lots', []) if l['id'] == lot_id][0] != 'active':
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def decode_rle(input):
"""
Gets a stream of data and decompresses it
under a Run-Length Decoding.
:param input: The data to be decoded.
:return: The decoded string.
"""
decode_str = ""
count = ""
for ch in input:
# If not numerical
if not ch.isdigit():
# ... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def flatten(list_of_lists):
"""Flatten one level of nesting."""
return itertools.chain.from_iterable(list_of_lists) | bigcode/self-oss-instruct-sc2-concepts |
import six
def get_model_label(model):
"""
Take a model class or model label and return its model label.
>>> get_model_label(MyModel)
"myapp.MyModel"
>>> get_model_label("myapp.MyModel")
"myapp.MyModel"
"""
if isinstance(model, six.string_types):
return model
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def fst(ls):
"""returns the 0th element of a list"""
return ls[0] | bigcode/self-oss-instruct-sc2-concepts |
def get_camera_from_topic(topic):
"""
Returns the camera name given the image topic.
"""
topic_split = topic.split('/')
return topic_split[2] | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import json
def read_parameters(parameters_file: Path):
"""This function reads the config file containing the parameters needed for filtering datasets."""
if parameters_file.exists():
with open(parameters_file) as fout:
parameters = json.load(fout)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_parts(usage):
"""Extract individual components from a usage string"""
opp = {'{': '}', '[': ']', '(': ')'}
cur_word = []
tokens = []
stack = []
for c in usage:
if c.isspace() and not stack:
if cur_word:
tokens.append(''.join(cur_word))
... | bigcode/self-oss-instruct-sc2-concepts |
def array_chunk(array, size):
"""
Given an array and chunk size, divide the array
into many subarrays, where each subarray is of
length size.
array_chunk([1,2,3,4], 2) --> [[1,2], [3,4]]
array_chunk([1,2,3,4,5], 2) --> [[1,2], [3,4], [5]]
"""
counter = 0
outer_list = []
inner_lis... | bigcode/self-oss-instruct-sc2-concepts |
def time_minutes(dt):
"""Format a datetime as time only with precision to minutes."""
return dt.strftime('%H:%M') | bigcode/self-oss-instruct-sc2-concepts |
import re
def offset(text):
"""Returns index of first non-whitespace character.
Args:
text (str): string to be analyzed for whitespaces.
Returns:
index (int): index of first non-whitespace character; -1 if none found.
"""
index = 0 # Assume first character is not a whitespace
... | bigcode/self-oss-instruct-sc2-concepts |
def WithChanges(resource, changes):
"""Apply ConfigChangers to resource.
It's undefined whether the input resource is modified.
Args:
resource: KubernetesObject, probably a Service.
changes: List of ConfigChangers.
Returns:
Changed resource.
"""
for config_change in changes:
resource = co... | bigcode/self-oss-instruct-sc2-concepts |
import binascii
def encode(bs):
"""Given a bytes object, return a Base64-encoded version of that object, without
newlines."""
return binascii.b2a_base64(bs, newline=False).decode("utf-8").rstrip() | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_tns_name(name: str):
"""
Checks if a string adheres to the TNS naming scheme
"""
return re.match("^AT|SN(19|20)\d\d[a-z]{3,4}$", name) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_wiki_text(text):
"""
Normalizes a text such as a wikipedia title.
@param text text to normalize
@return normalized text
"""
return text.replace("_", " ").replace("''", '"') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Union
def try_parse_int_float_str(candidate: Any) -> Union[float, int, str]:
"""
Tries to parse the given value as an int or float. If this does not work simply the
string-representation of the candidate will be returned.
Examples:
>>> res = try_parse... | bigcode/self-oss-instruct-sc2-concepts |
def find_edf_events(raw):
"""Get original EDF events as read from the header.
For GDF, the values are returned in form
[n_events, pos, typ, chn, dur]
where:
======== =================================== =======
name description type
======== ================... | bigcode/self-oss-instruct-sc2-concepts |
def buildup_function(p, E_max, p_half):
"""Calculate asymptotic buildup curve
Args:
p (array): power series
E_max (float): maximum enhancement
p_half (float): power at half saturation
Returns:
ndarray: buildup curve
.. math::
f(p) = 1 + E_{max} * p / (p_{1/2} +... | bigcode/self-oss-instruct-sc2-concepts |
def plot_hsu(hst, models, max_speed, pressure_charge, max_pressure):
"""
For the given HST computes the sizes, efficiencies and plots the efficiency map.
Returns:
---
fig: plotly figure object
"""
hst.compute_sizes()
hst.compute_speed_limit(models['pump_speed'])
hst.add_no_load((180... | bigcode/self-oss-instruct-sc2-concepts |
def format(dt, fmt = "dt", simplified = True):
"""Format a datetime object.
Use a python :py:class:`datetime.datetime` object and convert it to a string,
wrapping the :py:meth:`datetime.datetime.strftime` method.
For convenience, enable the interpretation of a simpler syntax for common and
default ... | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def _fmod(x, y):
"""
returns x - n * y, where n is the quotient of x / y, rounded
towards zero to an integer.
"""
fquot = mpmath.mpf(x) / y
if fquot < 0:
n = -mpmath.floor(-fquot)
else:
n = mpmath.floor(fquot)
return x - n * y | bigcode/self-oss-instruct-sc2-concepts |
def count_in_list(my_list, count_for=1):
""" Gets the count of a certain value in a list.
Args:
my_list (list of obj): The list to search through.
count_for (obj): The object to count.
Returns:
int: The number of that object
"""
count = 0
for item in my_list... | bigcode/self-oss-instruct-sc2-concepts |
def pool_sku(config, lower=False):
# type: (dict, bool) -> str
"""Get Pool sku
:param dict config: configuration object
:param bool lower: lowercase return
:rtype: str
:return: pool sku
"""
sku = config['pool_specification']['sku']
return sku.lower() if lower else sku | bigcode/self-oss-instruct-sc2-concepts |
def filter_latest_builds(builds):
"""Filters Build objects to include only the latest for each builder.
Args:
builds: A collection of Build objects.
Returns:
A list of Build objects; only one Build object per builder name. If
there are only Builds with no build number, then one is ... | bigcode/self-oss-instruct-sc2-concepts |
def checksum(number, alphabet='0123456789'):
"""Calculate the Luhn checksum over the provided number. The checksum
is returned as an int. Valid numbers should have a checksum of 0."""
n = len(alphabet)
number = tuple(alphabet.index(i)
for i in reversed(str(number)))
return (sum(nu... | bigcode/self-oss-instruct-sc2-concepts |
def racks_for_replica_list(replicas, pos=None):
"""
Returns a set of racks for each of the given replicas in the list
Skip the replica at position pos, if specified
:params replicas: a list of Broker objects
:params pos: a replica position to skip, or None to not skip a replica
:returns: a list... | bigcode/self-oss-instruct-sc2-concepts |
def tbody(
trContent=""):
"""
*Generate a table body - TBS style*
**Key Arguments:**
- ``trContent`` -- the table row content
**Return:**
- ``tbody`` -- the table body
"""
tbody = """<tbody class="">%(trContent)s</tbody>""" % locals()
return tbody | bigcode/self-oss-instruct-sc2-concepts |
def sample_width_to_string(sample_width):
"""Convert sample width (bytes) to ALSA format string."""
return {1: 's8', 2: 's16', 4: 's32'}[sample_width] | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def sha256(payload):
"""This function returns the sha256 of the provided payload"""
return hashlib.sha256(payload).digest() | bigcode/self-oss-instruct-sc2-concepts |
def _generate_snitch_text(cluster):
"""Generate the text for the PropertyFileSnitch file"""
i=1
contents = [
"# Auto-generated topology snitch during cluster turn-up", "#",
"# Cassandra node private IP=Datacenter:Rack", "#", ""
]
for z in cluster.keys():
contents.append("# Zo... | bigcode/self-oss-instruct-sc2-concepts |
from collections import OrderedDict
def readResult(fname):
"""
Open results file, extract and return minimum point as OrderedDict
and return raw list of all other lines for further processing.
"""
RES=[]
OTH=[]
with open(fname) as f:
for line in f:
l=line.strip()
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _identifier_for_name(name, *reserveds):
"""Makes an identifier from a given name and disambiguates if it is reserved.
1. replace invalid identifier characters with '_'
2. prepend with '_' if first character is a digit
3. append a disambiguating positive integer if it is reserved
:p... | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def var(lam):
"""
Variance of the Poisson distribution.
"""
return mpmath.mpf(lam) | bigcode/self-oss-instruct-sc2-concepts |
def scale_to_range(min_max_old, element, min_max_new=[0, 10]):
"""Scale element from min_max_new to the new range, min_max_old.
Args:
min_max_old: Original range of the data, [min, max].
element: Integer that will be scaled to the new range, must be
within the old_range.
min... | bigcode/self-oss-instruct-sc2-concepts |
def output_file_version() -> str:
"""A suffix that is added to output files, denoting a version of the data format"""
return 'v5' | bigcode/self-oss-instruct-sc2-concepts |
def _GetBrowserPID(track):
"""Get the browser PID from a trace.
Args:
track: The tracing_track.TracingTrack.
Returns:
The browser's PID as an integer.
"""
for event in track.GetEvents():
if event.category != '__metadata' or event.name != 'process_name':
continue
if event.args['name'] =... | bigcode/self-oss-instruct-sc2-concepts |
def mean(x1, x2):
"""Integer average."""
return (x1 + x2)/2 | bigcode/self-oss-instruct-sc2-concepts |
def get_time(seconds):
"""Returns human readable time format for stats."""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
return "%dd:%dh:%02dm:%02ds" % (d, h, m, s) | bigcode/self-oss-instruct-sc2-concepts |
def manage_time(timestamp):
"""
Given the string representation of a the time using the
"minutes:seconds[:miliseconds]" representation, returns the number
of seconds using double precision
"""
time_strip = timestamp.split(":")
seconds = int(time_strip[0]) * 60 + int(time_strip[1])
# Ad... | bigcode/self-oss-instruct-sc2-concepts |
import json
def parse_genres(movie):
"""
Convert genres to a dictionnary for dataframe.
:param movie: movie dictionnary
:return: well-formated dictionnary with genres
"""
parse_genres = {}
g = movie['genres']
with open('genre.json', 'r') as f:
genres = json.load(f)
for k... | bigcode/self-oss-instruct-sc2-concepts |
def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Celsius and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
>>> rankine_to_celsius(2... | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(point_a, point_b):
"""
Returns the distance between two points given as tuples
"""
x0, y0 = point_a
x1, y1 = point_b
return math.hypot(x0 - x1, y0 - y1) | bigcode/self-oss-instruct-sc2-concepts |
def estimate_clipping_rect(projector, size):
"""
Return:
rect -- NSRect style 2d-tuple.
flipped (bool) -- Whether y-axis is flipped.
"""
# lt -> rt -> lb -> rb
image_corners = [(0, 0), (size[0], 0), (0, size[1]), size]
x_points = []
y_points = []
for corner in image_corners:
... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(nested):
"""
flattens a nested list
>>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]])
['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'fhg', 4]
"""
result = []
try:
# dont iterate over string-like objects:
try:
nested + ''
except(TypeError):
pass
else:... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Callable
import hashlib
from typing import Union
def _hash(
tpl: Tuple, hash_function: Callable = hashlib.sha1, as_int: bool = True
) -> Union[str, int]:
"""Deterministic hash function. The main use here is
providing a `commit_hash` for a Dataset to compare acro... | bigcode/self-oss-instruct-sc2-concepts |
def generate_sequence(lst: list[int]) -> list[int]:
"""Return a new list that contains the sequence of integers between the minimum and maximum of
lst, inclusive.
When the minimum and maximum of lst are the same, the list should only contain one element.
Assume that len(lst) >= 1.
>>> generate_se... | bigcode/self-oss-instruct-sc2-concepts |
import math
def euclidean_distance(p, q):
""" Computes the distance between two points p and q.
"""
return math.sqrt((p[0] - q[0])**2 + (p[1] - q[1])**2) | bigcode/self-oss-instruct-sc2-concepts |
def _normalize_image_id(image_id):
"""
The image IDs we get back from parsing "docker build" output are abbreviated to 12 hex digits.
In order to compare them to the ids we get from "docker.Client.images()" calls, we need to
normalize them
"""
if image_id is None:
return None
if ima... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def mask_fill(
fill_value: float,
tokens: torch.Tensor,
embeddings: torch.Tensor,
padding_index: int,
) -> torch.Tensor:
"""
Function that masks embeddings representing padded elements.
:param fill_value: the value to fill the embeddings belonging to padded tokens.
:param... | bigcode/self-oss-instruct-sc2-concepts |
def _average(value_a: float, num_a: int, value_b: float, num_b: int) -> float:
"""Compute a weighted average of 2 values with associated numbers."""
divisor = num_a + num_b
if divisor == 0:
return 0
else:
return float(value_a * num_a + value_b * num_b) / divisor | bigcode/self-oss-instruct-sc2-concepts |
def average(lst):
"""
Calculates the average of a given list
:param lst: list of numbers
:return: average value
"""
return sum(lst) / len(lst) | bigcode/self-oss-instruct-sc2-concepts |
def getChunks(dsets,nbchunks):
""" Splits dataset object into smaller chunks
Parameters:
* dsets (dict): dataset
* nbchunks (int): number of data chunks to be created
Returns:
* dict: chunks from dataset stored as dictionaries
"""
ret = []
for ichunk in range(nbchunks):
datagrp = {}
f... | bigcode/self-oss-instruct-sc2-concepts |
def from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
r, g, b = rgb
return f'#{r:02x}{g:02x}{b:02x}' | bigcode/self-oss-instruct-sc2-concepts |
import math
def printAngle(angle):
"""Generate angle line
Parameters
----------
angle : Angle Object
Angle Object
Returns
-------
angleLine : str
Angle line data
"""
k0 = angle.K0*8.3680
angle0 = math.radians(angle.angle0)
return '<Angle class1=\"%s\... | bigcode/self-oss-instruct-sc2-concepts |
def get_batchid_from_job(job_ads_dict):
"""
Get batchID string from condor job dict
"""
batchid = '{0}.{1}'.format(job_ads_dict['ClusterId'], job_ads_dict['ProcId'])
return batchid | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_name() -> str:
"""Generate a random account name."""
return "temp" + str(random.randint(100000, 999999)) | bigcode/self-oss-instruct-sc2-concepts |
def sort_by_tc(events):
"""Sorts events by their rec_start_tc."""
events.sort(key=lambda e: (e.rec_start_tc.frames, e.track))
return events | bigcode/self-oss-instruct-sc2-concepts |
def all_equal(s):
"""Return whether all elements in a list are equal."""
return len(set(s)) <= 1 | bigcode/self-oss-instruct-sc2-concepts |
def get_node_ids(apic, args):
"""
Get the list of node ids from the command line arguments.
If none, get all of the node ids
:param apic: Session instance logged in to the APIC
:param args: Command line arguments
:return: List of strings containing node ids
"""
if args.switch is not None... | bigcode/self-oss-instruct-sc2-concepts |
def _html_tag(tag, contents, attr_string=''):
"""Wraps 'contents' in an HTML element with an open and closed 'tag', applying the 'attr_string' attributes. """
return '<' + tag + attr_string + '>' + contents + '</' + tag + '>' | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def tmp_cache(config, tmpdir):
"""Move the cache to a temporary dir that is empty at the start of the test and
deleted after the test."""
config['CACHE_ROOT_DIR'] = pathlib.Path(tmpdir)
return config['CACHE_ROOT_DIR'] | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def read_metafile(path):
"""
Read contents from given metafile
"""
with codecs.open(path, 'rb', 'utf-8') as f:
return f.read() | bigcode/self-oss-instruct-sc2-concepts |
def read_content_from_file(filename):
"""Simply reads content from a file.
Used so we don't have to mock __builtin__.open()
Args:
filename (string): name of the file
"""
with open(filename, 'r') as fh:
content = fh.read()
return content | bigcode/self-oss-instruct-sc2-concepts |
import torch
def collate_fn(data):
""" Creates mini-batch from x, ivec, jvec tensors
We should build custom collate_fn, as the ivec, and jvec have varying lengths. These should be appended
in row form
Args:
data: list of tuples contianing (x, ivec, jvec)
Returns:
x: one hot enco... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def extract_body_from_html(html_soup):
"""Return an XML beautiful soup object with the <body> of the input HTML file"""
body = html_soup.body.extract()
xml_soup = BeautifulSoup('', 'xml')
xml_soup.append(body)
return xml_soup | bigcode/self-oss-instruct-sc2-concepts |
import yaml
import json
def load_config_file(config_file: str, child_name="dockerConfiguration") -> dict:
"""
Load OSDF configuration from a file -- currently only yaml/json are supported
:param config_file: path to config file (.yaml or .json).
:param child_name: if present, return only that child n... | bigcode/self-oss-instruct-sc2-concepts |
def make_frame(contents, title=''):
"""
Wrap `contents` in \begin{frame} ... \end{frame},
optionally setting `title`
"""
lines = [r'\begin{frame}']
if title != '':
lines.append(f'\\frametitle{{{title}}}')
lines += [
f'{contents}',
r'\end{frame}'
]
return '\n'.... | bigcode/self-oss-instruct-sc2-concepts |
def separate_words_and_numbers(strings):
"""
Separates words and numbers into two lists.
:param strings: List of strings.
:return: One list of words and one list of numbers
"""
filtered_words = []
filtered_numbers = []
for string in strings:
if string.isdigit():
... | bigcode/self-oss-instruct-sc2-concepts |
def intersection(lst1, lst2):
"""returns the intersection between two lists"""
if (lst1 == None or lst2 == None):
return []
lst3 = [value for value in lst1 if value in lst2]
return lst3 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _format_faces_indices(faces_indices, max_index):
"""
Format indices and check for invalid values. Indices can refer to
values in one of the face properties: vertices, textures or normals.
See comments of the load_obj function for more details.
Args:
faces_indices: List of... | bigcode/self-oss-instruct-sc2-concepts |
def _pairs(exercises):
""" Returns a list of pairs of exercises in `excercises` """
pair_list = []
for i in range(len(exercises)//2):
pair_list.append((exercises[2 * i], exercises[2 * i + 1]))
return pair_list | bigcode/self-oss-instruct-sc2-concepts |
def _unique_metric_name(name, existing_metrics):
"""Returns a unique name given the existing metric names."""
existing_names = set([metric.name for metric in existing_metrics])
proposed_name = name
cnt = 1 # Start incrementing with 1.
# Increment name suffix until the name is unique.
while proposed_name i... | bigcode/self-oss-instruct-sc2-concepts |
def V(x):
"""
potential energy function
use units such that m = 1 and omega_0 = 1
"""
return 0.5 * pow(x, 2.0) | bigcode/self-oss-instruct-sc2-concepts |
def dms_to_deg(deg,min,sec):
"""Convert a (deg,arcmin,arcsec) to decimal degrees"""
return deg+min/60.+sec/3600. | bigcode/self-oss-instruct-sc2-concepts |
def construct_network_config_string(cfg_list):
"""
Creates the network configuration string from a list of addresses created via convert_network_address_to_list
Args:
cfg_list (List): List of lists containing all the addresses
Returns:
cfg_string (str): String containing the numbers of... | bigcode/self-oss-instruct-sc2-concepts |
def from_pandas_contextual(df):
""" Convert contextual ``pandas.DataFrame`` to list of tuples.
Args:
df (DataFrame):
anomalies, passed as ``pandas.DataFrame``
containing two columns: start and stop.
Returns:
list:
tuple (start, end) timestamp.
Raise... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_dist(x1,x2,y1,y2):
"""Find distance between two points"""
return abs(math.sqrt(pow(x1-x2,2) + pow(y1-y2,2))) | bigcode/self-oss-instruct-sc2-concepts |
def get_X_Y(**cosmo):
"""The fraction of baryonic mass in hydrogen and helium.
Assumes X_H + Y_He = 1.
You must specify either 'X_H', or 'Y_He', or both.
"""
if 'X_H' in cosmo and 'Y_He' not in cosmo:
X_H = cosmo['X_H']
Y_He = 1. - X_H
elif 'Y_He' in cosmo and 'X_H' not in cosm... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def do_materials_match(
materials_1: List[str],
materials_2: List[str],
colors_1: List[str],
colors_2: List[str]
) -> bool:
"""Returns whether the two given material lists match, or, if either of the
given material lists are empty, returns whether the two given color li... | bigcode/self-oss-instruct-sc2-concepts |
def separate_appetizers(dishes, appetizers):
"""
:param dishes: list of dish names
:param appetizers: list of appetizer names
:return: list of dish names
The function should return the list of dish names with appetizer names removed.
Either list could contain duplicates and may require de-dupin... | bigcode/self-oss-instruct-sc2-concepts |
def compute_loss(batch, output, loss_func):
"""Computes the loss of a given batch
Args:
batch (dict): The current batch
output (tuple): Tuple of tensors (output of `TransformerModel`)
loss_func (:obj:`nn.modules._Loss`): The loss function
Returns:
(:obj:`torch.Tensor`, int)... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import itertools
def flatten_(list_of_lists: List[List]) -> List:
"""Reduce a lists of lists to a list, functionally
>>> assert flatten_([[1, 2], [3, 4]]) == [1, 2, 3, 4]
Thanks to CTT at
https://stackoverflow.com/a/716482/500942
"""
return list(itertools.chain.fr... | bigcode/self-oss-instruct-sc2-concepts |
def clean_data(df):
"""
Clean the dataset
Args:
df: (pandas.DatFrame) containing data to be cleaned
Returns:
df: (pandas.DataFrame) containing the cleaned dataset
"""
try:
# clean target labels
categories = df.categories.str.split(";", expand=True)
cat_n... | 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.