seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_safe_filename(title):
"""
Get a safe string to use as a filename
:param title: your target file title
:return: the filename to use
:rtype: str
"""
keep_chars = (' ', '.', '_')
return "".join(c for c in title if c.isalnum() or c in keep_chars).rstrip() | bigcode/self-oss-instruct-sc2-concepts |
def time_format(num, digits=1, align_unit=False):
# type: (float, int, bool) -> str
"""Format and scale output according to standard time
units.
Example
-------
>>> time_format(0)
'0.0 s'
>>> time_format(0, align_unit=True)
'0.0 s '
>>> time_format(0.002)
'2.0 ms'
>>> t... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_accuracy(dataloader, pred_list, nb_models):
"""
Computes the accuracy across al batches between the true labels in the dataloader and the batch predictions in pred_list
------------------
Input:
dataloader: contains the validation dataset X,y
pred_list: list of of tens... | bigcode/self-oss-instruct-sc2-concepts |
def get_flood_risk_rating(num):
"""Converts an integer value of a flood risk rating to the rating it
represents - low (0/1), moderate (2), high (3), severe (4)"""
if num == 0 or num == 1:
return "Low"
if num == 2:
return "Moderate"
if num == 3:
return "High"
if num == 4... | bigcode/self-oss-instruct-sc2-concepts |
def cross_compile(*args, **kwargs):
"""Compile the source string into a code object
__future__ imports change the behavior of default compile function
This function just provides the 'compile' free of __future__ imports
"""
return compile(*args, **kwargs) | bigcode/self-oss-instruct-sc2-concepts |
def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ["__doc__"])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retv... | bigcode/self-oss-instruct-sc2-concepts |
def get_channel(version: str) -> str:
"""Find channel based on version number."""
if "dev0" in version:
return "dev"
if "dev" in version:
return "nightly"
if "b" in version:
return "beta"
return "stable" | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def splitall(path):
"""
Split path into each part, top catalogue on top, filename (if included) last
"""
out = Path(path).parts
return out | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Union
from typing import Tuple
import operator
def _ensure_index(x: Any) -> Union[int, Tuple[int, ...]]:
"""Ensure x is either an index or a tuple of indices."""
try:
return operator.index(x)
except TypeError:
return tuple(map(operator.index, x)) | bigcode/self-oss-instruct-sc2-concepts |
def line_pad(linestr, padding=''):
"""
:param linestr: multiple line string with `\n` as line separator.
:param padding: left padding string to add before each line.
It could also be a callable object that returns a string.
This is useful when creating dynamic padding.
:return: multiple line s... | bigcode/self-oss-instruct-sc2-concepts |
def mat_var(data, struc, field):
"""Get the 'field' from the 'struc' in the 'data' imported from Matlab"""
return data[struc][field].item() | bigcode/self-oss-instruct-sc2-concepts |
def _cols_if_none(X, self_cols):
"""Since numerous transformers in the preprocessing
and feature selection modules take ``cols`` arguments
(which could end up as ``None`` via the ``validate_is_pd``
method), this will return the columns that should be used.
Parameters
----------
X : Pandas ... | bigcode/self-oss-instruct-sc2-concepts |
def torch_to_numpy(t):
"""
torch tensor to numpy array
:param t: the torch tensor
:return: numpy array
"""
return t.numpy() | bigcode/self-oss-instruct-sc2-concepts |
def gen_target_cfg_items(target_cfg):
"""
Convert target_cfg to list of target configs
"""
if isinstance(target_cfg, list):
# list of templates defined for this target
return target_cfg
elif isinstance(target_cfg, dict):
# only one template defined for this target
ret... | bigcode/self-oss-instruct-sc2-concepts |
def intersection(l1, l2):
"""Return intersection of two lists as a new list::
>>> intersection([1, 2, 3], [2, 3, 4])
[2, 3]
>>> intersection([1, 2, 3], [1, 2, 3, 4])
[1, 2, 3]
>>> intersection([1, 2, 3], [3, 4])
[3]
>>> intersection([1, 2, 3], [4, 5, 6])
... | bigcode/self-oss-instruct-sc2-concepts |
def _equiv_topology(top_1, top_2):
"""Compare topologies using string reps of atoms and bonds"""
for (b1, b2) in zip(top_1.bonds(), top_2.bonds()):
if str(b1) != str(b2):
return False
for (a1, a2) in zip(top_1.atoms(), top_2.atoms()):
if str(a1) != str(a2):
return Fa... | bigcode/self-oss-instruct-sc2-concepts |
import re
def ProcessGitHubLinks(markup, github):
"""Replaces the GitHub local links by the external variants."""
markup = re.sub(
r'#(\d+)',
r'[#\1](https://github.com/%s/issues/\1)' % github,
markup)
markup = re.sub(
r'\[(.+?)\]\((wiki/.+?)\)',
r'[\1](https://github.com/%s/\2)' %... | bigcode/self-oss-instruct-sc2-concepts |
def transpose(df):
"""Transpose df, set 'Date' as index, and strip columns."""
df = df.T.reset_index().rename(columns={"index" : "Date"})
return df.set_index("Date") | bigcode/self-oss-instruct-sc2-concepts |
def unique_label(operator):
"""Function for generating short name for operator from it's address. It takes first 6 and last 4 symbols and
combines it. """
return operator[:6] + operator[-4:] | bigcode/self-oss-instruct-sc2-concepts |
import re
def sphinx_escape(value):
""" Escapes SphinxQL search expressions. """
if not isinstance(value, str):
return value
value = re.sub(r"([=<>()|!@~&/^$\-\'\"\\])", r'\\\\\\\1', value)
value = re.sub(r'\b(SENTENCE|PARAGRAPH)\b', r'\\\\\\\1', value)
return value | bigcode/self-oss-instruct-sc2-concepts |
import base64
def s2b(s: str) -> bytes:
"""b64 string to bytes."""
return base64.b64decode(s) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def constant_schedule(value: Union[float, int]):
"""Constructs a constant schedule.
Args:
value: value to be held constant throughout.
Returns:
schedule: A function that maps step counts to values.
"""
return lambda count: value | bigcode/self-oss-instruct-sc2-concepts |
def parse_lon_lat(grid, lon, lat):
""" Parse lat and lon parameters """
if lat is None:
lat = grid.axes['lat']['data'][0]
if lon is None:
lon = grid.axes['lon']['data'][0]
return lon, lat | bigcode/self-oss-instruct-sc2-concepts |
def get_unique(frame, column_name):
"""
Helper function to get unique count for column
"""
return frame[column_name].value_counts().compute() | bigcode/self-oss-instruct-sc2-concepts |
def get_properties(dataset, property_offsets=None):
"""
Extract properties and return values in a dictionary:
{
'properties':
{
'datetime': time,
'odc:creation_datetime': creation_time,
...
}
}
"""
props = dict()
props['datetime'] = dataset.center_ti... | bigcode/self-oss-instruct-sc2-concepts |
def get_enduse_regs(
enduse,
fuels_disagg):
"""
Get a specific enduse for all regions
Arguments
---------
enduse : str
Enduse to sum
fuels_disagg : list
Fuels per disaggregated regions
Returns
-------
fuels_enduse : dict
Fuels of an enduse fo... | bigcode/self-oss-instruct-sc2-concepts |
import random
def next_unused_name_in_group(grp, length):
""" Gives a name that isn't used in a Group.
Generates a name of the desired length that is not a Dataset or
Group in the given group. Note, if length is not large enough and
`grp` is full enough, there may be no available names meaning that
... | bigcode/self-oss-instruct-sc2-concepts |
import six
def elide(string, max_length, ellipsis="...", position=1.0):
"""
Elides characters to reduce a string to a maximum length.
Replaces elided characters with an ellipsis.
>>> string = "Hello, world. This is a test."
>>> elide(string, 24)
'Hello, world. This i...'
>>> e... | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_hex(input_string: str):
"""Convert input_string into string of hexadecimal values."""
return " ".join([hex(ord(ch))[2:] for ch in input_string]) | bigcode/self-oss-instruct-sc2-concepts |
def convert_uint32_to_array(value):
""" Convert a number into an array of 4 bytes (LSB). """
return [
(value >> 0 & 0xFF),
(value >> 8 & 0xFF),
(value >> 16 & 0xFF),
(value >> 24 & 0xFF)
] | bigcode/self-oss-instruct-sc2-concepts |
def solve(v):
""" Sum big numbers and get first digits. """
# no gmp support, pruning table
# int32 support: trunc digits
t = (
37107, #2875339021027,
46376, #9376774900097,
74324, #9861995247410,
91942, #2133635741615,
23067, #5882075393461,
89261, #67069... | bigcode/self-oss-instruct-sc2-concepts |
def read_data(filename):
""" read the cities data ffrom txt file and store them as a list of tuples of (x, y) """
cities = []
with open(filename) as f:
lines = f.readlines()
n = int(lines[0].split()[0])
for line in lines[1:]:
cities.append((float(line.split()[0]), float(l... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def Factorial(x):
"""Computes the factorial of an integer number.
"""
# 0) SECURITY CHECK
if not isinstance(x, int):
raise ValueError( "'Factorial' function only accepts integers" )
# 1) COMPUTE THE FACTORIAL
if x == 0 or x == 1:
return 1
else:
ret... | bigcode/self-oss-instruct-sc2-concepts |
def motifPosCmp(motifOcc1, motifOcc2):
"""Compares two motif occurences according to their position on a given
sequence. The occurences must be on the same sequence."""
assert(motifOcc1.getSeqName() == motifOcc2.getSeqName())
motifOcc1Centre = motifOcc1.getCentre()
motifOcc2Centre = motifOcc2.getCe... | bigcode/self-oss-instruct-sc2-concepts |
import typing
import pkg_resources
def get_imagenet_classes() -> typing.List[str]:
"""Get the list of ImageNet 2012 classes."""
filepath = pkg_resources.resource_filename("vit_keras", "imagenet2012.txt")
with open(filepath) as f:
classes = [l.strip() for l in f.readlines()]
return classes | bigcode/self-oss-instruct-sc2-concepts |
import math
def pts_near(gt_bbx, pred_bbx, rad): # change name
"""
Determine if two points are within a radius.
Parameters
----------
gt_bbx : dict
[centre_x, centre_y]
pred_bbx : dict
[centre_x, centre_y]
Returns
-------
True or False
"""
# creat... | bigcode/self-oss-instruct-sc2-concepts |
def len4bytes(v1, v2, v3, v4):
"""Return the packet body length when represented on 4 bytes"""
return (v1 << 24) | (v2 << 16) | (v3 << 8) | v4 | bigcode/self-oss-instruct-sc2-concepts |
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result ... | bigcode/self-oss-instruct-sc2-concepts |
def create_word_count_dict(word_count_queryset):
"""
This function creates a dictionary where the keys are word names
and the values are word counts from a given queryset.
:param word_count_queryset: A WordCountQueryset containing word names
and their associated word counts.
:return: A dictionar... | bigcode/self-oss-instruct-sc2-concepts |
def unique_list(l):
"""Remove duplicate term from a list
Parameters
----------
l : list
A list potentially contains duplicate terms
Returns
ulist : list
A list without unique terms
"""
ulist = []
for item in l:
if item not in ulist:
u... | bigcode/self-oss-instruct-sc2-concepts |
import random
def mutUniform(individual, expr, pset):
"""Randomly select a point in the tree *individual*, then replace the
subtree at that point as a root by the expression generated using method
:func:`expr`.
:param individual: The tree to be mutated.
:param expr: A function object that can gen... | bigcode/self-oss-instruct-sc2-concepts |
import random
def randomize(applicants):
"""
Random permutation of applicant list. Typical usage is before
prioritization.
"""
return random.sample(applicants, k = len(applicants)) | bigcode/self-oss-instruct-sc2-concepts |
def _arithmetic_mean(nums) -> float:
"""Return arithmetic mean of nums : (a1 + a2 + ... + an)/n"""
return sum(nums) / len(nums) | bigcode/self-oss-instruct-sc2-concepts |
def tag(tag, url_name=None):
"""
Render a tag and a URL to filter by it if the base URL is provided.
"""
return {"tag": tag, "url_name": url_name} | bigcode/self-oss-instruct-sc2-concepts |
def get_reference_id(url: str):
"""
Return the reference id from a URL
For example:
>>> get_reference_id("https://github.com/advisories/GHSA-c9hw-wf7x-jp9j")
'GHSA-c9hw-wf7x-jp9j'
"""
_url, _, ref_id = url.strip("/").rpartition("/")
return ref_id | bigcode/self-oss-instruct-sc2-concepts |
def centroid_of_points(pts):
"""Returns the centroid of a cluster of points. Automatically
works with either 2D or 3D point tuples."""
xs, ys, zs = 0, 0, 0
for pt in pts:
xs += pt[0]
ys += pt[1]
if len(pt) > 2:
zs += pt[2]
if len(pts) > 0:
xs /= len(pts)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Tuple
def _get_callable_info(callable: Callable) -> Tuple[str, str]:
"""Returns type and name of a callable.
Parameters
----------
callable
The callable
Returns
-------
Tuple[str, str]
The type and name of the callable. Type ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def uncamel(phrase, sep='-'):
"""
converts camelcase phrase into seperated lower-case phrase
Parameters
---
phrase : str
phrase to convert
Examples
---
>>> uncamel('HTTPRequestHeader')
'http-request-header'
>>> uncamel('StatusCode404', sep=' ')
'... | bigcode/self-oss-instruct-sc2-concepts |
def load_data_and_labels(filename, encoding="utf-8"):
"""Loads data and label from a file.
Args:
filename (str): path to the file.
encoding (str): file encoding format.
The file format is tab-separated values.
A blank line is required at the end of a sentence.
For exam... | bigcode/self-oss-instruct-sc2-concepts |
def trim_middle(arbitrary_string: str, max_length: int) -> str:
"""
Trim down strings to max_length by cutting out the middle.
This assumes that the most "interesting" bits are toward
the beginning and the end.
Adds a highly unusual '✂✂✂' in the middle where characters
were stripped out, to avo... | bigcode/self-oss-instruct-sc2-concepts |
def _get_categorization_parameters_for_extract_study(extract_study_id, dict_cur):
"""
returns a dictionary keyed by (vocabulary_id, concept_code) of lists of rows.
The rows are dictionaries as those returned by a dict_cur.
param extract_study_id
Returns dictionary keyed by (vocabu... | bigcode/self-oss-instruct-sc2-concepts |
def float_or_none(arg):
"""Returns None or float from a `float_or_none` input argument.
"""
if arg is None or str(arg).lower() == 'none':
return None
return float(arg) | bigcode/self-oss-instruct-sc2-concepts |
def get_position_left(original_position):
"""
Given a position (x,y) returns the position to the left of the original position, defined as (x-1,y)
"""
(x,y) = original_position
return(x-1,y) | bigcode/self-oss-instruct-sc2-concepts |
def get_fields(fields, response):
"""Extracts desired fields from the API response"""
results = {}
for field in fields:
results[field] = response.get(field)
return results | bigcode/self-oss-instruct-sc2-concepts |
def withdraw_money(amount, card_balance):
"""Withdraw given amount of money from the account."""
card_balance -= amount
# save new balnace to the database
return card_balance | bigcode/self-oss-instruct-sc2-concepts |
def convert_batch_idx_to_window_idx(batch_idx, ws_multiplier):
"""return absolute_window_idx that batch_idx is in"""
return int(batch_idx/ws_multiplier) | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def read_object(filename):
"""Convenience function for retrieving object from file using pickle.
Arguments:
filename {str} -- path to file
Returns:
object -- object in file (uses pickle)
"""
with open(filename, 'rb') as file:
obj = pickle.load(file)
... | bigcode/self-oss-instruct-sc2-concepts |
def match_content_type(filename: str) -> str:
"""
Match file extensions to content-type. A quick lightweight list.
This is needed so s3 vends the right MIME type when the file is downloaded
directly from the bucket.
"""
content_type_match = {
'json': 'application/json',
'js': 'ap... | bigcode/self-oss-instruct-sc2-concepts |
def duplicate(my_list):
"""Return a new list that repeats the input twice"""
return my_list + my_list | bigcode/self-oss-instruct-sc2-concepts |
def filter_providers_by_type(providers, type):
"""
helper function to filter a list of providers by type
:param providers: ``list``
:param type: str
:returns: filtered ``dict`` provider
"""
providers_ = {provider['type']: provider for provider in providers}
return providers_.get(type,... | bigcode/self-oss-instruct-sc2-concepts |
def get_full_module_name(o, lower=False):
"""
Returns the full module and class name of an object o.
For example, for our :class: OntonotesReader, returns
'nlp.forte.data.readers.ontonotes_reader.OntonotesReader'.
"""
if not isinstance(o, type):
o = o.__class__
module = o.__module__
... | bigcode/self-oss-instruct-sc2-concepts |
def expression_polynomial(cobj, prop, T):
"""
Create expressions for CoolProp rational polynomial forms
Args:
cobj: Component object that will contain the parameters
prop: name of property parameters are associated with
T: temperature to use in expression
Returns:
Pyomo... | bigcode/self-oss-instruct-sc2-concepts |
def any_ga(geoawi):
"""
GEOAWI: GA W/I GRID
0=None
1=Quest
2=<I2
3=<O2
4=<1/2 DA
5=<1DA
6=<2DA
7=>2DA
8=CG
Returns:
0, 1, 88
"""
if geoawi == 0:
return 0
elif 1 <= geoawi <= 7:
return 1
elif geo... | bigcode/self-oss-instruct-sc2-concepts |
def _merge_weights(spin_d1, spin_d2):
"""Sum the weights stored in two dictionaries with keys being the spins"""
if len(spin_d1) != len(spin_d2):
raise RuntimeError("Critical - mismatch spin-dict length")
out = {}
for spin in spin_d1:
out[spin] = spin_d1[spin] + spin_d2[spin]
return ... | bigcode/self-oss-instruct-sc2-concepts |
def read(path, open_flags='r'):
"""Opens file at |path| with |open_flags| reads it and then returns the
result."""
with open(path, open_flags) as file_handle:
return file_handle.read() | bigcode/self-oss-instruct-sc2-concepts |
def valueToString(v):
"""
>>> valueToString(0)
'0'
>>> valueToString(10)
'10'
>>> valueToString(-10)
'-10'
>>> valueToString(0.1)
'0.1'
>>> valueToString(0.0001)
'0.0001'
>>> valueToString(0.00001)
'0'
>>> valueToString(10.0001)
'10.0001'
>>> valueToString... | bigcode/self-oss-instruct-sc2-concepts |
def period_starts(counter, period):
"""
Utility function to test whether we are at the beginning of a cycle
of length `period`.
If the period is non positive, this always return False, otherwise
it returns True when `counter` is 0, cycle, 2*cycle, etc.
@param counter typically an epoch index, o... | bigcode/self-oss-instruct-sc2-concepts |
def get_vararg_name(varargs_name, i):
# type: (str, int) -> str
""" Given some integer i, return the name of the ith vararg.
Note that the given internal names to these parameters are
impossible to be assigned by the user because they are invalid
Python variable names, as they start with a star
... | bigcode/self-oss-instruct-sc2-concepts |
def get_options(options, names):
"""Returns a dictionary with options for the given keys.
Args:
options: dict
names: list of keys
Returns:
dict
"""
new = {}
for name in names:
if name in options:
new[name] = options[name]
return new | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def list_digest(inp_list):
"""Return a digest to uniquely identify a list."""
if type(inp_list) is not list:
raise TypeError("list_digest only works on lists!")
if not inp_list:
raise ValueError("input must be a non-empty list!")
# If we can rely on python >= 3.8, shlex.... | bigcode/self-oss-instruct-sc2-concepts |
def create_api_auth_refresh_parms(_client_id, _api_secret, _refresh_token):
"""
Creates the request parameters necessary to refresh an authentication token.
@param _client_id: Client ID magic string from the API setup.
@param _api_secret: Super secret API secret from the API setup that you are never allowed to see ... | bigcode/self-oss-instruct-sc2-concepts |
def quote_title(title):
"""Quote an article name of a MediaWiki page."""
return title.replace(" ", "_") | bigcode/self-oss-instruct-sc2-concepts |
import random
def max_weight_paths(k, weight_paths_dict, paths_to_edges, overlap=True, norev=False, rgen=None):
"""
Returns k largest-weight paths. The function proceeds in order through descending weight values to select paths,
and if an entire weight class of paths is not to be included, applies a pred... | bigcode/self-oss-instruct-sc2-concepts |
def load_processed_data(processed_path, parsed_reader):
""" Load parsed results from disk
:param processed_path: the file name to a file that stores parsed results
:type processed_path: str
:param parsed_reader: the parsed reader to load parsed results
:type parsed_reader: ParsedReader
:return:... | bigcode/self-oss-instruct-sc2-concepts |
def get_month_as_str_col(df, date_col):
"""Generate a pandas series of the month as a string in YYYY-MM format from the date column.
Parameters
----------
df : pandas df
Pandas dataframe
date_col : str
Name of the column in the dataframe containing the timestamp
Returns
---... | bigcode/self-oss-instruct-sc2-concepts |
def calc_IoU(bbox1, bbox2):
"""
Calculate intersection over union for two boxes.
Args:
bbox1 (array_like[int]): Endpoints of the first bounding box
in the next format: [ymin, xmin, ymax, xmax].
bbox2 (array_like[int]): Endpoints of the second bounding box
in the next... | bigcode/self-oss-instruct-sc2-concepts |
def is_(self, state):
"""Check if machine is in given state."""
translator = self._meta['translator']
state = translator.translate(state)
return self.actual_state == state | bigcode/self-oss-instruct-sc2-concepts |
def remove_quotation_marks(source_string):
"""
:param source_string: String from which quotation marks will be removed (but only the outermost).
:return: String without the outermost quotation marks and the outermost white characters.
"""
first = source_string.find('"')
second = source_string[fi... | bigcode/self-oss-instruct-sc2-concepts |
def write_file(filename="", text=""):
"""Write a string to a text file"""
with open(filename, 'w') as f:
c = f.write(text)
return c | bigcode/self-oss-instruct-sc2-concepts |
import re
def pick_only_key_sentence(text, keyword):
"""
If we want to get all sentence with particular keyword.
We can use below function.
Parameters
----------
text: str
Text selected to apply transformation.
keyword: str
Word to search within the phrase... | bigcode/self-oss-instruct-sc2-concepts |
def coverageTruncatedToString(coverage) :
"""Converts the coverage percentage to a formatted string.
Returns: coveragePercentageAsString, coverageTruncatedToOneDecimalPlace
Keyword arguments:
coverage - The coverage percentage.
"""
# Truncate the 2nd decimal place, rather than rounding
# to... | bigcode/self-oss-instruct-sc2-concepts |
def get_nodes(dag):
"""
Returns the names of all nodes found in dag
"""
nodes = dag.sig.names
for node in dag.nodes:
if node not in nodes and isinstance(node, str):
nodes.append(node)
return nodes | bigcode/self-oss-instruct-sc2-concepts |
def validate_transaction(spend_amounts, tokens_amounts):
"""
A transaction is considered valid here if the amounts of tokens
in the source UTXOs are greater than or equal to the amounts to spend.
:param spend_amounts: amounts to spend
:param tokens_amounts: existing amounts to spend from
:retur... | bigcode/self-oss-instruct-sc2-concepts |
def poly(X, Y, degree):
"""
Polynomial kernel implementation.
X, Y: The matrices between which pairwise distances
are computed.
degree: The degree of the polynomial
"""
return (X @ Y.T + 1)**degree | bigcode/self-oss-instruct-sc2-concepts |
def k2f(k: float, r: int = 2) -> float:
"""Kelvin to Fahrenheit."""
return round(((k - 273.15) * (9 / 5)) + 32, r) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def resolve_doc_file_path(module_name: str, out_dir: Path, file_extension: str) -> Path:
"""Return the absolute path to a rendered doc file
Args:
module_name (str): the module name, i.e. "networkx.drawing.layout"
out_dir (Path): the output directory, i.e. Path("/build... | bigcode/self-oss-instruct-sc2-concepts |
import six
def to_text(s, encoding="utf-8"):
"""
Converts the bytes to a text type, if not already.
:s: the bytes to convert to text
:returns: `unicode` on Python2 and `str` on Python3.
"""
if isinstance(s, six.text_type):
return s
else:
return six.binary_type(s).decode(en... | bigcode/self-oss-instruct-sc2-concepts |
def find_between( s, first, last ):
"""Find a string between two characters."""
try:
start = s.index(first) + len(first)
end = s.index(last, start)
return s[start:end]
except ValueError:
return "" | bigcode/self-oss-instruct-sc2-concepts |
def get_name_value(line):
"""Get benchmark name and result from a text line"""
name = line.split()[1]
value = int(line.split()[4])
return name,value | bigcode/self-oss-instruct-sc2-concepts |
def is_sunday(date):
"""Is the specified date (a datetime.date object) a Sunday?"""
return date.weekday() == 6 | bigcode/self-oss-instruct-sc2-concepts |
def query_registry(model, registry):
"""Performs a lookup on a content type registry.
Args:
model: a Django model class
registry: a python dictionary like
```
{
"my_app_label": True,
"my_other_model": {
"my_model": True,... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_md5(payload):
"""
Generate md5 hash of a payload
:param payload: The payload to be hashed.
:returns: md5 hash
:rtype: str
"""
return hashlib.md5(payload).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def scores(L):
"""Get the scores (position * alphabet score) for all words in list."""
scores = []
for key, val in enumerate(L):
scores.append(val * (key + 1))
return scores | bigcode/self-oss-instruct-sc2-concepts |
def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,
choice_col,
availability_vars,
wide_data):
"""
Checks whether or not each ob... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_path_info(path_info):
"""
Parse path info formatted like a/c/f where c and f are optional
and a leading / accepted.
Return tuple (a, c, f). If invalid path_info a is set to None.
If c or f are omitted they are set to None.
"""
mo = re.match(r'^/?(?P<a>\w+)(/(?P<c>\w+)(... | bigcode/self-oss-instruct-sc2-concepts |
def do_check(func, files, status):
"""
Generic do_check helper method
Args:
func (function): Specific function to call
files (list): list of files to run against
status (list): list of pre-receive check failures to eventually print
to the user
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def checkscheme(arglist, arg):
"""Returns index of arg in arglist or if not found returns -1.
"""
return arglist.index(arg) if arg in arglist else -1 | bigcode/self-oss-instruct-sc2-concepts |
def total_number_of_clusters(tree) -> int:
"""Get the number of leaves in the tree."""
if tree is None:
return 1
return sum(total_number_of_clusters(subtree)
for subtree in tree.subregions) | bigcode/self-oss-instruct-sc2-concepts |
import math
def round_to_n(x: float, n_digits: int) -> float:
"""Round a floating point to n significant digits
Args:
x (float): Number to round
n_digits (int): Number of digits to keep
Returns:
float: Rounded version of x with n_digits digits
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import time
def log_tail(contents=''):
"""return a string, which can be write to the tail of a log files"""
s = '================================================================\n'
s += '[time] ' + time.asctime(time.localtime()) + '\n'
s += '[program finish succeed!]\n'
s += contents
s += '=... | 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.