seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def parse_ipmi_sdr(output):
"""Parse the output of the sdr info retrieved with ipmitool"""
hrdw = []
for line in output:
items = line.split("|")
if len(items) < 3:
continue
if "Not Readable" in line:
hrdw.append(('ipmi', items[0].strip(), 'value', 'Not Reada... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def repository(tmp_path: Path) -> Path:
"""Fixture for a repository."""
path = tmp_path / "repository"
path.mkdir()
(path / "marker").write_text("Lorem")
return path | bigcode/self-oss-instruct-sc2-concepts |
def latest_actions_only(items):
"""Keep only the most recent occurrence of each action, while preserving the order"""
used = set()
res = []
for item in reversed(items):
if item not in used:
res.append(item)
used.add(item)
return reversed(res) | bigcode/self-oss-instruct-sc2-concepts |
def planet(armageddon):
"""Return a default planet (exponential atmosphere)"""
return armageddon.Planet() | bigcode/self-oss-instruct-sc2-concepts |
def mult_with_submatrix(A, columns, x):
"""Computes :math:`b = A[:, I] x`
"""
A = A[:, columns]
return A @ x | bigcode/self-oss-instruct-sc2-concepts |
def set_cover(X, subsets):
"""
This algorithm finds an approximate solution
to finding a minimum collection of subsets
that cover the set X.
It is shown in lecture that this is a
(1 + log(n))-approximation algorithm.
"""
cover = set()
subsets_copy = list(subsets)
while True:
S = max(subsets_co... | bigcode/self-oss-instruct-sc2-concepts |
def _validate_float(value):
""" Convert an arbitrary Python object to a float, or raise TypeError.
"""
if type(value) is float: # fast path for common case
return value
try:
nb_float = type(value).__float__
except AttributeError:
raise TypeError(
"Object of type ... | bigcode/self-oss-instruct-sc2-concepts |
def lr_lin_reduction(learning_rate_start = 1e-3, learning_rate_stop = 1e-5, epo = 10000, epomin= 1000):
"""
Make learning rate schedule function for linear reduction.
Args:
learning_rate_start (float, optional): Learning rate to start with. The default is 1e-3.
learning_rate_stop (float, op... | bigcode/self-oss-instruct-sc2-concepts |
def split_conn_port(connection):
"""Return port number of a string such as 'port0' as an
integer, or raise ValueError if format is invalid"""
try:
return int(connection.split('port', 1)[1])
except (ValueError, IndexError):
msg = "port string %s does not match format 'port<N>' for integer... | bigcode/self-oss-instruct-sc2-concepts |
def tail(list, n):
""" Return the last n elements of a list """
return list[:n] | bigcode/self-oss-instruct-sc2-concepts |
import torch
def categorical_focal_loss(y_true, y_pred):
"""
Reference: https://github.com/umbertogriffo/focal-loss-keras
Softmax version of focal loss.
m
FL = SUM -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)
c=1
where m = number of classes, c = class and o = observa... | bigcode/self-oss-instruct-sc2-concepts |
def compute_loss(logits, target, criterion):
"""
logits shape: [seq-len, batch-size, output_dim]
target shape: [batch-size, seq-len]
"""
loss = criterion(logits, target)
return loss | bigcode/self-oss-instruct-sc2-concepts |
def _add(a: int, b: int) -> int:
"""Add two numbers together.
Args:
a (int): First number.
b (int): Second number.
Returns:
int: A sum of two numbers.
"""
return a + b | bigcode/self-oss-instruct-sc2-concepts |
def _parse_list_file(path):
"""
Parses files with lists of items into a list of strings.
Files should contain one item per line.
"""
with open(path, 'r') as f:
items = [i for i in f.read().split('\n') if i != '']
return items | bigcode/self-oss-instruct-sc2-concepts |
def first_elem(s):
""" Extracts first element of pandas Series s, or returns s if not a series. """
try:
return s.iloc[0]
except AttributeError:
return s | bigcode/self-oss-instruct-sc2-concepts |
import glob
def get_images(path):
"""
Checks the folder for images
:param path: The folder in which we will check for images
:return: An array of all images found
"""
path = path
images = glob.glob(path + "**/**/**/*.jpg", recursive=True)
images.extend((glob.glob(path + "**/**/**/*.png... | bigcode/self-oss-instruct-sc2-concepts |
from itertools import chain, repeat
from typing import Iterable
from typing import Iterator
def ncycles(it: Iterable, n: int) -> Iterator:
"""
Returns the sequence elements n times
>>> [*ncycles(range(3), 3)]
[0, 1, 2, 0, 1, 2, 0, 1, 2]
"""
return chain.from_iterable(repeat(it, n)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_audio_paths(dataset_root_path, lst_name):
"""Extract audio paths."""
audio_paths = []
with open(dataset_root_path / "scoring" / lst_name) as f:
for line in f:
audio_path, lang = tuple(line.strip().split())
if lang != "nnenglish":
continue
... | bigcode/self-oss-instruct-sc2-concepts |
def foreground_color(bg_color):
"""
Return the ideal foreground color (black or white) for a given background color in hexadecimal RGB format.
"""
bg_color = bg_color.strip('#')
r, g, b = [int(bg_color[c:c + 2], 16) for c in (0, 2, 4)]
if r * 0.299 + g * 0.587 + b * 0.114 > 186:
return '... | bigcode/self-oss-instruct-sc2-concepts |
def count_trajectories(n: int) -> int:
"""
The Grasshopper is in position 1.
The Grasshopper may jump to +1, +2 or +3.
How many possible trajectories does the grasshopper have to get to position n?
If n<=1, consider that the Grasshopper has 0 possible trajectory.
>>> count_trajectories(0)
0... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_request(url, max_tries=10):
""" Get JSON data from BiGG RESTful API.
Args:
url (str): url request
max_tries (int): maximum number of communication attempts (default: 10)
Returns:
dict: json data
"""
resp, data = None, None
for i in range(max_... | bigcode/self-oss-instruct-sc2-concepts |
def ubfx(value, lsb, width):
"""Unsigned Bitfield Extract"""
return (value >> lsb) & ((1 << width) - 1) | bigcode/self-oss-instruct-sc2-concepts |
def interleaved2complex(data):
"""
Make a complex array from interleaved data.
"""
return data[..., ::2] + 1j * data[..., 1::2] | bigcode/self-oss-instruct-sc2-concepts |
import inspect
import gc
def gc_objects_by_type(tipe):
"""
Return a list of objects from the garbage collector by type.
"""
if isinstance(tipe, str):
return [o for o in gc.get_objects() if type(o).__name__ == tipe]
elif inspect.isclass(tipe):
return [o for o in gc.get_objects() if ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import List
def _nt_quote_args(args: Optional[List[str]]) -> List[str]:
"""Quote command-line arguments for DOS/Windows conventions.
Just wraps every argument which contains blanks in double quotes, and
returns a new argument list.
"""
# Cover None-type
... | bigcode/self-oss-instruct-sc2-concepts |
def sign_extend(value: int, orig_size: int, dest_size: int) -> int:
"""
Calculates the sign extension for a provided value and a specified destination size.
:param value: value to be sign extended
:param orig_size: byte width of value
:param dest_size: byte width of value to extend to.
:return:... | bigcode/self-oss-instruct-sc2-concepts |
def identity(*args):
"""
Return whatever is passed in
Examples
--------
>>> x = 1
>>> y = 2
>>> identity(x)
1
>>> identity(x, y)
(1, 2)
>>> identity(*(x, y))
(1, 2)
"""
return args if len(args) > 1 else args[0] | bigcode/self-oss-instruct-sc2-concepts |
def _convert_to_index_name(s):
"""Converts a string to an Elasticsearch index name."""
# For Elasticsearch index name restrictions, see
# https://github.com/DataBiosphere/data-explorer-indexers/issues/5#issue-308168951
# Elasticsearch allows single quote in index names. However, they cause other
# p... | bigcode/self-oss-instruct-sc2-concepts |
import re
def coerceColType(colType):
"""
Given a colType, coerce to closest native SQLite type and return that, otherwise raise a ValueError.
Parameters:
colType (str): column type from DBML specification.
Returns:
str: valid SQLite column type.
"""
colType = colType.upper()
n... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import importlib
import ast
def load_cli(import_str: str) -> Any:
"""Load the cli object from a import name. Adapted from gunicorn.
Examples:
flask.cli:cli
pipx.cli:create_parser()
"""
import_name, _, obj = import_str.partition(":")
if not (import_name and ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_regex_string(string):
"""
Parse header string according to wappalizer DB format
strings follow the below format:
<string>[\\;version:\\\d][\\;confidence:\d]
"string" is a mandatory regex string followed by 0 or more parameters (key:value), can be empty
parameters are divided by a \\;... | bigcode/self-oss-instruct-sc2-concepts |
from math import pi as π, radians
def theoretical_peak_angle_velocity(stride_freq_Hz: float = 3.,
total_angle_deg: float = 180.,
disp: bool = True):
"""Cheetah leg moves from 0⁰ -> 90⁰ -> 0⁰ in about 1/3 of a second. Ie, follows the shape:
... | bigcode/self-oss-instruct-sc2-concepts |
def Courant(alpha, h, c):
"""
Computes the courant condition.
Parameters
----------
alpha: Scaling parameter (generally 0.4)
h: array of h's
c: array of speeds of sound
Returns
-------
float: min. time step according to courant condition... | bigcode/self-oss-instruct-sc2-concepts |
def cal_iou(box1, box2):
"""
computing IoU
:param box1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param box2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
cx1, cy1, cx2, cy2 = box1
gx1, gy1, gx2, gy2 = box2
# 计算每个矩形的面积
S_rec1 = (cx2 - cx1) * (cy... | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def _get_embl_wrapper(embl_key, indent=5, subsequent_indent=None, width=80):
"""Returns a textwrap.TextWrapper for embl records (eg, write
<key> <string> by providing embl key and a string. Wrap text to
80 column"""
# define the string to prepen (eg "OC ")
prepend = '{key:<{in... | bigcode/self-oss-instruct-sc2-concepts |
def find_worst(list_of_values, quantity):
"""
auxiliary function to changeworst,
finds the indexes of the worst performing members
:param list_of_values: list of values relative to the members of the candidate
used to determine which is the worst performing ones
:param quantity: the quantity... | bigcode/self-oss-instruct-sc2-concepts |
def get_resource_file(entity, resource_info, base_url):
"""
Create a file object from which resource data can be read.
resource_info is a value returned by `find_fixed_resource` or `find_entity_resource`
base_url is a base URL that may be used to resolving relative references in the
... | bigcode/self-oss-instruct-sc2-concepts |
def field_eq(p, e):
"""
Checks the field values of a parsed message for equality against
some ground truth value.
Parameters
----------
p : object with dict-like attributed access
Parsed field contents.
e : object with dict-like attributed access
Expected field contents.
Returns
----------
... | bigcode/self-oss-instruct-sc2-concepts |
def _format_list(elems):
"""Formats the given list to use as a BUILD rule attribute."""
elems = ["\"{}\"".format(elem) for elem in elems]
if not elems:
return "[]"
if len(elems) == 1:
return "[{}]".format(elems[0])
return "[\n {},\n ]".format(",\n ".join(elems)) | bigcode/self-oss-instruct-sc2-concepts |
def footer() -> str:
"""
Return the footer of the LaTeX document.
:return: LaTeX document footer.
"""
return "\\end{tikzcd}\n\\end{document}" | bigcode/self-oss-instruct-sc2-concepts |
def ReformatForLog( data ):
"""
Change all non printable characters into something human readable.
Arguments:
data -- The raw data that may contain unprintable characters
Example: 0x0D will show up as <D>
"""
output = ''
for char in data:
o = ord( char )
if( o < 32 ): # Unprintable control character... | bigcode/self-oss-instruct-sc2-concepts |
def read_text_file(filename):
"""
Read .txt file
Args:
:param: filename(str): the name of .txt file
Returns:
:param: text(str): text in .txt file
"""
with open(filename, "r", encoding="utf-16") as file:
text = file.readlines()
return str(text) | bigcode/self-oss-instruct-sc2-concepts |
def _filterobsoleterevs(repo, revs):
"""returns a set of the obsolete revisions in revs"""
return {r for r in revs if repo[r].obsolete()} | bigcode/self-oss-instruct-sc2-concepts |
def parse_mode(new_mode):
"""Function to parse a mode give in input to chmod function.
Parameters
----------
new_mode --> str, the new resource permissions, in the form of [0-7][0-7][0-7]
Returns
-------
(own,grp,others) --> tuple(int,int,int), the permissions parsed
"""
#t... | bigcode/self-oss-instruct-sc2-concepts |
def iseven(n):
"""
Return True if n is an even number and False otherwise.
"""
return (n % 2 == 0) | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_object_classes(classes_or_instances, expected_base_class=None):
"""Given a list of instances or class objects, return the list of their classes.
:param classes_or_instances: mixed list to parse
:type classes_or_instances: list[type or object]
:param expected_base_class: if give... | bigcode/self-oss-instruct-sc2-concepts |
def d(b, a, bnds):
"""
Calculate difference between two images
Parameters:
b (ee.Image): 'before' image
a (ee.Image): 'after' image
bnds (ee.List<str>): band names included in calculation
Returns:
ee.Image: difference image with original bands
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def find_nth_natural_number(i, limit):
"""Returns the ith natural number and the number containing it"""
assert i >= 1
number_map = {}
nums = []
prev_len = 0
for num in range(1, limit + 1):
nums.append(num)
new_len = len(str(num)) + prev_len
number_map.update({j: (prev_le... | bigcode/self-oss-instruct-sc2-concepts |
import re
def form_date_parameter(date: str, name: str) -> str:
"""Form the date parameter for the API query after checking whether given date is valid.
Args:
date (str): date in format YYYY-MM-DD
name (str): either 'startDate' or 'endDate', used to differentiate API query parameters
Rai... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def matvec(mat, vec, out=None):
"""Matrix-vector product (supports broadcasting)
Parameters
----------
mat : (..., M, N) tensor
Input matrix.
vec : (..., N) tensor
Input vector.
out : (..., M) tensor, optional
Placeholder for the output tensor.
Return... | bigcode/self-oss-instruct-sc2-concepts |
def acquire_title(soup):
"""
Take a BeautifulSoup content of a book page.
Return the title of the book.
"""
title = soup.h1.string
return title | bigcode/self-oss-instruct-sc2-concepts |
def find_samples(data):
"""
Parse a list of raw packages into a list of raw samples
:param data: List of raw packages (int)
:return: samples, fail_count.
samples: List of raw samples
fail_count: number of samples that could not be decoded
"""
sample = None
looking_... | bigcode/self-oss-instruct-sc2-concepts |
def load_room_descrips(data, room_names):
"""
Loading each rooms respective main description.
Parameters:
data(dict): Nested dictionaries containing
all information of the game.
room_names(list): List containg room names.
Returns:
room_descrips(list): Returns list o... | bigcode/self-oss-instruct-sc2-concepts |
def lines2paragraphs(lines):
"""
Return a list of paragraphs from a list of lines
(normally holding the lines in a file).
"""
p = [] # list of paragraphs to be returned
firstline = 0 # first line in a paragraph
currentline = 0 # current line in the file
lines.insert(l... | bigcode/self-oss-instruct-sc2-concepts |
def bytes_as_char_array(b): # type: (bytes) -> str
"""
Given a sequence of bytes, format as a char array
"""
return '{ ' + ', '.join('0x%02x' % x for x in b) + ' }' | bigcode/self-oss-instruct-sc2-concepts |
def get_cpubind(cpu_binding):
"""Convert aprun-style CPU binding to PALS-style"""
# First check for keywords
if not cpu_binding or cpu_binding == "cpu":
return "thread"
if cpu_binding == "depth":
return "depth"
if cpu_binding == "numa_node":
return "numa"
if cpu_binding =... | bigcode/self-oss-instruct-sc2-concepts |
def info_to_name(display):
"""extract root value from display name
e.g. function(my_function) => my_function
"""
try:
return display.split("(")[1].rstrip(")")
except IndexError:
return "" | bigcode/self-oss-instruct-sc2-concepts |
def get_x_minmax(start_times, end_times):
"""Determine the horizontal (x) min and max values.
This function adds 1% to either side for padding.
Args:
start_times (np.array): First packet unix timestamps of all pcaps.
end_times (np.array): Last packet unix timestamps of all pcaps.
Retur... | bigcode/self-oss-instruct-sc2-concepts |
def get_busco_score(short_summary):
"""get busco Complete score from short_summary.txt"""
with open(short_summary) as f:
for line in f:
line = line.strip()
if line.startswith(("#", "*")) or line == "":
continue
elif line.startswith("C:"):
... | bigcode/self-oss-instruct-sc2-concepts |
def rgb_to_hex(rgb):
"""
Covert RGB tuple to Hex code
"""
return f'0x{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}' | bigcode/self-oss-instruct-sc2-concepts |
def is_managed_by_cloudformation(physical_resource_id: str, resource_array: list) -> bool:
"""
Given a physical resource id and array of rources - returns if the resource is managed by cloudformation
Parameters:
physical_resource_id (string): The identifier of the resource - eg igw-09a7b4932e331edb... | bigcode/self-oss-instruct-sc2-concepts |
def combine_QUBO_storage(QUBO_storage, solved_QUBOs, column_solutions):
"""
Merges previous QUBO storage with new solutions.
Parameters
----------
QUBO_storage : list
Input QUBO storage list.
solved_QUBOs : dict
The QUBOs that were solved in this latest iteration.
column_sol... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_week_format_from_timestamp(timestamp_millis: int) -> str:
"""Get week format from timestamp in milliseconds. The week number
returned will follow ISO-8601 standard
:param timestamp_millis: Timestamp in milliseconds.
:type timestamp_millis: int
:return: Return... | bigcode/self-oss-instruct-sc2-concepts |
def counting_sort(array, maxval):
"""
Sorts the list 'array' using counting sort
>>> from pydsa import counting_sort
>>> a = [5, 6, 1, 9, 3]
>>> counting_sort(a, 9)
[1, 3, 5, 6, 9]
"""
count = [0] * (maxval + 1)
for a in array:
count[a] += 1
i = 0
for a in range(max... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_string_from_comment(comment):
"""Extract a string from a comment formatted like this:
'/u/<username> string' or
'/u/<username>
string' """
lines = comment.body.split("\n")
try:
if lines[0] != "/u/check_em_out":
assert lines[0].startswith("/u... | bigcode/self-oss-instruct-sc2-concepts |
def Nu_dist(Re_outtube_dist, Pr_coolwater_dist):
"""
Calculates the Nusselt criterion of coolwater.
Parameters
----------
Re_outtube_dist : float
The Reynold criterion, [dimensionless]
Pr_coolwater_dist : float
The Prandtl criterion, [dimensionless]
Returns
-------
Nu... | bigcode/self-oss-instruct-sc2-concepts |
def get_rb_blob_attribute(blobdict, attr):
"""Get Attribute `attr` from dict `blobdict`
Parameters
----------
blobdict : dict
Blob Description Dictionary
attr : string
Attribute key
Returns
-------
ret : Attribute Value
"""
try:
value = blobdict['BLOB'][... | bigcode/self-oss-instruct-sc2-concepts |
def bxor(*args):
"""Return the bitwise xor of all arguments."""
res = 0
for arg in args:
res ^= arg
return res | bigcode/self-oss-instruct-sc2-concepts |
def b_count(pattern):
"""
Count the number of B's that occur in a site pattern
Input:
pattern --- a site pattern
Output:
num_b --- the number of B's in the site pattern
"""
num_b = 0
for char in pattern:
if char == "B":
num_b += 1
return num_b | bigcode/self-oss-instruct-sc2-concepts |
import torch
def adaptive_add_fusion(z: torch.Tensor, p: torch.Tensor):
"""Adds a point cloud to a noise tensor that can have a smaller dimension.
The noise tensor `z` with `dim_z` channels will be added to the first `dim_z`
channels of the point cloud `p`.
Args:
z: Reference point cloud of ... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def Aggregate_median_SABV_AGE(rnaseq):
"""Compute median TPM by gene+tissue+sex+age."""
logging.info("=== Aggregate_median_SABV_AGE:")
logging.info(f"Aggregate_median_SABV_AGE IN: nrows = {rnaseq.shape[0]}, cols: {str(rnaseq.columns.tolist())}")
rnaseq = rnaseq[["ENSG", "SMTSD", "SEX", "AGE", "... | bigcode/self-oss-instruct-sc2-concepts |
def try_mine(block):
"""Updates the nonce and sees if it's valid.
"""
block.nonce += 1
return block.is_valid() | bigcode/self-oss-instruct-sc2-concepts |
def v0_is_perfect_square(number):
"""Return True if given number is the square of an integer."""
return int(number**0.5)**2 == number | bigcode/self-oss-instruct-sc2-concepts |
def unpack_and_split_nodes(data, path):
"""Unpack a list of results
Args:
data: A dictionary containing the results
path: A list of fields indicating the fields to select.
final one should be a list of nodes
Returns:
issues: A list of dicts; each dict is the data for some of
the results
... | bigcode/self-oss-instruct-sc2-concepts |
def evaluate(function, param1, param2):
"""
Returns <function>, called with <param1> and <param2>
"""
return function(param1, param2) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _linear_interpolation_utilities(v_norm, v0_src, size_src, v0_dst, size_dst, size_z):
"""
Computes utility values for linear interpolation at points v.
The points are given as normalized offsets in the source interval
(v0_src, v0_src + size_src), more precisely:
v = v0_src + v_... | bigcode/self-oss-instruct-sc2-concepts |
def is_truthy(data):
"""
Returns True if the data is a truthy value, False otherwise.
"""
string = str(data).lower()
return string in ['true', '1', 'f'] | bigcode/self-oss-instruct-sc2-concepts |
def get_toolchain_dir(toolchain_dir_output):
"""Find the toolchain directory."""
prefix = 'vs_path = '
for line in toolchain_dir_output.splitlines():
if line.startswith(prefix):
return line[len(prefix):].strip('"')
raise Exception('Unable to find toolchain dir in output:\n%s' % (
too... | bigcode/self-oss-instruct-sc2-concepts |
def cal_accuracy_on_2(sample_label_prob_dict_list, test_label_list):
"""
:param
sample_label_prob_dict_list:
[
{1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1}
{1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1}
...
]
test_label_list:
[1,2,5... | bigcode/self-oss-instruct-sc2-concepts |
def reciprocate_currency(dataframe, reciprocal_list):
"""
Reciprocate the values of columns for currencies subordinate to USD
:param dataframe: dataframe to reciprocate values
:param reciprocal_list: list of currencies to reciprocate values for
:return: dataframe with reciprocated values
"""
regex_reciprocal =... | bigcode/self-oss-instruct-sc2-concepts |
import socket
import struct
def unpack_ip_addr(addr):
"""Given a six-octet BACnet address, return an IP address tuple."""
if isinstance(addr, bytearray):
addr = bytes(addr)
return (socket.inet_ntoa(addr[0:4]), struct.unpack('!H', addr[4:6])[0]) | bigcode/self-oss-instruct-sc2-concepts |
def get_provenance(
software_name="x", software_version="y", schema_version="1", environment=None,
parameters=None):
"""
Utility function to return a provenance document for testing.
"""
document = {
"schema_version": schema_version,
"software": {
"name": soft... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_metrics(filestr:str):
"""
Load metric dict from filestr
Args:
filestr (str): strig to save dict to
Return:
metrics (dict): loaded metrics
"""
# pickle load
with open(filestr, 'rb') as f:
metrics = pickle.load(f)
return metrics | bigcode/self-oss-instruct-sc2-concepts |
def leap_year(year: int) -> bool:
"""Report if a year is leap.
:param year: int - year.
:return: bool
"""
return (year % 4 == 0 and not year % 100 == 0) or year % 400 == 0 | bigcode/self-oss-instruct-sc2-concepts |
def check_pkt_filter_report_hash(mode):
"""Check if Flow Director hash match reporting mode is valid
There are three modes for the reporting mode.
* none
* match (default)
* always
"""
if mode in ['none', 'match', 'always']:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def causal_estimation(cpi, rate):
"""
Calculate all the data to make a causal estimation of the exchange rate,
according to the PPP theory: ex_rate_USD_UYU ~= a * CPI_uy / CPI_us
The constant "a" is calculated with the expanding mean of the previous
values. The function makes no predictions into the... | bigcode/self-oss-instruct-sc2-concepts |
def volume_prisma(area_dasar: float, tinggi: float) -> float:
"""
kalkulasi dari volume prisma
referensi
https://en.wikipedia.org/wiki/Prism_(geometry)
>>> volume_prisma(10, 2)
20.0
>>> volume_prisma(11, 1)
11.0
"""
return float(area_dasar * tinggi) | bigcode/self-oss-instruct-sc2-concepts |
def getSeqPos(ref_profile, seq):
"""
Get the start and end position when mapped to refSeq.
Sequence to feed to the func should be afa format
(e.x. one from mothurAligner).
Parameters:
-----------
ref_profile : list
a gap profile, 0 is gap and 1 is real base pair.
seq : str
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def parse_arrayindexandlength(number):
"""
Returns an array index and length tuple for the given number.
"""
# Could just use >> and & for this, but since we have to be more
# careful with LinkIdAndLinkedBehavior anyway, since that one's
# weirder, we may as well just use struct ... | bigcode/self-oss-instruct-sc2-concepts |
def prepare_special_error_type(source, target, error_type, charset=None):
"""
Remove all non-matching words from both the source and the target string.
Args:
source (str): Source string.
target (str): Target string.
error_type (str): One of: 'copy_chars', 'uppercase', 'digits',
... | bigcode/self-oss-instruct-sc2-concepts |
def self(client):
"""Requests information on role of the current user."""
return client.get_role_self() | bigcode/self-oss-instruct-sc2-concepts |
def no_c(my_string):
"""
removes all instances of 'c' & 'C' from string
"""
new_str = ""
for i in range(len(my_string)):
if my_string[i] != 'c' and my_string[i] != 'C':
new_str += my_string[i]
return (new_str) | bigcode/self-oss-instruct-sc2-concepts |
import math
def abs(x):
"""Return the absolute value of x"""
return math.fabs(x) | bigcode/self-oss-instruct-sc2-concepts |
def jupyter_get_variable(name, magic_command_instance):
"""
Retrieves the value of a local variable in a notebook.
@param name variable name
@param magic_command_instance instance of `Magics <http://ipython.readthedocs.io/en/stable/api/
... | bigcode/self-oss-instruct-sc2-concepts |
def get_tx_input_amount(tx):
"""Returns the the total input amount"""
inp_amount = 0
for inp in tx.inputs:
inp_amount += inp.witness_utxo.value
return inp_amount | bigcode/self-oss-instruct-sc2-concepts |
def xor(string, byte):
"""Exclusive-ors each character in a string with the given byte."""
results = []
for ch in string:
results.append(chr(ord(ch) ^ byte))
return ''.join(results) | bigcode/self-oss-instruct-sc2-concepts |
def CheckChangeHasTestField(input_api, output_api):
"""Requires that the changelist have a TEST= field."""
if input_api.change.TEST:
return []
else:
return [output_api.PresubmitNotifyResult(
'Changelist should have a TEST= field. TEST=none is allowed.')] | bigcode/self-oss-instruct-sc2-concepts |
def shorter_name(key):
"""Return a shorter name for an id.
Does this by only taking the last part of the URI,
after the last / and the last #. Also replaces - and . with _.
Parameters
----------
key: str
Some URI
Returns
-------
key_short: str
A shortened, but more... | bigcode/self-oss-instruct-sc2-concepts |
def _catmull_rom_weighting_function(x: float) -> float:
"""Catmull-Rom filter's weighting function.
For more information about the Catmull-Rom filter, see
`Cubic Filters <https://legacy.imagemagick.org/Usage/filter/#cubics>`_.
Args:
x (float): distance to source pixel.
Returns:
fl... | bigcode/self-oss-instruct-sc2-concepts |
def convert_neg(arr, size):
"""
Convert any negative indices into their positive equivalent.
This only works for a 1D array.
Parameters
----------
arr : ndarray
Array having negative indices converted.
size : int
Dimension of the array.
Returns
-------
ndarray
... | 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.