seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import math
def _flat_hex_coords(centre, size, i):
""" Return the point coordinate of a flat-topped regular hexagon.
points are returned in counter-clockwise order as i increases
the first coordinate (i=0) will be:
centre.x + size, centre.y
"""
angle_deg = 60 * i
angle_rad = math.pi / 180 * angle_deg
return (
centre.x + size * math.cos(angle_rad),
centre.y + size * math.sin(angle_rad),
) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def make_get_request(uri: str, payload):
"""
Function to make a GET request to API Endpoint
:param uri:
:param payload:
:return:
"""
response = requests.get(uri, payload)
if response.status_code != 200:
return None
else:
return response.json() | bigcode/self-oss-instruct-sc2-concepts |
def has_two_adjacent(password):
"""Check if the password contains a pair of adjacent digits"""
last_char = None
num_adjacent = 0
for char in password:
if char == last_char:
num_adjacent += 1
else:
if num_adjacent == 1:
return True
last_char = char
num_adjacent = 0
if num_adjacent == 1:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
def dot(A, B, dim=-1):
"""
Computes the dot product of the input tensors along the specified dimension
Parameters
----------
A : Tensor
first input tensor
B : Tensor
second input tensor
dim : int (optional)
dimension along the dot product is computed (default is 1)
Returns
-------
Tensor
the tensor containing the dot products
"""
return torch.sum(A*B, dim, keepdim=True) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def check_prefix(prefix: Union[str, tuple, list], content: str):
"""Determines whether or not the prefix matches the content.
Parameters
----------
prefix : Union[str, tuple, list]
The affix that appears at the beginning of a sentence.
content : str
The string that contains the content.
Returns
-------
starts_with_prefix : bool
_description_
"""
starts_with_prefix = bool(content.startswith(tuple(prefix)))
return starts_with_prefix | bigcode/self-oss-instruct-sc2-concepts |
def _account_data(cloud):
"""Generate the auth data JSON response."""
claims = cloud.claims
return {
'email': claims['email'],
'sub_exp': claims['custom:sub-exp'],
'cloud': cloud.iot.state,
} | bigcode/self-oss-instruct-sc2-concepts |
def _determine_start(lines):
"""
Determines where the section listing all SMART attributes begins.
:param lines: the input split into lines.
:type lines: list[str]
:return: the index of the first attribute.
:rtype: int
"""
cnt = 0
for idx, val in enumerate(lines):
if lines[idx].startswith("======"):
cnt += 1
if cnt == 2:
return idx + 1 | bigcode/self-oss-instruct-sc2-concepts |
def specificrulevalue(ruleset, summary, default=None):
"""
Determine the most specific policy for a system with the given multiattractor summary.
The ruleset is a dict of rules, where each key is an aspect of varying specificity:
- 2-tuples are the most specific and match systems with that summary.
- Integers are less specific and match systems with that number of distinct attractors.
- The None key indicates the default rule.
"""
specific = None
attractors, monotonic = summary
if summary in ruleset:
specific = summary
elif attractors in ruleset:
specific = attractors
return ruleset[specific] if specific in ruleset else default | bigcode/self-oss-instruct-sc2-concepts |
def rotate90_point(x, y, rotate90origin=()):
"""Rotates a point 90 degrees CCW in the x-y plane.
Args:
x, y (float): Coordinates.
rotate90origin (tuple): x, y origin for 90 degree CCW rotation in x-y plane.
Returns:
xrot, yrot (float): Rotated coordinates.
"""
# Translate point to origin
x -= rotate90origin[0]
y -= rotate90origin[1]
# 90 degree CCW rotation and translate back
xrot = -y + rotate90origin[0]
yrot = x + rotate90origin[1]
return xrot, yrot | bigcode/self-oss-instruct-sc2-concepts |
def is_dict(value):
"""Checks if value is a dict"""
return isinstance(value, dict) | bigcode/self-oss-instruct-sc2-concepts |
def get_ordinal_suffix(number):
"""Receives a number int and returns it appended with its ordinal suffix,
so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc.
Rules:
https://en.wikipedia.org/wiki/Ordinal_indicator#English
- st is used with numbers ending in 1 (e.g. 1st, pronounced first)
- nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)
- rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)
- As an exception to the above rules, all the "teen" numbers ending with
11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th,
pronounced one hundred [and] twelfth)
- th is used for all other numbers (e.g. 9th, pronounced ninth).
"""
str_num = str(number)
if (len(str_num) > 1 and str_num[-2] == '1') or str_num[-1] == '0' or int(str_num[-1]) > 3:
return str_num + 'th'
elif str_num[-1] == '1':
return str_num + 'st'
elif str_num[-1] == '2':
return str_num + 'nd'
elif str_num[-1] == '3':
return str_num + 'rd'
else:
raise ValueError | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def unique_hash(input_str: str) -> str:
"""Uses MD5 to return a unique key, assuming the input string is unique"""
# assuming default UTF-8
return hashlib.md5(input_str.encode()).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def show_price(price: float) -> str:
"""
>>> show_price(1000)
'$ 1,000.00'
>>> show_price(1_250.75)
'$ 1,250.75'
"""
return "$ {0:,.2f}".format(price) | bigcode/self-oss-instruct-sc2-concepts |
def format_title(title, first_title):
"""
Generates the string for a title of the example page, formatted for a
'sphinx-gallery' example script.
Parameters
----------
title : string
The title string.
first_title : boolean
Indicates whether the title is the first title of the example script.
Returns
-------
string : The formatted string for the example script.
"""
if first_title:
block_str = '"""\n' \
'' + title + '\n' \
''.ljust(len(title) + 1, '=') + '\n' \
'"""\n'
else:
block_str = '# %%\n' \
'# .. rubric:: ' + title + ':\n'
return block_str + '\n' | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_saliency(interpreter, inputs, target):
""" Perform integrated gradient for saliency.
"""
# define saliency interpreter
# interpreter = captum.attr.Saliency(net)
attribution = interpreter.attribute(inputs, target)
attribution = torch.squeeze(attribution)
return torch.sum(attribution, 0) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def parse_gtid_range_string(input_range):
"""Converts a string like "uuid1:id1-id2:id3:id4-id5, uuid2:id6" into a dict like
{"uuid1": [[id1, id2], [id3, id3], [id4, id5]], "uuid2": [[id6, id6]]}. ID ranges are
sorted from lowest to highest"""
# This might be called again for a value that has already been processed
if isinstance(input_range, dict):
return input_range
elif not input_range or not input_range.strip():
return {}
by_uuid = collections.defaultdict(list)
for uuid_and_ranges in input_range.split(","):
server_uuid, *ranges = uuid_and_ranges.strip().split(":")
all_ranges = by_uuid[server_uuid.lower()]
for rng in ranges:
if "-" in rng:
low, high = rng.split("-")
else:
low, high = rng, rng
all_ranges.append([int(low), int(high)])
return {server_uuid: sorted(ranges, key=lambda rng: rng[0]) for server_uuid, ranges in by_uuid.items()} | bigcode/self-oss-instruct-sc2-concepts |
import string
def _clean_string(s):
"""Clean up a string.
Specifically, cleaning up a string entails
1. making it lowercase,
2. replacing spaces with underscores, and
3. removing any characters that are not lowercase letters, numbers, or
underscores.
Parameters
----------
s: str
String to clean up.
Returns
-------
str:
Cleaned up string according to above definition.
"""
valid = string.ascii_lowercase + string.digits + '_'
s_nospace = s.lower().replace(' ', '_')
s_clean = ''.join(char for char in s_nospace if char in valid)
return s_clean | bigcode/self-oss-instruct-sc2-concepts |
def frontiers_from_time_to_bar(seq, bars):
"""
Convert the frontiers in time to a bar index.
The selected bar is the one which end is the closest from the frontier.
Parameters
----------
seq : list of float
The list of frontiers, in time.
bars : list of tuple of floats
The bars, as (start time, end time) tuples.
Returns
-------
seq_barwise : list of integers
List of times converted in bar indexes.
"""
seq_barwise = []
for frontier in seq:
for idx, bar in enumerate(bars):
if frontier >= bar[0] and frontier < bar[1]:
if bar[1] - frontier < frontier - bar[0]:
seq_barwise.append(idx)
else:
if idx == 0:
seq_barwise.append(idx)
#print("The current frontier {} is labelled in the start silence ({},{}), which is incorrect.".format(frontier, bar[0], bar[1]))
else:
seq_barwise.append(idx - 1)
break
return seq_barwise | bigcode/self-oss-instruct-sc2-concepts |
def split_int(i, p):
"""
Split i into p buckets, such that the bucket size is as equal as possible
Args:
i: integer to be split
p: number of buckets
Returns: list of length p, such that sum(list) = i, and the list entries differ by at most 1
"""
split = []
n = i / p # min items per subsequence
r = i % p # remaindered items
for i in range(p):
split.append(int(n + (i < r)))
return split | bigcode/self-oss-instruct-sc2-concepts |
def findNthFibonnachiNumberIterative(n: int) -> int:
"""Find the nth fibonacchi number
Returns:
int: the number output
"""
if n <= 2:
return 1
first, second = 0, 1
while n-1:
third = first + second
first = second
second = third
n -= 1
return second | bigcode/self-oss-instruct-sc2-concepts |
def load_factor(ts, resolution=None, norm=None):
"""
Calculate the ratio of input vs. norm over a given interval.
Parameters
----------
ts : pandas.Series
timeseries
resolution : str, optional
interval over which to calculate the ratio
default: resolution of the input timeseries
norm : int | float, optional
denominator of the ratio
default: the maximum of the input timeseries
Returns
-------
pandas.Series
"""
if norm is None:
norm = ts.max()
if resolution is not None:
ts = ts.resample(rule=resolution).mean()
lf = ts / norm
return lf | bigcode/self-oss-instruct-sc2-concepts |
def construct_iscsi_bdev(client, name, url, initiator_iqn):
"""Construct a iSCSI block device.
Args:
name: name of block device
url: iSCSI URL
initiator_iqn: IQN name to be used by initiator
Returns:
Name of created block device.
"""
params = {
'name': name,
'url': url,
'initiator_iqn': initiator_iqn,
}
return client.call('construct_iscsi_bdev', params) | bigcode/self-oss-instruct-sc2-concepts |
def min_interp(interp_object):
"""
Find the global minimum of a function represented as an interpolation object.
"""
try:
return interp_object.x[interp_object(interp_object.x).argmin()]
except Exception as e:
s = "Cannot find minimum of tthe interpolation object" + str(interp_object.x) + \
"Minimal x: " + str(interp_object.x.min()) + "Maximal x: " + str(interp_object.x.max())
raise e | bigcode/self-oss-instruct-sc2-concepts |
def hasSchema(sUrl):
"""
Checks if the URL has a schema (e.g. http://) or is file/server relative.
Returns True if schema is present, False if not.
"""
iColon = sUrl.find(':');
if iColon > 0:
sSchema = sUrl[0:iColon];
if len(sSchema) >= 2 and len(sSchema) < 16 and sSchema.islower() and sSchema.isalpha():
return True;
return False; | bigcode/self-oss-instruct-sc2-concepts |
def check_knight_move(lhs, rhs):
"""check_knight_move checks whether a knight move is ok."""
col_diff = abs(ord(lhs[0]) - ord(rhs[0]))
row_diff = abs(int(lhs[1]) - int(rhs[1]))
return (col_diff == 2 and row_diff == 1) or (col_diff == 1 and row_diff == 2) | bigcode/self-oss-instruct-sc2-concepts |
def remove(self):
"""Remove this node.
@return: self
"""
self.parent.remove_creator(self)
return self | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def timestamp_ddmmyyyyhhmmss_to_ntp(timestamp_str):
"""
Converts a timestamp string, in the DD Mon YYYY HH:MM:SS format, to NTP time.
:param timestamp_str: a timestamp string in the format DD Mon YYYY HH:MM:SS
:return: Time (float64) in seconds from epoch 01-01-1900.
"""
timestamp = datetime.strptime(timestamp_str, "%d %b %Y %H:%M:%S")
return (timestamp - datetime(1900, 1, 1)).total_seconds() | bigcode/self-oss-instruct-sc2-concepts |
def read_file(file, delimiter):
"""Reads data from a file, separated via delimiter
Args:
file:
Path to file.
delimiter:
Data value separator, similar to using CSV.
Returns:
An array of dict records.
"""
f = open(file, 'r')
lines = f.readlines()
records = []
for line in lines:
# convert to obj first
record = line.strip().split(delimiter)
record_obj = {
'lastName': record[0],
'firstName': record[1],
'gender': record[2],
'favoriteColor': record[3],
'dateOfBirth': record[4]
}
records.append(record_obj)
f.close()
return records | bigcode/self-oss-instruct-sc2-concepts |
import csv
def readAIAresponse(csvFile):
"""Obtains the SDO/AIA responses from a .csv file.
Parameters
----------
csvFile : str
The .csv file with the SDO/AIA responses in it. First line should be labels for each
column as a comma seperated string, e.g. row1=['logt, A94, A171'].
Returns
-------
A dictionary with the responses where the keys are determined by the labels for each column.
"""
with open(csvFile) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
resp = {}
for c,row in enumerate(readCSV):
if c == 0:
for t in row[0].split(sep=", "):
resp[t]=[] # find and make the keys from the first row of the .csv file
else:
for a, key in enumerate(resp.keys()):
resp[key].append(float(row[a])) # match each key to its index in the row
return resp | bigcode/self-oss-instruct-sc2-concepts |
def get_pickle_file_path(file_name, target, folder):
"""
Returns a path to a saved file
Parameters
----------
file_name: str
name of the saved file
target: str
name of target column
folder: str
name of the folder file is saved in
Returns
-------
path to the pickle folder with the filename structure {target}_{variable_name}.pickle in this case
"""
return f'{folder}/{target}_{file_name}.pickle' | bigcode/self-oss-instruct-sc2-concepts |
def model_zero(x, k, y0, y1):
"""
One-compartment first-order exponential decay model
:param x: float time
:param k: float rate constant
:param y0: float initial value
:param y1: float plateau value
:return: value at time point
"""
return y0 - (k * x) | bigcode/self-oss-instruct-sc2-concepts |
def concatenate_codelines(codelines):
""" Compresses a list of strings into one string. """
codeline = ""
for l in codelines:
codeline = codeline + l
return codeline | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def to_pipeline_params(params: dict[str, Any], step_prefix: str):
"""Rename estimator parameters to be usable an a pipeline.
See https://scikit-learn.org/stable/modules/compose.html#pipeline.
"""
return {"{0}__{1}".format(step_prefix, key): value for key, value in params.items()} | bigcode/self-oss-instruct-sc2-concepts |
def toutf8(ustr):
"""Return UTF-8 `str` from unicode @ustr
This is to use the same error handling etc everywhere
if ustr is `str`, just return it
"""
if isinstance(ustr, str):
return ustr
return ustr.encode("UTF-8") | bigcode/self-oss-instruct-sc2-concepts |
def RemoveUppercase(word):
"""Remove the uppercase letters from a word"""
return word.lower() | bigcode/self-oss-instruct-sc2-concepts |
def plural(count=0):
"""Return plural extension for provided count."""
ret = 's'
if count == 1:
ret = ''
return ret | bigcode/self-oss-instruct-sc2-concepts |
def degreeDays(dd0, T, Tbase, doy):
"""
Calculates degree-day sum from the current mean Tair.
INPUT:
dd0 - previous degree-day sum (degC)
T - daily mean temperature (degC)
Tbase - base temperature at which accumulation starts (degC)
doy - day of year 1...366 (integer)
OUTPUT:
x - degree-day sum (degC)
"""
if doy == 1: # reset in the beginning of the year
dd0 = 0.
return dd0 + max(0, T - Tbase) | bigcode/self-oss-instruct-sc2-concepts |
def obj_to_dict(obj, *args, _build=True, _module=None, _name=None,
_submodule=None, **kwargs):
"""Encodes an object in a dictionary for serialization.
Args:
obj: The object to encode in the dictionary.
Other parameters:
_build (bool): Whether the object is to be built on deserialization.
_module (str): Custom name for the module containing the object.
_name (str): Custom name of the object.
_submodule(str): Name of a submodule (e.g. the class holding a
classmethod). Only used when defined.
args: If the object is to be built, the arguments to give on creation.
kwargs: If the object is to be built, the keyword arguments to give on
creation.
Returns:
dict: The dictionary encoding the object.
"""
d = {
"_build": _build,
"__module__": _module if _module else obj.__class__.__module__,
"__name__": _name if _name else obj.__class__.__name__,
}
if _build:
d["__args__"] = args
d["__kwargs__"] = kwargs
if _submodule:
d["__submodule__"] = _submodule
return d | bigcode/self-oss-instruct-sc2-concepts |
def identity(x):
"""x -> x
As a predicate, this function is useless, but it provides a
useful/correct default.
>>> identity(('apple', 'banana', 'cherry'))
('apple', 'banana', 'cherry')
"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def epoch2checkpoint(_epoch: int) -> str:
"""
Args:
_epoch: e.g. 2
Returns:
_checkpoint_name: e.g. 'epoch=2.ckpt'
"""
return f"epoch={_epoch}.ckpt" | bigcode/self-oss-instruct-sc2-concepts |
def ED(first, second):
""" Returns the edit distance between the strings first and second."""
if first == '':
return len(second)
elif second == '':
return len(first)
elif first[0] == second[0]:
return ED(first[1:], second[1:])
else:
substitution = 1 + ED(first[1:], second[1:])
deletion = 1 + ED(first[1:], second)
insertion = 1 + ED(first, second[1:])
return min(substitution, deletion, insertion) | bigcode/self-oss-instruct-sc2-concepts |
def remove_slash(path: str) -> str:
"""Remove slash in the end of path if present.
Args:
path (str): Path.
Returns:
str: Path without slash.
"""
if path[-1] == "/":
path = path[:-1]
return path | bigcode/self-oss-instruct-sc2-concepts |
def chk_chng(src_flist,dst_flist):
""" Returns unchanged file list and changed file list
Accepts source file list and dsetination file list"""
uc_flist = []
c_flist = []
for files in src_flist:
if files in dst_flist:
uc_flist.append(files)
else:
c_flist.append(files)
return uc_flist,c_flist | bigcode/self-oss-instruct-sc2-concepts |
def cnn_estimate(inputs, network, est_fn):
"""
Estimated labelf by the trained cnn network
Inputs
======
inputs: np.ndarray
The test dataset
network: lasagne.layers
The trained cnn network
Output
======
label_est: np.ndarray
The estimated labels
"""
# estimate
print("Estimating ...")
label_est = est_fn(inputs)
return label_est[0] | bigcode/self-oss-instruct-sc2-concepts |
def _can_append_long_entry(e, f):
"""True if f is a FATDirEntry that can follow e. For f to follow e, f and e
must have the same checksum, and f's ordinal must be one less than e"""
return (
f.LDIR_Chksum == e.LDIR_Chksum and
f.long_name_ordinal() + 1 == e.long_name_ordinal()
) | bigcode/self-oss-instruct-sc2-concepts |
def get_declared_licenses(license_object):
"""
Return a list of declared licenses, either strings or dicts.
"""
if not license_object:
return []
if isinstance(license_object, str):
# current, up to date form
return [license_object]
declared_licenses = []
if isinstance(license_object, dict):
# old, deprecated forms
"""
"license": {
"type": "MIT",
"url": "http://github.com/kriskowal/q/raw/master/LICENSE"
}
"""
declared_licenses.append(license_object)
elif isinstance(license_object, list):
# old, deprecated forms
"""
"licenses": [{"type": "Apache License, Version 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0" } ]
or
"licenses": ["MIT"],
"""
declared_licenses.extend(license_object)
return declared_licenses | bigcode/self-oss-instruct-sc2-concepts |
import math
def to_acres(km2):
""" square KM to acres """
if math.isnan(km2):
return 0
return round(km2 * 247.11) | bigcode/self-oss-instruct-sc2-concepts |
def extract_transcript_sequences(bed_dic, seq_dic,
ext_lr=False,
full_hits_only=False):
"""
Given a dictionary with bed regions (region ID -> BED row) and a
sequence dictionary (Sequence ID -> sequence), extract the BED region
sequences and return in new dictionary (region ID -> region sequence).
Optionally, extend regions by ext_lr nt (up- and downstream).
In case full extension is not possible, use maximum extension possible.
Set full_hits_only=True to only recover full hits.
>>> seq_dic = {"T1" : "AAAACCCCGGGGTTTT", "T2" : "ATATACACAGAGCGCGCTCTGTGT"}
>>> bed_dic = {"S1" : "T1\\t4\\t8\\tS1\\t0\\t+", "S2" : "T2\\t6\\t8\\tS2\\t0\\t+"}
>>> extract_transcript_sequences(bed_dic, seq_dic, ext_lr=2)
{'S1': 'AACCCCGG', 'S2': 'ACACAG'}
>>> extract_transcript_sequences(bed_dic, seq_dic, ext_lr=5, full_hits_only=True)
{'S2': 'TATACACAGAGC'}
"""
id2seq_dic = {}
# Process .bed regions.
for reg_id in bed_dic:
cols = bed_dic[reg_id].split("\t")
seq_id = cols[0]
reg_s = int(cols[1])
reg_e = int(cols[2])
assert seq_id in seq_dic, "sequence ID \"%s\" not found in given sequence dictionary" %(seq_id)
seq = seq_dic[seq_id]
# Update region borders.
new_s = reg_s
new_e = reg_e
exp_l = new_e - new_s
# Adjust if given start or end is out of bounds.
if new_s < 0:
new_s = 0
if new_e > len(seq):
new_e = len(seq)
# If region should be extended up- and downstream by ext_lr.
if ext_lr:
new_s = new_s - ext_lr
new_e = reg_e + ext_lr
exp_l = new_e - new_s
# If start or end is out of bounds after extension.
if new_s < 0:
new_s = 0
if new_e > len(seq):
new_e = len(seq)
reg_seq = seq[new_s:new_e]
reg_l = len(reg_seq)
if full_hits_only:
if not reg_l == exp_l:
continue
id2seq_dic[reg_id] = reg_seq
return id2seq_dic | bigcode/self-oss-instruct-sc2-concepts |
import random
def getRandomColor(colorsList):
"""Returns a random color from <colorsList> or OFF"""
if len(colorsList) > 0:
return colorsList[random.randint(0, len(colorsList)-1)]
return 0, 0, 0 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def uri_from_details(namespace: str, load_name: str,
version: Union[str, int],
delimiter='/') -> str:
""" Build a labware URI from its details.
A labware URI is a string that uniquely specifies a labware definition.
:returns str: The URI.
"""
return f'{namespace}{delimiter}{load_name}{delimiter}{version}' | bigcode/self-oss-instruct-sc2-concepts |
def npm_download_url(namespace, name, version, registry='https://registry.npmjs.org'):
"""
Return an npm package tarball download URL given a namespace, name, version
and a base registry URL.
For example:
>>> expected = 'https://registry.npmjs.org/@invisionag/eslint-config-ivx/-/eslint-config-ivx-0.1.4.tgz'
>>> assert npm_download_url('@invisionag', 'eslint-config-ivx', '0.1.4') == expected
>>> expected = 'https://registry.npmjs.org/angular/-/angular-1.6.6.tgz'
>>> assert npm_download_url('', 'angular', '1.6.6') == expected
>>> expected = 'https://registry.npmjs.org/angular/-/angular-1.6.6.tgz'
>>> assert npm_download_url(None, 'angular', '1.6.6') == expected
"""
if namespace:
ns_name = f'{namespace}/{name}'
else:
ns_name = name
return f'{registry}/{ns_name}/-/{name}-{version}.tgz' | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def find_le(a, x):
"""Find the rightmost value of A which is less than or equal to X."""
i = bisect.bisect_right(a, x)
if i: return a[i-1]
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_status_color(status):
"""Return (markup) color for test result status."""
colormap = {"passed": {"green": True, "bold": True},
"failed": {"red": True, "bold": True},
"blocked": {"blue": True, "bold": True},
"skipped": {"yellow": True, "bold": True}}
return colormap.get(status, {}) | bigcode/self-oss-instruct-sc2-concepts |
def date_month(date):
"""Find the month from the given date."""
return date.month | bigcode/self-oss-instruct-sc2-concepts |
def packages(package_helper):
"""Return the list of specified packages (i.e. packages explicitely installed excluding dependencies)"""
return package_helper.specified_packages() | bigcode/self-oss-instruct-sc2-concepts |
def _kron(vec0,vec1):
"""
Calculates the tensor product of two vectors.
"""
new_vec = []
for amp0 in vec0:
for amp1 in vec1:
new_vec.append(amp0*amp1)
return new_vec | bigcode/self-oss-instruct-sc2-concepts |
def get_container_name(framework):
"""Translate the framework into the docker container name."""
return 'baseline-{}'.format({
'tensorflow': 'tf',
'pytorch': 'pyt',
'dynet': 'dy'
}[framework]) | bigcode/self-oss-instruct-sc2-concepts |
def _merge_temporal_interval(temporal_interval_list):
"""
Merge the temporal intervals in the input temporal interval list. This is for situations
when different actions have overlap temporal interval. e.g if the input temporal interval list
is [(1.0, 3.0), (2.0, 4.0)], then [(1.0, 4.0)] will be returned.
:param temporal_interval_list: list of tuples.
List of tuples with (temporal interval start time, temporal interval end time).
:return: list of tuples.
The merged temporal interval list.
"""
# sort by the temporal interval start
temporal_interval_list_sorted = sorted(
temporal_interval_list, key=lambda x: x[0]
)
i = 0
while i < len(temporal_interval_list_sorted) - 1:
a1, b1 = temporal_interval_list_sorted[i]
a2, b2 = temporal_interval_list_sorted[i + 1]
if a2 <= b1:
del temporal_interval_list_sorted[i]
temporal_interval_list_sorted[i] = [a1, max(b1, b2)]
else:
i += 1
return temporal_interval_list_sorted | bigcode/self-oss-instruct-sc2-concepts |
def datetimeToReadable(d, tz):
"""Returns datetime as string in format %H:%M %m/%d/%Y
%d datetime object
%returns string of object in readable format."""
return d.astimezone(tz).strftime("%H:%M %m/%d/%Y") | bigcode/self-oss-instruct-sc2-concepts |
def _default_call_out_of_place(op, x, **kwargs):
"""Default out-of-place evaluation.
Parameters
----------
op : `Operator`
Operator to call
x : ``op.domain`` element
Point in which to call the operator.
kwargs:
Optional arguments to the operator.
Returns
-------
out : `range` element
An object in the operator range. The result of an operator
evaluation.
"""
out = op.range.element()
result = op._call_in_place(x, out, **kwargs)
if result is not None and result is not out:
raise ValueError('`op` returned a different value than `out`.'
'With in-place evaluation, the operator can '
'only return nothing (`None`) or the `out` '
'parameter.')
return out | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def gen_id() -> str:
"""Generate new Skybell IDs."""
return str(uuid.uuid4()) | bigcode/self-oss-instruct-sc2-concepts |
def wrap_list(list_, idx):
"""Return value at index, wrapping if necessary.
Parameters
----------
list_ : :class:`list`
List to wrap around.
idx : :class:`int`
Index of item to return in list.
Returns
-------
:class:`list` element
Item at given index, index will be wrapped if necessary.
"""
return list_[idx % len(list_)] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def get_tensor_dimensions(n_atom_types : int, n_formal_charge : int, n_num_h : int,
n_chirality : int, n_node_features : int, n_edge_features : int,
parameters : dict) -> Tuple[list, list, list, list, int]:
"""
Returns dimensions for all tensors that describe molecular graphs. Tensor dimensions
are `list`s, except for `dim_f_term` which is simply an `int`. Each element
of the lists indicate the corresponding dimension of a particular subgraph matrix
(i.e. `nodes`, `f_add`, etc).
"""
max_nodes = parameters["max_n_nodes"]
# define the matrix dimensions as `list`s
# first for the graph reps...
dim_nodes = [max_nodes, n_node_features]
dim_edges = [max_nodes, max_nodes, n_edge_features]
# ... then for the APDs
if parameters["use_chirality"]:
if parameters["use_explicit_H"] or parameters["ignore_H"]:
dim_f_add = [
parameters["max_n_nodes"],
n_atom_types,
n_formal_charge,
n_chirality,
n_edge_features,
]
else:
dim_f_add = [
parameters["max_n_nodes"],
n_atom_types,
n_formal_charge,
n_num_h,
n_chirality,
n_edge_features,
]
else:
if parameters["use_explicit_H"] or parameters["ignore_H"]:
dim_f_add = [
parameters["max_n_nodes"],
n_atom_types,
n_formal_charge,
n_edge_features,
]
else:
dim_f_add = [
parameters["max_n_nodes"],
n_atom_types,
n_formal_charge,
n_num_h,
n_edge_features,
]
dim_f_conn = [parameters["max_n_nodes"], n_edge_features]
dim_f_term = 1
return dim_nodes, dim_edges, dim_f_add, dim_f_conn, dim_f_term | bigcode/self-oss-instruct-sc2-concepts |
def djb2(s: str) -> int:
"""
Implementation of djb2 hash algorithm that
is popular because of it's magic constants.
>>> djb2('Algorithms')
3782405311
>>> djb2('scramble bits')
1609059040
"""
hash = 5381
for x in s:
hash = ((hash << 5) + hash) + ord(x)
return hash & 0xFFFFFFFF | bigcode/self-oss-instruct-sc2-concepts |
def parse_variable_field(field, re_dict):
"""Function takes a MARC21 field and the Regex dictgroup and
return a list of the subfields that match the Regex patterns.
Parameters:
field -- MARC21 field
re_dict -- Regular Expression dictgroup
"""
output = []
if field is None or re_dict is None:
return output
test_ind1 = re_dict.get('ind1').replace("_", " ")
test_ind2 = re_dict.get('ind2').replace("_", " ")
if field.indicators == [test_ind1, test_ind2]:
output = field.get_subfields(re_dict.get('subfield'))
return output | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from textwrap import dedent
def _commands(fds_file: Path) -> str:
"""Return the commands for PBS job scheduler."""
return dedent(
f"""
# run fds in parallel
mpiexec -np $MPI_NP fds_mpi {fds_file.name}
""".rstrip()
) | bigcode/self-oss-instruct-sc2-concepts |
def is_private(attribute):
"""Return whether an attribute is private."""
return attribute.startswith("_") | bigcode/self-oss-instruct-sc2-concepts |
import re
def single_line_conversion(line):
""" converts a single line typedef to a using statement, preserving whitespace
"""
components = re.split('\s', line)
name = components[-1][:-1] #last item, drop the trailing space
typedef_index = 0
for c in components:
if c == 'typedef':
break
typedef_index = typedef_index + 1
using = 'using ' + name + ' ='
components[typedef_index] = using
new_line = ' '.join(components[:-1]) + ';'
return new_line | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def random_lc_alphanumeric_string(length):
"""Return random lowercase alphanumeric string of specified length."""
return ''.join(random.choice(string.ascii_lowercase + string.digits) for ii in range(length)) | bigcode/self-oss-instruct-sc2-concepts |
def neg_pt(pt, curve):
"""Negate a point.
Args:
pt (tuple(int, int)): Point (x, y). Use (None, None) for point at infinity.
curve (tuple(int, int, int)): (a, b, n) representing the
Elliptic Curve y**2 = x**3 + a*x + b (mod n).
Returns:
tuple(int, int): Point -pt.
"""
if pt == (None, None):
return (None, None)
x, y = pt
_a, _b, n = curve
return (x, n - y) | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_to_dict(file_json):
"""Create dictionary from json file."""
with open(file_json) as infile:
mydict = json.load(infile)
return mydict | bigcode/self-oss-instruct-sc2-concepts |
import click
def get_help_msg(command):
"""get help message for a Click command"""
with click.Context(command) as ctx:
return command.get_help(ctx) | bigcode/self-oss-instruct-sc2-concepts |
def flatten_bands(bands):
"""
Flatten the bands such that they have dimension 2.
"""
flattened_bands = bands.clone()
bands_array = bands.get_bands()
flattened_bands.set_bands(bands_array.reshape(bands_array.shape[-2:]))
return flattened_bands | bigcode/self-oss-instruct-sc2-concepts |
def check_same_keys(d1, d2):
"""Check if dictionaries have same keys or not.
Args:
d1: The first dict.
d2: The second dict.
Raises:
ValueError if both keys do not match.
"""
if d1.keys() == d2.keys():
return True
raise ValueError("Keys for both the dictionaries should be the same.") | bigcode/self-oss-instruct-sc2-concepts |
import re
def _MarkOptional(usage):
"""Returns usage enclosed in [...] if it hasn't already been enclosed."""
# If the leading bracket matches the trailing bracket its already marked.
if re.match(r'^\[[^][]*(\[[^][]*\])*[^][]*\]$', usage):
return usage
return '[{}]'.format(usage) | bigcode/self-oss-instruct-sc2-concepts |
def keep_type(adata, nodes, target, k_cluster):
"""Select cells of targeted type
Args:
adata (Anndata): Anndata object.
nodes (list): Indexes for cells
target (str): Cluster name.
k_cluster (str): Cluster key in adata.obs dataframe
Returns:
list: Selected cells.
"""
return nodes[adata.obs[k_cluster][nodes].values == target] | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def ticks_from_datetime(dt: datetime):
"""Convert datetime to .Net ticks"""
if type(dt) is not datetime:
raise TypeError('dt must be a datetime object')
return (dt - datetime(1, 1, 1)).total_seconds() * 10000000 | bigcode/self-oss-instruct-sc2-concepts |
import toml
def toml_files(tmp_path):
"""Generate TOML config files for testing."""
def gen_toml_files(files={'test.toml': {'sec': {'key': 'val'}}}):
f_path = None
for name, config in files.items():
f_path = tmp_path / name
with open(f_path, 'w') as f:
toml.dump(config, f)
if len(files) == 1:
return f_path
return tmp_path
return gen_toml_files | bigcode/self-oss-instruct-sc2-concepts |
import csv
def readCSV(filename):
"""
Reads the .data file and creates a list of the rows
Input
filename - string - filename of the input data file
Output
data - list containing all rows of the csv as elements
"""
data = []
with open(filename, 'rt', encoding='utf8') as csvfile:
lines = csv.reader(csvfile)
for row in lines:
data.append(row)
return data | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_phone_number(text,format=1):
"""
Checks if the given text is a phone number
* The phone must be for default in format (000)0000000, but it can be changed
Args:
text (str): The text to match
(optional) format (int): The number of the phone format that you want to check, default 1 (see below the formats)
Returns:
A boolean value, True if the text is a phone number in the specified format or False if not
Raises:
TypeError: If not text given
KeyError: If the given format doesn't exists or is different that an integer
Formats (# can be any 0-9 number):
0: ##########
1: (###)#######
2: (###)-###-####
3: (###) ### ####
4: ###-###-####
5: ### ### ####
6: (###)###-####
7: (###)### ####
"""
formats = {
0: r'^\d{10}$',
1: r'^\(\d{3}\)\d{7}$',
2: r'^\(\d{3}\)-\d{3}-\d{4}$',
3: r'^\(\d{3}\) \d{3} \d{4}$',
4: r'^\d{3}-\d{3}-\d{4}$',
5: r'^\d{3} \d{3} \d{4}$',
6: r'^\(\d{3}\)\d{3}-\d{4}$',
7: r'^\(\d{3}\)\d{3} \d{4}$',
}
return True if re.match(formats[format],text.strip()) else False | bigcode/self-oss-instruct-sc2-concepts |
def hamming_weight(x):
"""
Per stackoverflow.com/questions/407587/python-set-bits-count-popcount
It is succint and describes exactly what we are doing.
"""
return bin(x).count('1') | bigcode/self-oss-instruct-sc2-concepts |
def _is_pronoun (mention) :
"""Check if a mention is pronoun"""
components=mention.split()
if components[1]=="PRON" :
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def swap_clips(from_clip, to_clip, to_clip_name, to_in_frame, to_out_frame):
"""
Swaping clips on timeline in timelineItem
It will add take and activate it to the frame range which is inputted
Args:
from_clip (resolve.mediaPoolItem)
to_clip (resolve.mediaPoolItem)
to_clip_name (str): name of to_clip
to_in_frame (float): cut in frame, usually `GetLeftOffset()`
to_out_frame (float): cut out frame, usually left offset plus duration
Returns:
bool: True if successfully replaced
"""
# add clip item as take to timeline
take = from_clip.AddTake(
to_clip,
float(to_in_frame),
float(to_out_frame)
)
if not take:
return False
for take_index in range(1, (int(from_clip.GetTakesCount()) + 1)):
take_item = from_clip.GetTakeByIndex(take_index)
take_mp_item = take_item["mediaPoolItem"]
if to_clip_name in take_mp_item.GetName():
from_clip.SelectTakeByIndex(take_index)
from_clip.FinalizeTake()
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def _price_dish(dish):
"""
Computes the final price for ordering the given dish, taking into account the requested
quantity and options.
Args:
dish (dict): KB entry for a dish, augmented with quantity and options information.
Returns:
float: Total price for ordering the requested quantity of this dish with options included.
"""
total_price = dish['price']
if 'options' in dish:
total_price += sum([option.get('price', 0) for option in dish['options']])
return total_price * dish['quantity'] | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def get_character_names(characters, verbose=False):
"""Print the unicode name of a list/set/string of characters.
Args:
characters (list/set/string): a list, string or set of characters.
verbose (bool): if set to True, the output will be printed
Returns:
(dict): a dictionary of characters and their names.
Examples:
>>> char_dict = {"١": "ARABIC-INDIC DIGIT ONE",\
"٢": "ARABIC-INDIC DIGIT TWO"}
>>> char_dict == get_character_names("١٢")
True
>>> char_dict == get_character_names(["١", "٢"])
True
>>> char_dict == get_character_names({"١", "٢"})
True
"""
char_dict = dict()
for c in sorted(list(characters)):
try:
name = unicodedata.name(c)
except:
name = None
char_dict[c] = name
if verbose:
print("{}\t{}".format(c, name))
return char_dict | bigcode/self-oss-instruct-sc2-concepts |
import time
def parse_time(epoch_time):
"""Convert epoch time in milliseconds to [year, month, day, hour, minute, second]"""
date = time.strftime('%Y-%m-%d-%H-%M-%S', time.gmtime(epoch_time/1000))
return [int(i) for i in date.split('-')] | bigcode/self-oss-instruct-sc2-concepts |
import typing
import math
def isanan(value: typing.Any) -> bool:
"""Detect if value is NaN."""
return isinstance(value, float) and math.isnan(value) | bigcode/self-oss-instruct-sc2-concepts |
def fix_public_key(str_key):
"""eBay public keys are delivered in the format:
-----BEGIN PUBLIC KEY-----key-----END PUBLIC KEY-----
which is missing critical newlines around the key for ecdsa to
process it.
This adds those newlines and converts to bytes.
"""
return (
str_key
.replace('KEY-----', 'KEY-----\n')
.replace('-----END', '\n-----END')
.encode('utf-8')
) | bigcode/self-oss-instruct-sc2-concepts |
def _error_string(error, k=None):
"""String representation of SBMLError.
Parameters
----------
error : libsbml.SBMLError
k : index of error
Returns
-------
string representation of error
"""
package = error.getPackage()
if package == "":
package = "core"
template = "E{} ({}): {} ({}, L{}); {}; {}"
error_str = template.format(
k,
error.getSeverityAsString(),
error.getCategoryAsString(),
package,
error.getLine(),
error.getShortMessage(),
error.getMessage(),
)
return error_str | bigcode/self-oss-instruct-sc2-concepts |
def powmod(x, k, MOD):
""" fast exponentiation x^k % MOD """
p = 1
if k == 0:
return p
if k == 1:
return x
while k != 0:
if k % 2 == 1:
p = (p * x) % MOD
x = (x * x) % MOD
k //= 2
return p | bigcode/self-oss-instruct-sc2-concepts |
def remove_trail_idx(param):
"""Remove the trailing integer from a parameter."""
return "_".join(param.split("_")[:-1]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_qdyn_compiler(configure_log):
"""Return the name the Fortran compiler that QDYN was compiled with"""
with open(configure_log) as in_fh:
for line in in_fh:
if line.startswith("FC"):
m = re.search(r'FC\s*:\s*(.*)', line)
if m:
fc = m.group(1)
return fc
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_ipv4(ip):
"""Checks if the ip address is a valid ipv4 address including CIDR mask."""
regex = r'^(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)$'
pattern = re.compile(regex)
return pattern.search(ip) is not None | bigcode/self-oss-instruct-sc2-concepts |
def get_categories_info(categories_id, doc):
"""Get object name from category id
"""
for cate_infor in doc['categories']:
if categories_id == cate_infor['id']:
return cate_infor['name']
return None | bigcode/self-oss-instruct-sc2-concepts |
def is_unique_corr(x):
"""Check that ``x`` has no duplicate elements.
Args:
x (list): elements to be compared.
Returns:
bool: True if ``x`` has duplicate elements, otherwise False
"""
return len(set(x)) == len(x) | bigcode/self-oss-instruct-sc2-concepts |
def getImageLink(url, img_url, caption):
"""
Converts a URL to a Markdown image link.
"""
return "[]({url})".format(
caption=caption,
img_url=img_url,
url=url
) | bigcode/self-oss-instruct-sc2-concepts |
def get_chars_from_guesses(guesses):
"""
gets characters from guesses (removes underscores), removes duplicates and sorts them in an array which is returned.
example guess: "__cr_"
"""
guesses_copy = guesses.copy()
guesses_copy = "".join(guesses_copy)
return sorted("".join(set(guesses_copy.replace("_", "")))) | bigcode/self-oss-instruct-sc2-concepts |
def computeAbsPercentageError(true, predicted):
"""
:param true: ground truth value
:param predicted: predicted value
:return: absolute percentage error
"""
return abs((true - predicted) / true) * 100 | bigcode/self-oss-instruct-sc2-concepts |
def lines(a, b):
"""Return lines in both a and b"""
l1 = a.splitlines()
l2 = b.splitlines()
s1 = set(l1)
s2 = set(l2)
l = [i for i in s1 if i in s2]
return l | bigcode/self-oss-instruct-sc2-concepts |
def check_campus(department_name, department_dict, val):
"""
Returns the campus/college the given 'department_name' is in
depending on the value of the 'val' parameter
@params
'department_name': The full name of the department to search for
'department_dict': The dictionary of department information to search through
'val': Can either be 'Campus' or 'College', used to determine which value
to return
Returns
The campus or college the given 'department_name' is in
"""
# for [c] -> campus, [college] -> Colleges in Campus
for c, college in department_dict.items():
for col_name, deps in college.items():
for dep_a, dep_f in deps.items():
if val == 'Campus':
if dep_f == department_name:
return c
elif val == 'College':
if dep_f == department_name or dep_a == department_name:
return col_name | 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.