seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
from typing import Sequence
from functools import reduce
from operator import mul
def prod(digits: Sequence[str]) -> int:
"""
Returns the product of a string of digits.
"""
return reduce(mul, map(int, digits)) | bigcode/self-oss-instruct-sc2-concepts |
def truncate_term_rankings( orig_rankings, top ):
"""
Truncate a list of multiple term rankings to the specified length.
"""
if top < 1:
return orig_rankings
trunc_rankings = []
for ranking in orig_rankings:
trunc_rankings.append( ranking[0:min(len(ranking),top)] )
return trunc_rankings | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_sin(x):
"""
Return the sine of x (measured in radians).
"""
return math.sin(x) | bigcode/self-oss-instruct-sc2-concepts |
import struct
import socket
def inet_ntoa(i):
"""Like `socket.inet_nota()` but accepts an int."""
packed = struct.pack('!I', i)
return socket.inet_ntoa(packed) | bigcode/self-oss-instruct-sc2-concepts |
def format_sec_to_dhm(sec):
"""Format seconds to days, hours, minutes.
Args:
sec: float or int
Number of seconds in a period of time.
Returns: str
Period of time represented as a string on the form ``0d\:00h\:00m``.
"""
rem_int, s_int = divmod(int(sec), 60)
rem_int, m_int,... | bigcode/self-oss-instruct-sc2-concepts |
import ast
from typing import List
from typing import Tuple
def get_scr119(node: ast.ClassDef) -> List[Tuple[int, int, str]]:
"""
Get a list of all classes that should be dataclasses"
ClassDef(
name='Person',
bases=[],
keywords=[],
body=[
... | bigcode/self-oss-instruct-sc2-concepts |
import click
def style_prompt(message):
"""Returns a unified style for click prompts."""
return click.style(message, fg="cyan") | bigcode/self-oss-instruct-sc2-concepts |
def is_prime(n):
"""Return True if n is a prime."""
if (n % 2 == 0 and n > 2) or n == 1:
return False
return all(n % i for i in range(3, int(n**0.5) + 1, 2)) | bigcode/self-oss-instruct-sc2-concepts |
def _cache_name(request):
"""
Name for a preset cache.
"""
return "cache_%s" % request.user.username | bigcode/self-oss-instruct-sc2-concepts |
def book_value_per_share(book_value, total_shares):
"""Computes book value per share.
Parameters
----------
book_value : int or float
Book value (equity) of an enterprice
total_shares : int or float
Total number of shares
Returns
-------
out : int or float
Book ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import json
def str_to_list_of_ints(val) -> List[int]:
"""Accepts a str or list, returns list of ints. Specifically useful when
num_hidden_units of a set of layers is specified as a list of ints"""
if type(val) == list:
return val
else:
return [int(v) for v in... | bigcode/self-oss-instruct-sc2-concepts |
def center_crop(image, crop_size=None):
"""Center crop image.
Args:
image: PIL image
crop_size: if specified, size of square to center crop
otherwise, fit largest square to center of image
Returns:
cropped PIL image
"""
width, height = image.size
#... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def get_syntax_coloring_dicts(self) -> List[List[Dict]]:
"""
Converts the text in the editor based on the line_string_list into a list of lists of dicts.
Every line is one sublist which contains different dicts based on it's contents.
We create a dict f... | bigcode/self-oss-instruct-sc2-concepts |
def name_version_release(spec_fh):
"""
Take the name, version and release number from the given filehandle pointing at a sepc file.
"""
content = {}
for line in spec_fh:
if line.startswith('Name:') and 'name' not in content:
content['name'] = line[5:].strip()
elif line.st... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
import collections
import logging
def get_text(directory):
"""
Return a concatenated string of section texts from the specified directory.
Text files should be UTF-8 encoded.
"""
section_dir = pathlib.Path(directory)
paths = sorted(section_dir.glob('[0-9]*.md'))
name_to_text... | bigcode/self-oss-instruct-sc2-concepts |
def import_class(class_path):
"""
Imports a class having dynamic name/path.
Args:
class_path: str
Path to class (exp: "model.MmdetDetectionModel")
Returns:
mod: class with given path
"""
components = class_path.split(".")
mod = __import__(components[0])
for c... | bigcode/self-oss-instruct-sc2-concepts |
import re
def rmPunct(string) :
"""Remove punctuation"""
return re.sub(r'[^\w\s]','',string) | bigcode/self-oss-instruct-sc2-concepts |
def remove_min_count(df, min_count):
"""
Function remove_min_count: This function removes data that is all zeros in a column
best used once merging has taken place to get rid of all features that are zero in both conditions
:param df: @type pandas dataframe: The data to remove counts below min_count... | bigcode/self-oss-instruct-sc2-concepts |
def sort_by_score(iterable):
"""Sorts a collection of objects by their score attribute, descending.
Args:
iterable: iterable collection of objects with a score attribute.
Returns:
The collection sorted by score descending.
"""
return sorted(iterable, key=lambda x: x.score, reverse=True) | bigcode/self-oss-instruct-sc2-concepts |
import math
def next_power_of_two(x: int) -> int:
"""Return next highest power of 2, or self if a power of two or zero."""
if x == 0:
return 0
assert x >= 1, f"x must be 1 or greater; was: {x}"
result = int(2 ** math.ceil(math.log2(x)))
assert result >= x
return result | bigcode/self-oss-instruct-sc2-concepts |
def escape_filter_chars(assertion_value,escape_mode=0):
"""
Replace all special characters found in assertion_value
by quoted notation.
escape_mode
If 0 only special chars mentioned in RFC 4515 are escaped.
If 1 all NON-ASCII chars are escaped.
If 2 all chars are escaped.
"""
if escape_mo... | bigcode/self-oss-instruct-sc2-concepts |
def _index_to_sequence(i, dim_list):
"""
For a matrix entry with index i it returns state it corresponds to.
In particular, for dim_list=[2]*n it returns i written as a binary number.
Parameters
----------
i : int
Index in a matrix.
dim_list : list of int
List of dimensions... | bigcode/self-oss-instruct-sc2-concepts |
import math
def y_ticks(max_y):
"""
Computes aesthetically pleasing y-axis tick marks for specified max value
Note:: will always include y=0 as the minimum value
returns list of y values and scaling factor
"""
log_max = math.log10(max_y)
m_log_y = math.floor(log_max) # log of ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def to_bitmask(M):
"""
Returns the bitmask sparse format of matrix 'M'
:param M: original weight matrix M
"""
wmb = (M != 0).float()
data = M[torch.nonzero(M, as_tuple=True)]
return wmb, data | bigcode/self-oss-instruct-sc2-concepts |
def vec_sum(a):
"""
Computes the inner sum of a vector
Parameters
----------
a: list[]
A vector of scalar values
Returns
-------
scalar
The sum of the elements in the vector
"""
return sum(a) | bigcode/self-oss-instruct-sc2-concepts |
import types
import functools
import inspect
def _is_unbound_self_method(core_callable):
"""Inspects a given callable to determine if it's both unbound, and the first argument in it's signature is `self`"""
if isinstance(core_callable, types.MethodType):
return False
if isinstance(core_callable, ... | bigcode/self-oss-instruct-sc2-concepts |
def extract_epoch(filename):
"""
Get the epoch from a model save string formatted as name_Epoch:{seed}.pt
:param str: Model save name
:return: epoch (int)
"""
if "epoch" not in filename.lower():
return 0
epoch = int(filename.lower().split("epoch_")[-1].replace(".pt", ""))
retur... | bigcode/self-oss-instruct-sc2-concepts |
def align_bitext_to_ds(bitext, ds):
"""
Return a subset of bitext that's aligned to ds.
"""
bitext_dict = dict([(src, (ind, tgt)) for ind, (src, tgt) in enumerate(bitext)])
new_bitext = []
for entry in ds:
en_sent = entry[2]
ind, tgt_sent = bitext_dict[en_sent]
new_bitext... | bigcode/self-oss-instruct-sc2-concepts |
import calendar
def get_month_name(month):
"""gets the month full name from the calendar."""
# print(calendar.month_abbr[month]) # to print the month appreviated name
return calendar.month_name[month] | bigcode/self-oss-instruct-sc2-concepts |
def filter_sequences(df, lower_bound, upper_bound, grouping_col='hadm_id'):
"""
Filters sequences so that only those that are between lower_bound and upper_bound remain
Parameters
----------
df: object
data on which to operate on
lower_bound: int
lower bound to discard
upper_... | bigcode/self-oss-instruct-sc2-concepts |
def supportScalar(location, support, ot=True):
"""Returns the scalar multiplier at location, for a master
with support. If ot is True, then a peak value of zero
for support of an axis means "axis does not participate". That
is how OpenType Variation Font technology works.
>>> supportScalar({}, {})... | bigcode/self-oss-instruct-sc2-concepts |
def get_history_score(history):
"""
Calculate the history score given a list of pass/fail booleans.
Lower indices represent the most recent entries.
"""
if len(history) == 0:
return 0.0
score = 1.0
for index, good in enumerate(history):
if not good:
score -= 0.5 /... | bigcode/self-oss-instruct-sc2-concepts |
def date_specificity(date_string):
"""Detect date specificity of Zotero date string.
Returns 'ymd', 'ym', or 'y' string.
"""
length = len(date_string)
if length == 10:
return 'ymd'
elif length == 7:
return 'ym'
elif length == 4:
return 'y'
return None | bigcode/self-oss-instruct-sc2-concepts |
def ignore(path, ignores):
"""
If the full path of a file in pivt is equal to the full path
of an element in the ignore list then we return True because
we do not want that full path in the list created by walk_root.
:param path: Full path to a file in the pivt directory
:param ignores: A list ... | bigcode/self-oss-instruct-sc2-concepts |
def get_stream_info_string(stream):
""" Returns (compact) string with stream information. """
name = stream.name()
hostname = stream.hostname()
source_id = stream.source_id()
uid = stream.uid()
return '{}@{}[{}][{}]'.format(name, hostname, source_id, uid) | bigcode/self-oss-instruct-sc2-concepts |
def implements(implementor, implementee):
"""
Verifies that the implementor has the same methods and properties as the
implementee. __XXX__ classes are excluded. For the purposes of method
comparison, arguemtn order is importent.
>>> class Implementor(object):
... foo = 1
... def ... | bigcode/self-oss-instruct-sc2-concepts |
def _clean_scale(scale):
"""Cleanup a 'scaling' string to be matplotlib compatible.
"""
scale = scale.lower()
if scale.startswith('lin'):
scale = 'linear'
return scale | bigcode/self-oss-instruct-sc2-concepts |
import string
import random
def random_pwd_generator(length, additional_str=''):
"""Generate random password.
Args:
length: length of the password
additional_str: Optional. Input additonal string that is allowed in
the password. Default to '' empty string.
Returns:... | bigcode/self-oss-instruct-sc2-concepts |
def get_summary_html_name(prj):
"""
Get the name of the summary HTML file for provided project object
:param peppy.Project prj: a project object to compose a summary HTML file name for
:return str: name of the summary HTML file
"""
fname = prj.name
if prj.subproject is not None:
fna... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_metrics(array_sure, array_possible, array_hypothesis):
""" Calculates precision, recall and alignment error rate as described in "A Systematic Comparison of Various
Statistical Alignment Models" (https://www.aclweb.org/anthology/J/J03/J03-1002.pdf) in chapter 5
Args:
array_sure: ... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def loss_creator(config):
"""Constructs the Torch Loss object.
Note that optionally, you can pass in a Torch Loss constructor directly
into the TorchTrainer (i.e., ``TorchTrainer(loss_creator=nn.BCELoss, ...)``).
Args:
config: Configuration dictionary passed into ``TorchTrainer`... | bigcode/self-oss-instruct-sc2-concepts |
def matscalarMul(mat, scalar):
"""Return matrix * scalar."""
dim = len(mat)
return tuple( tuple( mat[i][j] * scalar
for j in range(dim) )
for i in range(dim) ) | bigcode/self-oss-instruct-sc2-concepts |
import re
def slice(text, length=100, offset = 0, last_word=True):
"""
Slice a string.
"""
text = text[offset:]
if len(text) <= length or not last_word:
return text[:length]
return re.sub('(\s+\S+\s*)$', '', text[:length]) | bigcode/self-oss-instruct-sc2-concepts |
def pack_namedtuple_base_class(name: str, index: int) -> str:
"""Generate a name for a namedtuple proxy base class."""
return "namedtuple_%s_%d" % (name, index) | bigcode/self-oss-instruct-sc2-concepts |
def add_project(conn, project):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
sql = ''' INSERT INTO projects(name, begin_date, end_date)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
... | bigcode/self-oss-instruct-sc2-concepts |
def from_file(filename, level="(not set)"):
"""Load test cases from file, return as list of dicts.
Puzzle should be formatted as a string on a single line.
See puzzle.latinsquare.from_string. Trailing whitespace is stripped.
Args:
filename: File to read. One line per puzzle.
level: Lab... | bigcode/self-oss-instruct-sc2-concepts |
def get_type(array):
"""Return type of arrays contained within the dask array chunks."""
try:
datatype = type(array._meta) # Check chunk type backing dask array
except AttributeError:
datatype = type(array) # For all non-dask arrays
return datatype | bigcode/self-oss-instruct-sc2-concepts |
def extract_tensors(tf_graph):
"""
Get input, initial state, final state, and probabilities tensor from the graph
:param loaded_graph: TensorFlow graph loaded from file
:return: Tuple (tensor_input,tensor_initial_state,tensor_final_state, tensor_probs)
"""
tensor_input = tf_graph.get_tensor_by_n... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
def get_spot_request_ids_from_response(response: Dict) -> List[str]:
"""
Return list of all spot request ids from AWS response object
(DescribeInstances)
"""
spot_request_ids = []
for reservation in response['Reservations']:
for inst in ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import inspect
def get_available_class(module, class_name) -> Dict[str, type]:
"""Search specified subclasses of the given class in module.
:param module: The module name
:type module: module
:param class_name: the parent class
:type class_name: type
:return: A dict ma... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_real_float(candidate: Any) -> bool:
"""
Checks if the given `candidate` is a real `float`. An `integer` will return `False`.
Args:
candidate (Any): The candidate to test.
Returns:
bool: Returns `True` if the `candidate` is a real float; otherwise `False.... | bigcode/self-oss-instruct-sc2-concepts |
def char_from_number(number):
""" Converts number to string by rendering it in base 26 using
capital letters as digits """
base = 26
rval = ""
if number == 0:
rval = 'A'
while number != 0:
remainder = number % base
new_char = chr(ord('A') + remainder)
rval = n... | bigcode/self-oss-instruct-sc2-concepts |
def human_readable_bytes(value, digits= 2, delim= "", postfix=""):
"""Return a human-readable file size.
"""
if value is None:
return None
chosen_unit = "B"
for unit in ("KiB", "MiB", "GiB", "TiB"):
if value > 1000:
value /= 1024
chosen_unit = unit
els... | bigcode/self-oss-instruct-sc2-concepts |
def validate_num_results(request):
"""
A utility for parsing the requested number of results per page.
This should catch an invalid number of results and always return
a valid number of results, defaulting to 25.
"""
raw_results = request.GET.get('results')
if raw_results in ['50', '100']:
... | bigcode/self-oss-instruct-sc2-concepts |
def estimate_probability(word, previous_n_gram,
n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):
"""
Estimate the probabilities of a next word using the n-gram counts with k-smoothing
Args:
word: next word
previous_n_gram: A sequence of words of len... | bigcode/self-oss-instruct-sc2-concepts |
def mini_batch_size_update(mini_batch_size, gpu_count):
"""Increase mini-batch size to accommodate more than 1 GPU."""
if gpu_count <= 1:
return mini_batch_size
elif gpu_count > 1:
return mini_batch_size * gpu_count | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pixel_corner_lookup(filename):
"""
Returns (lons, lats, corners), the pickeled objects created by
save_pixel_corner_lookup.
Equivalent to the arguments returned by read_official_corner_lut.
"""
with open(filename, 'rb') as f:
obj = pickle.load(f)
return obj | bigcode/self-oss-instruct-sc2-concepts |
def binlist(n, width=0):
"""
Return list of bits that represent a non-negative integer.
n -- non-negative integer
width -- number of bits in returned zero-filled list (default 0)
"""
return list(map(int, list(bin(n)[2:].zfill(width)))) | bigcode/self-oss-instruct-sc2-concepts |
def andSearch(inverseIndex, query):
"""
Input: an inverse index, as created by makeInverseIndex, and a list of words to query
Output: the set of all document ids that contain _all_ of the specified words
"""
docIds = set()
for q in query:
if q in inverseIndex:
if not docIds:
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_split_timing_info(fn):
"""
Group lines by benchmark iteration, starting from migrad until
after the forks have been terminated.
"""
with open(fn, 'r') as fh:
lines = fh.read().splitlines()
bm_iterations = []
start_indices = []
end_indices = []
for ix, line in en... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def create_verts_index(verts_per_mesh, edges_per_mesh, device=None):
"""
Helper function to group the vertex indices for each mesh. New vertices are
stacked at the end of the original verts tensor, so in order to have
sequential packing, the verts tensor needs to be reordered so that the
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_mean_ci_score(rec):
"""
Parameters
----------
rec : dict
Audio recording record.
Returns
-------
Mean cacaophony index as float or -1 if it could not be found.
"""
ci = -1.0
try:
caco_id = rec['additionalMetadata']['analysis']['cacoph... | bigcode/self-oss-instruct-sc2-concepts |
def destagger(data, dim, new_coord, rename=True):
"""
Destagger WRF output data in given dimension by averaging neighbouring grid points.
Parameters
----------
data : xarray dataarray
input data.
dim : str
destaggering dimension.
new_coord : array-like
new coordinate... | bigcode/self-oss-instruct-sc2-concepts |
def points_at(links, other):
"""Whether any of the links points at the other"""
return any(_.points_at(other) for _ in links) | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_list(input, _type=int, _default_output=None):
"""
Converts the input to a list if not already.
Also performs checks for type of list items and will set output to the default value if type criteria isn't met
Args:
input: input that you are analyzing to convert to list of type
... | bigcode/self-oss-instruct-sc2-concepts |
def calc_channel_current(E, sigma, A):
"""
Calculate channel current
"""
I = E * sigma * A
return I | bigcode/self-oss-instruct-sc2-concepts |
def _make_bin_midpoints(bins):
"""Get midpoints of histogram bins."""
return (bins[:-1] + bins[1:]) / 2 | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def get_relpath(src, dst):
"""
Returns the relative path from ``src`` to ``dst``
Args:
src (``pathlib.Path``): the source directory
dst (``pathlib.Path``): the destination directory
Returns:
``pathlib.Path``: the relative path
"""
# osrc = src
ups =... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def validate_ref_component_optional(ref_component: Optional[int]) -> Optional[int]:
"""
Validates the reference to a component of an object.
:param ref_component: The reference to a component of the object.
:return: The validated reference to a component.
"""
if re... | bigcode/self-oss-instruct-sc2-concepts |
import math
def format_bytes(bytes):
"""
Get human readable version of given bytes.
Ripped from https://github.com/rg3/youtube-dl
"""
if bytes is None:
return 'N/A'
if type(bytes) is str:
bytes = float(bytes)
if bytes == 0.0:
exponent = 0
else:
exponent ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_object_presentation(obj_dict):
"""Returns one of object possible presentation:
- display_name
- title
- name
- slug
if Nothing is presented in serrialized object
than it will return `{tytle}_{id}` presentation.
"""
keys = ("display_name", "title", "name", "slug")
for key in keys:
if o... | bigcode/self-oss-instruct-sc2-concepts |
def distinct(not_distinct_list: list):
"""
Returns a list with no duplicate elements
"""
return list(set(not_distinct_list)) | bigcode/self-oss-instruct-sc2-concepts |
def add_vector(vector, increment, mod = False, bounds = (0, 0)):
"""
Adds two 2D vectors and returns the result
can also do modular arithmitic for wrapping
"""
result = [0, 0]
result[0] = vector[0] + increment[0]
result[1] = vector[1] + increment[1]
if mod:
result[0] = resu... | bigcode/self-oss-instruct-sc2-concepts |
def addHtmlBreaks(s, isXhtml=True):
"""Replace all returns by <br/> or <br>."""
tag = {True:'<br/>\n', False:'<br>\n'}[isXhtml]
return s.replace('\n',tag) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
import itertools
def xor_cipher(string: Iterable[str], key: Iterable[str]) -> str:
"""XOR шифр
:param string: Шифруемый/расшифровываемый текст
:type string: Iterable[str]
:param key: Ключ
:type key: Iterable[str]
:return: Текст после шифровки/дешифровки
:rtype:... | bigcode/self-oss-instruct-sc2-concepts |
def read_words(words_file):
""" (file open for reading) -> list of str
Return a list of all words (with newlines removed) from open file
words_file.
Precondition: Each line of the file contains a word in uppercase characters
from the standard English alphabet.
"""
f = open(words_file)
... | bigcode/self-oss-instruct-sc2-concepts |
def diff(list1, list2):
"""
Returns the list of entries that are present in list1 but not
in list2.
Args:
list1 A list of elements
list2 Another list of elements
Returns:
A list of elements unique to list1
"""
diffed_list = []
for item in list1:
if item not in list2:
diffed_list.... | bigcode/self-oss-instruct-sc2-concepts |
def agg_across_entities(entity_lists_by_doc):
"""
Return aggregate entities in descending order by count.
"""
if not entity_lists_by_doc or len(entity_lists_by_doc) == 0:
return []
result_set = {}
for doc_id in entity_lists_by_doc.keys():
cur_list = entity_lists_by_doc[doc_id]
... | bigcode/self-oss-instruct-sc2-concepts |
def GetMosysPlatform(config):
"""Get the name of the mosys platform for this board.
cros_config_schema validates there is only one mosys platform per
board. This function finds and prints the first platform name.
Args:
config: A CrosConfig instance.
Returns:
An exit status (0 for success, 1 for fa... | bigcode/self-oss-instruct-sc2-concepts |
def get_operations(product_id):
"""Get ProductImageCreate operations
Parameters
----------
product_id : str
id for which the product image will be created.
Returns
-------
query : str
variables: dict
"""
query = """
mutation ProductImageCreate($product: ID!,... | bigcode/self-oss-instruct-sc2-concepts |
def _fabric_intent_map_name(fabric_name, intent_map):
"""Fabric intent map name.
:param fabric_name: string
:param intent_map: string AR intent map name
:return: string
"""
return '%s-%s' % (fabric_name, intent_map) | bigcode/self-oss-instruct-sc2-concepts |
def get_score_list(lines, start_index=0):
"""
:param start_index: Optional index where to start the score checking.
:param lines: List of lines containing binary numbers.
:return: List of scores for each line index, score is +1 for '1' and -1 for '0'
e.g. line '101' gets score [1, -1, 1] an... | bigcode/self-oss-instruct-sc2-concepts |
def getFingerPrintOnCount(A):
"""
Input:
Iterable having boolean values 0 or 1
Output:
Count of number of 1 found in A
"""
count = 0
for i in A:
if(i == 1):
count += 1
return count | bigcode/self-oss-instruct-sc2-concepts |
def mix(color1, color2, pos=0.5):
"""
Return the mix of two colors at a state of :pos:
Retruns color1 * pos + color2 * (1 - pos)
"""
opp_pos = 1 - pos
red = color1[0] * pos + color2[0] * opp_pos
green = color1[1] * pos + color2[1] * opp_pos
blue = color1[2] * pos + color2[2] * opp_pos
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def is_mod_function(mod, fun):
"""Checks if a function in a module was declared in that module.
http://stackoverflow.com/a/1107150/3004221
Args:
mod: the module
fun: the function
"""
return inspect.isfunction(fun) and inspect.getmodule(fun) == mod | bigcode/self-oss-instruct-sc2-concepts |
def fill_matrix(matrix: list[list[int]]):
"""
Return a new list of lists (matrix) where inner lists all have the same
length. Inner lists that are short elements have the element 0 added.
"""
result = []
lengths = [len(row) for row in matrix]
maxlen = max(lengths)
for (i, row) in enumera... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def all_subclasses(cls: type) -> Tuple[type, ...]:
"""All subclasses of a class.
From: http://stackoverflow.com/a/17246726/2692780
"""
subclasses = []
for subclass in cls.__subclasses__():
subclasses.append(subclass)
subclasses.extend(all_subclasses(subcla... | bigcode/self-oss-instruct-sc2-concepts |
def milli_2_readadble(msecs):
"""Function: milli_2_readadble
Description: Converts milliseconds into days, hours, minutes and seconds.
Returns values with appropriate tags.
Arguments:
(input) msecs -> Milliseconds.
"""
data = msecs / 1000
seconds = data % 60
data /= 60... | bigcode/self-oss-instruct-sc2-concepts |
def macTolist(hexMac):
"""
converts hex MAC string to list
:param hexMax: MAC address to convert (string)
:returns: list of MAC address integers
"""
return [int(i,16) for i in hexMac.split('-')] | bigcode/self-oss-instruct-sc2-concepts |
def reaction_splitter(reaction):
"""
Args:
reaction (str) - reaction with correct spacing and correct reaction arrow `=>`
Returns (list):
List of compounds in the reaction
Example:
>>>reaction_splitter("c6h12o6 + 6o2 => 6h2o + 6co2")
['c6h12o6', '6o2', '6h2o... | bigcode/self-oss-instruct-sc2-concepts |
def expand_iupac(base: str, fill_n: bool=False) -> (str):
"""
Expand the IUPAC base
:param base: the IUPAC base to expand
:param fill_n: should we fill N or leave it empty
:return: a string with all the primary
bases that are encoded by the
IUPAC bases
"""
if base =... | bigcode/self-oss-instruct-sc2-concepts |
def size(self):
""" Return the size or length of the linked list. """
size = 0
node = self.head
while node:
size += 1
node = node.next
return size | bigcode/self-oss-instruct-sc2-concepts |
def to_loxone_level(level):
"""Convert the given HASS light level (0-255) to Loxone (0.0-100.0)."""
return float((level * 100) / 255) | bigcode/self-oss-instruct-sc2-concepts |
def _getfield(history, field):
"""
Return the last value in the trace, or None if there is no
last value or no trace.
"""
trace = getattr(history, field, [])
try:
return trace[0]
except IndexError:
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def pct_arg_to_int(arg):
"""Parse a numeric string that represents a percentage in units of 0.1%. 1000 == 100%"""
pat = re.compile("[0-9]{4,4}$")
m = pat.match(arg)
if m is None:
raise ValueError(f"Invalid percent string: {arg!r}")
pct = int(m.group(0))
if pct < 0 or pct > 1... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def themes_dir() -> pathlib.Path:
"""Return the directory where the themes are located."""
here = pathlib.Path(__file__).parent
return here.joinpath('themes') | bigcode/self-oss-instruct-sc2-concepts |
from math import cos, pi, sqrt
def linear_dist_sphere(radius: float, surf_dist: float, depth_a: float, depth_b: float) -> float:
"""
The purpose of this function is to find the actual, linear distance between the hypocenter of
and earthquake and the bottom of a fracking well. It's a more general proble... | bigcode/self-oss-instruct-sc2-concepts |
def is_maximum_in_period(cube):
"""Check if cube contains maximum values during time period."""
for cell_met in cube.cell_methods:
if cell_met.method == 'maximum' and 'time' in cell_met.coord_names:
return True | bigcode/self-oss-instruct-sc2-concepts |
def tuple_slice(tup, start, end):
"""get sliced tuple from start and end."""
return tup[start:end] | bigcode/self-oss-instruct-sc2-concepts |
def defaultModel(t, alpha=3.0, beta=None):
"""
See ebisu's defaultModel function documentation.
Note: This app's init_model function provides default alpha=2
instead of alpha=3.0, but it's a small difference, and this
function goes with default alpha=3.0.
"""
if beta is None:
beta =... | 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.