seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _key_in_string(string, string_formatting_dict):
"""Checks which formatting keys are present in a given string"""
key_in_string = False
if isinstance(string, str):
for key, value in string_formatting_dict.items():
if "{" + key + "}" in string:
key_in_string = True
return key_in_string | bigcode/self-oss-instruct-sc2-concepts |
def compare_two_model_index(index_1, index_2):
"""
If the two input index's row and column and their parent is equal, then they are equal for test.
"""
return (index_1.row() == index_2.row()) \
and (index_1.column() == index_2.column()) \
and (index_1.parent() == index_2.parent()) | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_json_from_file_path(path):
"""
Get the content of the json file and convert it into an object
"""
f = None
result = None
# noinspection PyBroadException
try:
f = open(path, "r", encoding="utf-8")
json_str = f.read().strip()
result = json.loads(json_str)
except Exception as e:
raise e
finally:
if f:
f.close()
return result | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def connect(
graph: List[List[int]], next_ver: int, current_ind: int, path: List[int]
) -> bool:
"""
Memeriksa apakah mungkin untuk menambahkan
berikutnya ke jalur dengan memvalidasi 2 pernyataan
1. Harus ada jalan antara titik saat ini dan berikutnya
2. Vertex berikutnya tidak boleh berada di jalur
Jika kedua validasi berhasil,return True
>>> graph = [[0, 1, 0, 1, 0],
... [1, 0, 1, 1, 1],
... [0, 1, 0, 0, 1],
... [1, 1, 0, 0, 1],
... [0, 1, 1, 1, 0]]
>>> path = [0, -1, -1, -1, -1, 0]
>>> curr_ind = 1
>>> next_ver = 1
>>> connect(graph, next_ver, curr_ind, path)
True
sama graph tapi coba connect ke node yang sudah ada di jalur
>>> path = [0, 1, 2, 4, -1, 0]
>>> curr_ind = 4
>>> next_ver = 1
>>> connect(graph, next_ver, curr_ind, path)
False
"""
if graph[path[current_ind - 1]][next_ver] == 0:
return False
return not any(vertex == next_ver for vertex in path) | bigcode/self-oss-instruct-sc2-concepts |
def addr_alignment(addr):
"""Compute the maximum alignment of a specified address, up to 4."""
return addr & 1 or addr & 2 or 4 | bigcode/self-oss-instruct-sc2-concepts |
def get_entry_ids(entry):
"""Creates a trakt ids dict from id fields on an entry. Prefers already populated info over lazy lookups."""
ids = {}
for lazy in [False, True]:
if entry.get('trakt_movie_id', eval_lazy=lazy):
ids['trakt'] = entry['trakt_movie_id']
elif entry.get('trakt_show_id', eval_lazy=lazy):
ids['trakt'] = entry['trakt_show_id']
elif entry.get('trakt_episode_id', eval_lazy=lazy):
ids['trakt'] = entry['trakt_episode_id']
if entry.get('tmdb_id', eval_lazy=lazy):
ids['tmdb'] = entry['tmdb_id']
if entry.get('tvdb_id', eval_lazy=lazy):
ids['tvdb'] = entry['tvdb_id']
if entry.get('imdb_id', eval_lazy=lazy):
ids['imdb'] = entry['imdb_id']
if entry.get('tvrage_id', eval_lazy=lazy):
ids['tvrage'] = entry['tvrage_id']
if ids:
break
return ids | bigcode/self-oss-instruct-sc2-concepts |
def add(number_x: int, number_y: int):
"""Adds two numbers."""
return number_x + number_y | bigcode/self-oss-instruct-sc2-concepts |
def get_instances_for_service(service_id: str, client) -> list:
""" Returns list of registered instance for service with id <service_id>"""
return client.list_instances(ServiceId=service_id).get('Instances', []) | bigcode/self-oss-instruct-sc2-concepts |
def check_insertion_order(metadict_inst, expected):
"""
Ensure that the keys of `metadict_inst` are in the same order as the keys
in `expected`.
The keys case is ignored.
"""
def normalise_keys(lst_pairs):
return [key.lower() for key, _ in lst_pairs]
assert normalise_keys(metadict_inst.items()) == normalise_keys(expected) | bigcode/self-oss-instruct-sc2-concepts |
def diagonal(matrix, reverse=False):
""" Return matrix' diagonal (count from the the back if reverse = True). """
diag = 0
if not reverse:
for i in range(len(matrix)):
diag += matrix[i][i]
else:
for i in range(len(matrix)):
diag += matrix[i][(len(matrix) - 1) - i]
return diag | bigcode/self-oss-instruct-sc2-concepts |
def flatten_whois(whois_record):
"""
Flattens a whois record result
Args:
whois_record (dict): A WHOIS record
Returns:
dict: A flattened WHOIS result
"""
flat_whois = dict()
flat_whois["domainName"] = whois_record["domainName"]
if "createdDate" in whois_record:
flat_whois["createdDate"] = whois_record["createdDate"]
if "updatedDate" in whois_record:
flat_whois["updatedDate"] = whois_record["updatedDate"]
if "expiresDate" in whois_record:
flat_whois["expiresDate"] = whois_record["expiresDate"]
if "registrant" in whois_record:
for key in whois_record["registrant"]:
flat_whois["registrant_{0}".format(key)] = whois_record["registrant"][key]
del flat_whois["registrant_rawText"]
if "administrativeContact" in whois_record:
for key in whois_record["administrativeContact"]:
flat_whois["administrativeContact_{0}".format(key)] = whois_record["administrativeContact"][key]
del flat_whois["administrativeContact_rawText"]
if "technicalContact" in whois_record:
for key in whois_record["technicalContact"]:
flat_whois["technicalContact_{0}".format(key)] = whois_record["technicalContact"][key]
del flat_whois["technicalContact_rawText"]
if "nameServers" in whois_record:
flat_whois["nameServers"] = "|".join(whois_record["nameServers"]["hostNames"])
if "status" in whois_record:
flat_whois["status"] = whois_record["status"]
if "registrarName" in whois_record:
flat_whois["registrarName"] = whois_record["registrarName"]
if "estimatedDomainAge" in whois_record:
flat_whois["estimatedDomainAge"] = whois_record["estimatedDomainAge"]
if "ips" in whois_record:
flat_whois["ips"] = "|".join(whois_record["ips"])
return flat_whois | bigcode/self-oss-instruct-sc2-concepts |
def rc_prescription_from_pm_and_imc(efl, f_pm, pm_vertex_to_focus):
"""Design a Ritchey-Chrétien telescope from information about its primary mirror.
Parameters
----------
efl : float
system effective focal length
f_pm : float
focal length of the primary mirror (should be negative)
pm_vertex_to_focus : float
the distance from the primary mirror vertex to the focus
remember that the pm has nonzero thickness
Returns
-------
float, float, float, float
c1, c2, k1, k2
"""
b = pm_vertex_to_focus
F = efl
D = f_pm * (F-b)
B = D + b
M = (F-B)/D # secondary mirror magnification
R1 = -(2*D*F)/(F-B)
R2 = -(2*D*B)/(F-B-D)
k1 = -1 - 2/M**3 * B/D
k2 = -1 - 2/(M-1)**3 * (M*(2*M-1) + B/D)
c1 = 1/R1
c2 = 1/R2
return c1, c2, k1, k2 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
import csv
def _preprocess_csv(file_path: Union[str, Path], delimiter: str):
"""Validates a CSV file and returns the data as a list of lists"""
if isinstance(file_path, str):
file_path = Path(file_path)
if not file_path.exists():
raise ValueError("File not found")
with open(file_path, "r", encoding="utf-8") as file:
reader = csv.reader(file, delimiter=delimiter)
csv_data = list(reader)
if not csv_data:
raise ValueError("File is empty")
return csv_data | bigcode/self-oss-instruct-sc2-concepts |
def remove_comment(line):
"""
与えられた文字列の"::"以降(右)を除去する
Args:
line: コメントを取り除きたい文字列
Return:
先頭がコメントだった場合(コメントのみの行だった場合): 空文字
それ以外: コメント部分を取り除いた文字列
"""
return "" if line.index("::") == 0 else line.split("::")[0] | bigcode/self-oss-instruct-sc2-concepts |
def _getitem_from_frame(f_locals, key, default=None):
"""
f_locals is not guaranteed to have .get(), but it will always
support __getitem__. Even if it doesnt, we return ``default``.
"""
try:
return f_locals[key]
except Exception:
return default | bigcode/self-oss-instruct-sc2-concepts |
def get_edges(graph: dict) -> set:
"""
Return a set of couples that represents all of the edges.
@input: graph (graph stored in an adjacency list where each vertex is
represented as an integer)
@example:
>>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]}
>>> get_edges(graph)
{(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)}
"""
edges = set()
for from_node, to_nodes in graph.items():
for to_node in to_nodes:
edges.add((from_node, to_node))
return edges | bigcode/self-oss-instruct-sc2-concepts |
import random
def SampleNegativeEdges(graph, num_edges):
"""Samples `num_edges` edges from compliment of `graph`."""
random_negatives = set()
nodes = list(graph.nodes())
while len(random_negatives) < num_edges:
i1 = random.randint(0, len(nodes) - 1)
i2 = random.randint(0, len(nodes) - 1)
if i1 == i2:
continue
if i1 > i2:
i1, i2 = i2, i1
n1 = nodes[i1]
n2 = nodes[i2]
if graph.has_edge(n1, n2):
continue
random_negatives.add((n1, n2))
return random_negatives | bigcode/self-oss-instruct-sc2-concepts |
def split_train_test(data, test_data_size: int):
"""Splits data into train and test.
Args:
data: All data.
test_data_size: Size of the `test` data.
Size of the `train` will be `len(data) - test_data_size`.
"""
train_data = data[:-test_data_size]
test_data = data[-test_data_size:]
return train_data, test_data | bigcode/self-oss-instruct-sc2-concepts |
def _is_dictionary(arg):
"""Check if argument is an dictionary (or 'object' in JS)."""
return isinstance(arg, dict) | bigcode/self-oss-instruct-sc2-concepts |
def _weight(entry):
"""
Sum a power of frequency.
Word frequencies have a skew with a long tail toward infrequent.
"""
weight = 500 * entry[0] ** 0.25
for i in range(3, len(entry), 2):
weight -= (entry[i] / 100.0) ** 4 * 100
return weight | bigcode/self-oss-instruct-sc2-concepts |
def split_nums_chars(str_: str) -> tuple[str, str]:
"""Splits the numbers and characters from a string
Args:
str_: The string to split
Returns:
A tuple containing the characters and the numbers
"""
nums = "".join([i for i in str_ if i.isnumeric()])
chars = "".join([i for i in str_ if i.isalpha()])
return chars, nums | bigcode/self-oss-instruct-sc2-concepts |
def capitalize(text: str) -> str:
"""
Capitalize the first letter only.
>>> capitalize("")
''
>>> capitalize("alice")
'Alice'
>>> capitalize("BOB")
'BOB'
>>> capitalize("alice and bob")
'Alice and bob'
"""
if not text:
return ""
return f"{text[0].capitalize()}{text[1:]}" | bigcode/self-oss-instruct-sc2-concepts |
def TestSuiteName(test_key):
"""Returns the test suite name for a given TestMetadata key."""
assert test_key.kind() == 'TestMetadata'
parts = test_key.id().split('/')
return parts[2] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import pickle
def deserialize(input_file: str) -> Any:
"""
Load data stored by ``serialize()``.
:param input_file: path to file when data was stored by serialize()
:return: list of objects
"""
with open(input_file, "rb") as f:
return pickle.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def _make_compound_key(table, key):
"""Returns a list of columns from `column_key` for `table` representing
potentially a compound key. The `column_key` can be a name of a single
column or list of column names."""
if not isinstance(key, (list, tuple)):
key = [key]
return [table.columns[name] for name in key] | bigcode/self-oss-instruct-sc2-concepts |
def get_region(regions, cluster):
""" Gets the region name from the cluster ID
Args:
regions (dictionary): dictionary of regions where shortname is the key to the long name value.
cluster (str): the OCI ID of the cluster in question.
Returns a string of the region long name.
"""
region_short_name = cluster.split('.')[3]
return regions[region_short_name] | bigcode/self-oss-instruct-sc2-concepts |
def convert_lanes_to_edges(lanes):
"""
Convert lanes (iterable) to edges (iterable).
Remove lane index from the end and then remove duplicates while retaining order.
Also works with single lane str.
>>> lanes
>>> ['1175109_0', '1175109_1', '1175109_2', '1183934_0', '1183934_1', '1183934_2']
>>> convert_lanes_to_edges(lanes)
>>> ['1175109', '1183934']
"""
if isinstance(lanes, str):
return lanes.rsplit('_', 1)[0]
return list(dict.fromkeys(map(lambda x: x.rsplit('_', 1)[0], lanes))) | bigcode/self-oss-instruct-sc2-concepts |
def load_blob(reader):
"""Given a reader object, such as returned by ExtBoar.get_blob(),
fetches all the blocks and returns the reconstructed
data. Warning: this means the whole blob will be loaded into
RAM."""
return "".join(reader) | bigcode/self-oss-instruct-sc2-concepts |
def window_landmark(region, flank_upstream=50, flank_downstream=50, ref_delta=0, landmark=0):
"""Define a window surrounding a landmark in a region, if the region has such a landmark,
(e.g. a start codon in a transcript), accounting for splicing of the region,
if the region is discontinuous
Parameters
----------
transcript : |SegmentChain| or |Transcript|
Region on which to generate a window surrounding a landmark
landmark : int
Position of the landmark within `region`
flank_upstream : int
Nucleotides upstream of `landmark` to include in window
flank_downstream : int
Nucleotides downstream of `landmark` to include in window
ref_delta : int
Offset from `landmark` to the reference point. If 0, the landmark
is the reference point. Default: 0
Returns
-------
|SegmentChain|
Window of `region` surrounding landmark
int
alignment offset to the window start, if `region` itself wasn't long
enough in the 5' direction to include the entire distance specified by
`flank_upstream`. Use this to align windows generated around similar
landmarks from different `regions` (e.g. windows surrounding start codons
in various transcripts).
(str, int, str)
Genomic coordinate of reference point as *(chromosome name, coordinate, strand)*
"""
if landmark + ref_delta >= flank_upstream:
fiveprime_offset = 0
my_start = landmark + ref_delta - flank_upstream
else:
fiveprime_offset = flank_upstream - landmark
my_start = 0
my_end = min(region.length, landmark + ref_delta + flank_downstream)
roi = region.get_subchain(my_start, my_end)
span = region.spanning_segment
chrom = span.chrom
strand = span.strand
if landmark + ref_delta == region.length:
if span.strand == "+":
ref_point = (chrom, span.end, strand)
else:
ref_point = (chrom, span.start - 1, strand)
else:
ref_point = region.get_genomic_coordinate(landmark + ref_delta)
return roi, fiveprime_offset, ref_point | bigcode/self-oss-instruct-sc2-concepts |
def hex2rgb(hexstring):
""" convert #RRGGBB to an (R, G, B) tuple """
hexstring = hexstring.strip()
if hexstring[0] == '#': hexstring = hexstring[1:]
if len(hexstring) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % hexstring)
r, g, b = hexstring[:2], hexstring[2:4], hexstring[4:]
r, g, b = [int(n, 16) for n in (r, g, b)]
return r / 255, g / 255, b / 255 | bigcode/self-oss-instruct-sc2-concepts |
def error(msg, value=None) -> str:
"""Formats msg as the message for an argument that failed to parse."""
if value is None:
return '<[{}]>'.format(msg)
return '<[{} ({})]>'.format(msg, value) | bigcode/self-oss-instruct-sc2-concepts |
def get_python_module_names(file_list, file_suffix='.py'):
""" Return a list of module names from a filename list. """
module_names = [m[:m.rfind(file_suffix)] for m in file_list
if m.endswith(file_suffix)]
return module_names | bigcode/self-oss-instruct-sc2-concepts |
def _symplectic_euler_step(state, force, dt):
"""Compute one step of the symplectic euler approximation.
Parameters
----------
state : array-like, shape=[2, dim]
variables a time t
force : callable
dt : float
time-step
Returns
-------
point_new : array-like, shape=[dim]
first variable at time t + dt
vector_new : array-like, shape=[dim]
second variable at time t + dt
"""
point, vector = state
point_new = point + vector * dt
vector_new = vector + force(point, vector) * dt
return point_new, vector_new | bigcode/self-oss-instruct-sc2-concepts |
def early_stop(patience, max_factor, vae_loss_val, em_loss_val):
"""
Manual implementation of https://keras.io/api/callbacks/early_stopping/.
:param patience: max number of epochs loss has not decreased
:param max_factor: max_factor * current loss is the max acceptable loss
:param vae_loss_val: list of vae validation losses
:param em_loss_val: list of emulator validation losses
:return: boolean, True (keep going) or False (stop early)
"""
if not len(em_loss_val) > patience: # there is not enough training to compare
return True
if vae_loss_val is not None:
vae_max_loss = vae_loss_val[-(1 + patience)] * max_factor # the max acceptable loss
else:
vae_max_loss = None
em_max_loss = em_loss_val[-(1 + patience)] * max_factor # the max acceptable loss
count = 0
while count < patience:
if em_loss_val[-(1 + count)] > em_max_loss:
if vae_loss_val is None:
count += 1
continue
elif vae_loss_val[-(1 + count)] > vae_max_loss:
count += 1
continue
else:
break
else:
break
if count == patience: # the last [patience] losses are all too large: stop training
print("Early stopping!")
return False # keep_going = False, i.e. stop early
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def combinations(n, k):
"""
Given two integers n and k, return all possible combinations of k numbers
out of 1 2 3 ... n.
n = 4
k = 2
[
[1,2],
[1,3],
[1,4],
[2,3],
[2,4],
[3,4],
]
"""
def find_combination(combination, nums):
if len(combination) >= k:
yield combination
return
for i, n in enumerate(nums):
for c in find_combination(combination + [n], nums[i+1:]):
yield c
return list(find_combination([], range(1, n + 1))) | bigcode/self-oss-instruct-sc2-concepts |
import re
def humansort(l):
"""Sort in place a given list the way humans expect.
NB: input list is modified
E.g. ['file11', 'file1'] -> ['file1', 'file11']
"""
def alphanum_key(s):
# Turn a string into a list of string and number chunks.
# e.g. "z23a" -> ["z", 23, "a"]
def tryint(s):
if s.isdigit():
return int(s)
return s
return [tryint(c) for c in re.split("([0-9]+)", s)]
l.sort(key=alphanum_key)
return l | bigcode/self-oss-instruct-sc2-concepts |
def fix_ecm_move_conflicts(conflict_ecm_list, move_order_text):
"""Get user input to sort out ECMs moved in both directions
It is possible that with a given set of active and inactive
ECMs and some sets of keywords given by the user to move ECMs
in bulk from one list to the other, there will be cases where
one or more ECMs moved from one list to the other would be
moved back by the keyword(s) directing the move in the other
direction.
This function takes those ECMs and asks the user whether, for
each ECM, they would like to continue the move as indicated
by the keyword(s) they gave for the move in the direction
indicated by 'move_order_text' or if they would like to leave
the ECM on its original list.
Args:
conflict_ecm_list (list): A list of ECM names corresponding
to the ECMs that are moved in both directions by the
keywords given by the user
move order text (str): A string indicating the original
intended direction to move the ECMs indicated in
'conflict_ecm_list'
Returns:
A list of the ECM names that should stay on the list
where they started (i.e., if they started out as active
ECMs, they should remain active).
If no ECMs are selected, an empty list is returned.
"""
# Inform the user that there are overlapping terms present
print('\nThe following ECMs, when using your specified search terms '
'would not be moved because the terms used for each direction '
'conflict for these ECMs. The ECMs listed below were selected '
'to move from', move_order_text + '.\n')
# Print each ECM with a corresponding number
for idx, entry in enumerate(conflict_ecm_list):
print(idx+1, '-', entry)
# Construct string to print for the input field
instruct_str = ('\nFrom the list, indicate which ECMs you would '
'still like to have moved from ' + move_order_text +
' by entering their corresponding number(s), if '
'any, separated by commas: ')
# Prompt the user to specify the desired outcome for each conflicting move
selections = input(instruct_str)
# Convert user input into a list of integers corresponding to the
# list entries for the ECMs to move, and handle cases where the
# user provides non-numeric text to the input
while True:
# Convert the user input into a list of integers with
# no extraneous trailing or leading spaces
try:
move_ecm_numbers = [int(x.strip())
for x in selections.split(',') if x.strip()]
# Handle the exception if a non-integer entry is passed
# to the input by requesting the user attempt to enter
# their desired entries from the list again
except ValueError:
input('An invalid non-numeric entry was given. '
'Please try again: ')
# When a valid input is received, interrupt the loop
else:
break
# Check that values aren't out of range and prompt the user for
# the list of desired entries until only valid entries are given
if move_ecm_numbers:
while max(move_ecm_numbers) > len(conflict_ecm_list):
selections = input('An out of range number was given. '
'Please try again: ')
move_ecm_numbers = [int(x.strip())
for x in selections.split(',') if x.strip()]
# Create a list of all of the ECMs that are going to be kept
# in place/not moved
keep_in_place = [conflict_ecm_list[i-1]
for i in range(1, len(conflict_ecm_list)+1)
if i not in move_ecm_numbers]
return keep_in_place | bigcode/self-oss-instruct-sc2-concepts |
def extract_value_other_gdf(x,gdf,col_name):
"""
Function to extract value from column from other GeoDataFrame
Arguments:
*x* : row of main GeoDataFrame.
*gdf* : geopandas GeoDataFrame from which we want to extract values.
*col_name* : the column name from which we want to get the value.
"""
try:
return gdf.loc[list(gdf.sindex.intersection(x.geometry.bounds))][col_name].values[0]
except:
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_dimensions6(o_dim, ri_dim):
""" Get the orientation, real/imag, height and width dimensions
for the full tensor (6 dimensions)."""
# Calculate which dimension to put the real and imaginary parts and the
# orientations. Also work out where the rows and columns in the original
# image were
o_dim = (o_dim % 6)
ri_dim = (ri_dim % 6)
if ri_dim < o_dim:
o_dim -= 1
if o_dim >= 3 and ri_dim >= 3:
h_dim = 2
elif o_dim >= 4 or ri_dim >= 4:
h_dim = 3
else:
h_dim = 4
if o_dim >= 4 and ri_dim >= 4:
w_dim = 3
elif o_dim >= 4 or ri_dim >= 4:
w_dim = 4
else:
w_dim = 5
return o_dim, ri_dim, h_dim, w_dim | bigcode/self-oss-instruct-sc2-concepts |
import torch
def voxel_box_decode(box_encodings, anchors):
"""
box decode for pillar-net in lidar
:param box_encodings: [N, 7] Tensor, normal boxes: x, y, z, w, l, h, r
:param anchors: [N, 7] Tensor, anchors
:param encode_angle_to_vector: whether encoding angle to vector
:param smooth_dim: whether using smooth dim
:return: decoded boxes
"""
box_ndim = anchors.shape[-1]
cas, cts = [], []
if box_ndim > 7:
xa, ya, za, la, wa, ha, ra, *cas = torch.split(anchors, 1, dim=-1)
xt, yt, zt, lt, wt, ht, rt, *cts = torch.split(box_encodings, 1, dim=-1)
else:
xa, ya, za, la, wa, ha, ra = torch.split(anchors, 1, dim=-1)
xt, yt, zt, lt, wt, ht, rt = torch.split(box_encodings, 1, dim=-1)
diagonal = torch.sqrt(la ** 2 + wa ** 2)
xg = xt * diagonal + xa
yg = yt * diagonal + ya
zg = zt * ha + za
lg = torch.exp(lt) * la
wg = torch.exp(wt) * wa
hg = torch.exp(ht) * ha
rg = rt + ra
cgs = [t + a for t, a in zip(cts, cas)]
return torch.cat([xg, yg, zg, lg, wg, hg, rg, *cgs], dim=-1) | bigcode/self-oss-instruct-sc2-concepts |
def bboxes_to_pixels(bbox, im_width, im_height):
"""
Convert bounding box coordinates to pixels.
(It is common that bboxes are parametrized as percentage of image size
instead of pixels.)
Args:
bboxes (tuple): (xmin, xmax, ymin, ymax)
im_width (int): image width in pixels
im_height (int): image height in pixels
Returns:
bboxes (tuple): (xmin, xmax, ymin, ymax)
"""
xmin, xmax, ymin, ymax = bbox
return xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_file(f):
"""Finds the MD5 hash of a file.
File must be opened in bytes mode.
"""
h = hashlib.md5()
chunk_size = 65536 # 64 KiB
for chunk in iter(lambda: f.read(chunk_size), b''):
h.update(chunk)
return h.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def kev2ang(energy):
"""
Convert energy [keV] to wavelength [Å]
"""
wlen = 12.398/energy
return wlen | bigcode/self-oss-instruct-sc2-concepts |
def listify(x):
"""If x is already a list, do nothing. Otherwise, wrap x in a list."""
if isinstance(x, list):
return x
else:
return [x] | bigcode/self-oss-instruct-sc2-concepts |
def em_complete(job):
"""Verify that energy minimization has completed"""
return job.isfile('em.gro') | bigcode/self-oss-instruct-sc2-concepts |
def world_to_index(x, y, origin, resolution, width):
""" Convert World coordinates to index """
x = (x - origin[0]) / resolution
y = (y - origin[1]) / resolution
return y * width + x | bigcode/self-oss-instruct-sc2-concepts |
def wait_for_button_press(button):
"""
Wait for a button to be pressed and released.
Parameter:
- `button` (Button): an instance of the EV3 Button() class
return the Button name that was pressed.
"""
pressed = None
while True:
allpressed = button.buttons_pressed
if bool(allpressed):
pressed = allpressed[0] # just get the first one
while not button.wait_for_released(pressed):
pass
break
return pressed | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_field_content(s: str) -> bool:
"""
Returns True if string s can be stored in a SubStation field.
Fields are written in CSV-like manner, thus commas and/or newlines
are not acceptable in the string.
"""
return "\n" not in s and "," not in s | bigcode/self-oss-instruct-sc2-concepts |
import builtins
def is_a_builtin(word) -> bool:
"""
Returns True if a word is a builtin python object
Args:
word: word to check
Returns: True if word is builtin python object
"""
return str(word) in dir(builtins) | bigcode/self-oss-instruct-sc2-concepts |
def invalidate_cols(platemap, cols, valid=False):
"""Returns updated plate map with specified columns invalidated.
:param platemap: Plate map to use
:type platemap: pandas dataframe
:param wells: Columns to invalidate, e.g. [1, 2, 3]
:type wells: int or list of ints
:param valid: Sets the stipulated column or columns 'True' or 'False', default = False
:type valid: bool
:return: Returns updated plate map
:rtype: pandas dataframe
"""
if type(cols) == int: # convert cols to a list because cols must be an iterable object to allow for list comprehension
cols = [cols]
all_ids = list(platemap.index) # create a list of all well ids from platemap indexes
inval_ids = [item for item in all_ids if int(item[1:]) in cols] # list of well ids to be invalidated based on the columns from 'cols' parameter
platemap.loc[inval_ids, 'Valid'] = valid
return platemap | bigcode/self-oss-instruct-sc2-concepts |
import getpass
def get_current_user() -> str:
"""Return the name of the current user"""
return getpass.getuser() | bigcode/self-oss-instruct-sc2-concepts |
def increase_threshold(thresh, thresh_inc):
"""
Increase the threshold based on a string
Inputs: - thresh Initial threshold
- thresh_inc How the threshold should be increased.
"xN": multiply by N
"+N": increase by N
Output: - thresh Increased threshold
"""
if thresh_inc.startswith("x"):
return thresh * float(thresh_inc.split("x")[1])
elif thresh_inc.startswith("+"):
return thresh + float(thresh_inc.split("+")[1])
raise ValueError("Unkown threshold update: {}".format(thresh_inc)) | bigcode/self-oss-instruct-sc2-concepts |
import math
def hd(inc, sd):
"""
Calculate horizontal distance.
:param inc: (float) inclination angle in degrees
:param sd: (float) slope distance in any units
"""
return sd * math.cos(math.radians(inc)) | bigcode/self-oss-instruct-sc2-concepts |
def get_symbol_name(*args):
"""Return fully-qualified symbol name given path args.
Example usage:
>>> get_symbol_name('ZenPacks.example.Name')
'ZenPacks.example.Name'
>>> get_symbol_name('ZenPacks.example.Name', 'schema')
'ZenPacks.example.Name.schema'
>>> get_symbol_name('ZenPacks.example.Name', 'schema', 'APIC')
'ZenPacks.example.Name.schema.APIC'
>>> get_symbol_name('ZenPacks.example.Name', 'schema.Pool')
'ZenPacks.example.Name.schema.Pool'
No verification is done. Names for symbols that don't exist may
be returned.
"""
return '.'.join(x for x in args if x) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
import re
def solidity_unresolved_symbols(hex_code: str) -> Set[str]:
""" Return the unresolved symbols contained in the `hex_code`.
Note:
The binary representation should not be provided since this function
relies on the fact that the '_' is invalid in hex encoding.
Args:
hex_code (str): The bytecode encoded as hexadecimal.
"""
return set(re.findall(r"_.{39}", hex_code)) | bigcode/self-oss-instruct-sc2-concepts |
def remove_comment(content):
"""Remove comment from the content."""
lines = content.split('\n')
return '\n'.join([line for line in lines if not line.startswith('#')]).strip() | bigcode/self-oss-instruct-sc2-concepts |
def person(request):
"""
A dummy fixture, parametrized so that it has two instances
"""
if request.param == 0:
return "world"
elif request.param == 1:
return "self" | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_tag(tag, allow_none=False, mytype='string', default=None, max_len=254):
""" Clean the given `tag` instance depending of its `mytype`."""
if default is None and allow_none is False:
if mytype == 'string':
default = 'unknown'
elif mytype == 'integer':
default = 0
elif mytype == 'float':
default = 0.0
if tag is None or tag == 'None':
return default if allow_none is False else None
if mytype == 'string':
try:
tag = str(tag).strip()
except UnicodeDecodeError:
tag = tag.strip()
else:
tag = str(tag)
if tag == '':
return default
elif mytype == 'integer' and re.match(r'\d{1,32}', str(tag)) is None:
return default
elif mytype == 'float':
try:
return float(tag)
except ValueError:
return default
return tag[:max_len].strip() | bigcode/self-oss-instruct-sc2-concepts |
def calculate_square(num):
"""
Returns the square of a given number
"""
return num * num | bigcode/self-oss-instruct-sc2-concepts |
def fmt_color(text: str, color: str) -> str:
"""Format a string in a certain color (`<span>`).
Args:
text: The text to format.
color: Any valid CSS color.
Returns:
A `<span>` that contains the colored text.
"""
return u'<span style="color:{color}">{text}</span>'.format(
color=color, text=str(text)
) | bigcode/self-oss-instruct-sc2-concepts |
def RIGHT(text, n):
"""Slices string(s) a specified number of characters from right.
Parameters
----------
text : list or string
string(s) to be sliced from right.
n : integer
number of characters to slice from right. Must be greater than zero.
Returns
-------
list or string
A list of converted strings or converted string that were sliced n characters from right.
"""
if n > 0:
if type(text) == str:
return(text[-n:])
elif type(text) == list:
try:
text_return = [i[-n:] for i in text]
return(text_return)
except:
print('Invalid list: please enter a list of strings.')
else:
print('Invalid type: please enter a string or list of strings.')
else:
print('n must be greater than zero.') | bigcode/self-oss-instruct-sc2-concepts |
def _stringify_int(integer):
"""Convert an integer into a string formatted with thousand separators.
Parameters
----------
integer : int
The integer.
Returns
-------
str
The integer turned into a string.
"""
return "{:,}".format(integer) | bigcode/self-oss-instruct-sc2-concepts |
def calc_percent(per, cent):
"""Takes the parameters "per" and "cent"
and returns the calculated percent."""
return (per / cent) * 100 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from typing import List
from typing import Tuple
def edge_has_empty_node(
edge: Union[List[str], Tuple[str, str]], node_ids_with_labels
) -> bool:
"""Check if edge contains an empty node."""
return not str(node_ids_with_labels[edge[0]]) or not str(
node_ids_with_labels[edge[1]]
) | bigcode/self-oss-instruct-sc2-concepts |
def cli(ctx, state="", history_id="", invocation_id="", tool_id="", workflow_id="", user_id="", date_range_min="", date_range_max="", limit=500, offset=0, user_details=False):
"""Get all jobs, or select a subset by specifying optional arguments for filtering (e.g. a state).
Output:
Summary information for each selected job.
For example::
[{'create_time': '2014-03-01T16:16:48.640550',
'exit_code': 0,
'id': 'ebfb8f50c6abde6d',
'model_class': 'Job',
'state': 'ok',
'tool_id': 'fasta2tab',
'update_time': '2014-03-01T16:16:50.657399'},
{'create_time': '2014-03-01T16:05:34.851246',
'exit_code': 0,
'id': '1cd8e2f6b131e891',
'model_class': 'Job',
'state': 'ok',
'tool_id': 'upload1',
'update_time': '2014-03-01T16:05:39.558458'}]
.. note::
The following filtering options can only be used with Galaxy ``release_21.05`` or later:
user_id, limit, offset, workflow_id, invocation_id
"""
return ctx.gi.jobs.get_jobs(state=state, history_id=history_id, invocation_id=invocation_id, tool_id=tool_id, workflow_id=workflow_id, user_id=user_id, date_range_min=date_range_min, date_range_max=date_range_max, limit=limit, offset=offset, user_details=user_details) | bigcode/self-oss-instruct-sc2-concepts |
def build_table(x,
perceiver,
cache,
cache_emb,
topk,
return_images=False,
index_dir=None):
"""
Maps each image to a linearized row in a table. Each entry in a row
is delimited by "|". Each entry comes from the topk results in the cache
as determined by cosine similarity in CLIP space.
"""
table = []
x = perceiver.encode_image(x).float()
x /= x.norm(dim=-1, keepdim=True)
if index_dir:
indices = cache_emb.search(x.cpu().numpy(), topk)[1]
for idx in range(len(x)):
row = ''
results = [cache[i] for i in indices[idx]]
for r in results:
row += r + ' | '
table.append(row)
else:
#print(x.shape)
#print(cache_emb.shape)
ipt = 100.0 * x.float() @ cache_emb.T.float()
similarity = (ipt).softmax(dim=-1)
for idx in range(len(x)):
row = ''
values, indices = similarity[idx].topk(topk)
for _, index in zip(values, indices):
row += cache[index] + ' | '
table.append(row)
if return_images:
return table, x
return table | bigcode/self-oss-instruct-sc2-concepts |
def match_pattern(resource: bytes, pattern: bytes, mask: bytes, ignored: bytes):
"""
Implementation of algorithm in:x
https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern
True if pattern matches the resource. False otherwise.
"""
resource = bytearray(resource)
pattern = bytearray(pattern)
mask = bytearray(mask)
if len(pattern) != len(mask):
return False
if len(resource) < len(pattern):
return False
start = 0
for byte in resource:
if byte in ignored:
start += 1
else:
break
iteration_tuples = zip(resource[start:], pattern, mask)
for resource_byte, pattern_byte, mask_byte in iteration_tuples:
masked_byte = resource_byte & mask_byte
if masked_byte != pattern_byte:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
def mse(target, predicted):
"""Mean Squared Error"""
return torch.mean((target - predicted)**2) | bigcode/self-oss-instruct-sc2-concepts |
def min_scalar_type(a):
"""
min_scalar_type(a)
For scalar ``a``, returns the data type with the smallest size
and smallest scalar kind which can hold its value. For non-scalar
array ``a``, returns the vector's dtype unmodified.
Floating point values are not demoted to integers,
and complex values are not demoted to floats.
Parameters
----------
a : scalar or array_like
The value whose minimal data type is to be found.
Returns
-------
out : dtype
The minimal data type.
Notes
-----
.. versionadded:: 1.6.0
See Also
--------
result_type, promote_types, dtype, can_cast
Examples
--------
>>> np.min_scalar_type(10)
dtype('uint8')
>>> np.min_scalar_type(-260)
dtype('int16')
>>> np.min_scalar_type(3.1)
dtype('float16')
>>> np.min_scalar_type(1e50)
dtype('float64')
>>> np.min_scalar_type(np.arange(4,dtype='f8'))
dtype('float64')
"""
return (a,) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def force_list(value: Any) -> list:
"""
Convert `value` to list or return `value` if it is already a list.
:param value: Value to convert to list.
"""
return list(value) if isinstance(value, (list, tuple)) else [value] | bigcode/self-oss-instruct-sc2-concepts |
def get_frameshift_lengths(num_bins):
"""Simple function that returns the lengths for each frameshift category
if `num_bins` number of frameshift categories are requested.
"""
fs_len = []
i = 1
tmp_bins = 0
while(tmp_bins<num_bins):
if i%3:
fs_len.append(i)
tmp_bins += 1
i += 1
return fs_len | bigcode/self-oss-instruct-sc2-concepts |
def set_appliance_discovery_emails(
self,
email_list: list[str],
) -> bool:
"""Update email addresses configured to be notified for discovery of
new appliances.
.. warning::
Replaces the current configured list with the new list. To
add an email, first retrieve the current emails and pass all
desired emails in the new list.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - discovery
- POST
- /gms/discovery
:param email_list: List of email addresses to be notified for
appliance discovery
:type email_list: list[str]
:return: Returns True/False based on successful call
:rtype: bool
"""
data = {
"emails": email_list,
}
return self._post(
"/gms/discovery",
data=data,
expected_status=[204],
return_type="bool",
) | bigcode/self-oss-instruct-sc2-concepts |
def _check_not_none(value, name):
"""Checks that value is not None."""
if value is None:
raise ValueError(f"`{name}` must be specified.")
return value | bigcode/self-oss-instruct-sc2-concepts |
def fill_point(x, y, z, _):
"""
Returns a string defining a set of minecraft fill coordinates relative to the actor.
In minecraft, the y axis denotes the vertical (non-intuitively).
"""
return f'~{int(x)} ~{int(z)} ~{int(y)}' | bigcode/self-oss-instruct-sc2-concepts |
import operator
def advance_permutation(a, increasing=True, forward=True):
"""
Advance a list of unique, ordered elements in-place, lexicographically
increasing or backward, by rightmost or leftmost digit.
Returns False if the permutation wrapped around - i.e. went from
lexicographically greatest to least, and True in all other cases.
If the length of the list is N, then this function will repeat values after
N! steps, and will return False exactly once.
See also https://stackoverflow.com/a/34325140/43839
"""
if not forward:
a.reverse()
cmp = operator.lt if increasing else operator.gt
try:
i = next(i for i in reversed(range(len(a) - 1)) if cmp(a[i], a[i + 1]))
j = next(j for j in reversed(range(i + 1, len(a))) if cmp(a[i], a[j]))
except StopIteration:
# This is the lexicographically last permutation.
if forward:
a.reverse()
return False
a[i], a[j] = a[j], a[i]
a[i + 1:] = reversed(a[i + 1:])
if not forward:
a.reverse()
return True | bigcode/self-oss-instruct-sc2-concepts |
def prompt(msg):
"""Prompt the user for input."""
value = ""
while not value:
value = input(msg+" ").strip()
return value | bigcode/self-oss-instruct-sc2-concepts |
import math
def p_sequence(expected_value, days_a_week, upper_bound, step):
"""Calcualtes the capacity values to test."""
lower_p = math.ceil(days_a_week*expected_value/0.99)
# PSEQ per week, pseq per day
PSEQ = sorted(list(set([int(lower_p + step*i) for i in range(upper_bound)])))
pseq = [round(i/days_a_week, 2) for i in PSEQ]
return(pseq, PSEQ) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def jitter(X, ox, oy):
"""
Helper function to randomly jitter an image.
Inputs
- X: PyTorch Tensor of shape (N, C, H, W)
- ox, oy: Integers giving number of pixels to jitter along W and H axes
Returns: A new PyTorch Tensor of shape (N, C, H, W)
"""
if ox != 0:
left = X[:, :, :, :-ox]
right = X[:, :, :, -ox:]
X = torch.cat([right, left], dim=3)
if oy != 0:
top = X[:, :, :-oy]
bottom = X[:, :, -oy:]
X = torch.cat([bottom, top], dim=2)
return X | bigcode/self-oss-instruct-sc2-concepts |
import time
def add_timer(func_name):
"""Decorator to add timing to run commands
"""
def decorator(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
line_len = 88
print("")
print("=" * line_len)
print(f"{func_name} execution time: {end - start} seconds")
print("=" * line_len)
return wrapper
return decorator | bigcode/self-oss-instruct-sc2-concepts |
import re
def to_slug(value):
""" Convert a string to a URL slug. """
value = value.lower()
# Space to dashes
value = re.sub(r'[\s_]+', '-', value)
# Special characters
value = re.sub(r'[^a-z0-9\-]+', '', value, flags=re.I)
# Extra dashes
value = re.sub(r'\-{2,}', '-', value)
value = re.sub(r'(^\-)|(\-$)', '', value)
return value | bigcode/self-oss-instruct-sc2-concepts |
def get_digits_by_length(patterns, length):
"""Find all digits of a given length."""
return [pattern for pattern in patterns if len(pattern) == length] | bigcode/self-oss-instruct-sc2-concepts |
def calculate_fantasy_points(player) -> float:
"""
Calculate the fantasy points this player earned from the formula
Kill = 0.3
Death = -0.3
Assist = 0.15
Last Hit = 0.003
Gold per minute = 0.002
EXP per minute = 0.002
Seconds of enemy stuns = 0.07
Every 1000 allied healing done = 0.4
Tower Kill = 1
Roshan Kill = 1
First blood = 3
https://dota2.gamepedia.com/Fantasy_Dota
Parameters
----------
player: Summary - a player summary
Returns
-------
The fantasy points scored by this player
"""
return (
player["kills"]*0.3 - player["deaths"]*0.3 + player["assists"]*0.15 + player["last_hits"]*0.003
+ player["gpm"]*0.002 + player["xpm"]*0.002 + player["enemy_stun_time"]*0.07
+ (player["healing"]/1000)*0.4 + player["towers_killed"] + player["rosh_kills"]
+ (3 if player["first_blood"] else 0)
) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from functools import reduce
from operator import mul
def multiples_of(numbers: List[int]):
"""
Calculate the number of numbers multiples in the range being their product.
Eg for 3, 5 compute amount of 3 & 5 multiples in frame size 3 * 5
"""
frame_size = reduce(mul, numbers)
multiples = sum(any(i % num == 0 for num in numbers) for i in range(frame_size))
return multiples, frame_size, multiples / frame_size | bigcode/self-oss-instruct-sc2-concepts |
def positive_percent(df):
"""
compute the percentage of positive Tweets: 2 is positive
:param df: a tweet dataframe
:return: percentage of positive tweets
"""
assert 'sentiment_vader_percent' in df, "The pandas dataframe should contain the sentiment of each tweet"
positive = 0
for sentiment in list(df['sentiment_vader_percent']):
if int(float(sentiment)) == 2:
positive += 1
else:
pass
return positive / df.shape[0] | bigcode/self-oss-instruct-sc2-concepts |
def gcd(a, b):
"""
Find the greatest common divisor of two integers a, b.
This uses Euclid's algorithm. For integer a, b, it holds that
a * b = LCM(a, b) * GCD(a, b).
Starting from range(1, 21), we replace two head elements x, y to LCM(x, y).
"""
dividend = max(a, b)
divisor = min(a, b)
if divisor == 0:
return dividend
return gcd(dividend % divisor, divisor) | bigcode/self-oss-instruct-sc2-concepts |
def rot(c, n):
""" This function rotates a single character c forward by n spots in the alphabet. """
# check to ensure that c is a single character
assert(type(c) == str and len(c) == 1)
if 'a' <= c <= 'z':
new_ord = ord(c) + n
if new_ord > ord('z'):
new_ord = ord(c) + n - 26
elif 'A' <= c <= 'Z':
new_ord = ord(c) + n
if new_ord > ord('Z'):
new_ord = ord(c) + n - 26
else:
return c
return chr(new_ord) | bigcode/self-oss-instruct-sc2-concepts |
def format_headers(headers):
"""
Return a list of column names formatted as headers
:param headers:
:return list:
"""
new_headers = []
for h in headers:
h: str = h
if '_' in h:
h = h.replace('_', ' ')
# if 'id' in h:
# h = h.replace('id', '')
h = h.strip()
h = h.capitalize()
if h == 'Power output':
h = 'Power output (kW)'
elif h == 'Ship type':
h = 'Type'
elif h == 'Ship status':
h = 'Status'
elif h == 'Speed':
h = 'Speed (kn)'
new_headers.append(h)
return new_headers | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def build_content(csvdict):
"""
Construct a new dictionary that will be used to populate the template.
"""
yamlkeys = ['title', 'excerpt', 'tags', 'mentors', 'badge', 'level']
#yamlkeys = ['title', 'excerpt', 'tags']
yamldict = {}
content = csvdict.copy()
#sidekeys = ['mentors', 'badge', 'level']
for k in yamlkeys:
yamldict[k] = csvdict[k]
del content[k]
yml = yaml.dump(yamldict)
content['yaml'] = yml
return content | bigcode/self-oss-instruct-sc2-concepts |
def _kern_class(class_definition, coverage_glyphs):
"""Transpose a ttx classDef
{glyph_name: idx, glyph_name: idx} --> {idx: [glyph_name, glyph_name]}
Classdef 0 is not defined in the font. It is created by subtracting
the glyphs found in the lookup coverage against all the glyphs used to
define the other classes."""
classes = {}
seen_glyphs = set()
for glyph, idx in class_definition.items():
if idx not in classes:
classes[idx] = []
classes[idx].append(glyph)
seen_glyphs.add(glyph)
classes[0] = set(coverage_glyphs) - seen_glyphs
return classes | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Union
def normalize(
data: torch.Tensor,
mean: Union[float, torch.Tensor],
stddev: Union[float, torch.Tensor],
eps: Union[float, torch.Tensor] = 0.0,
) -> torch.Tensor:
"""
Normalize the given tensor.
Applies the formula (data - mean) / (stddev + eps).
Args:
data: Input data to be normalized.
mean: Mean value.
stddev: Standard deviation.
eps: Added to stddev to prevent dividing by zero.
Returns:
Normalized tensor.
"""
return (data - mean) / (stddev + eps) | bigcode/self-oss-instruct-sc2-concepts |
def get_xarray_subset( dataset, variable_name, time_step_indices, xy_slice_indices ):
"""
Returns a subset of the provided dataset. The source dataset is restricted to the
variable and indices supplied. When contiguous time step and XY slice indices are
supplied, the resulting DataArray is a view of the original.
Takes 4 arguments:
dataset - xarray.Dataset or xarray.DataArray object to return a view
from.
variable_name - Variable to restrict the view to.
time_step_indices - Time step values to restrict the view to.
xy_slice_indices - XY slice indices to restrict the view to.
Returns 1 value:
data_array - xarray.DataArray object representing a subset of dataset.
"""
# create a new DataArray from the indices provided.
#
# NOTE: we select time steps by value and XY slices by array index. XY
# slices are generated contiguously, so array index maps to the slice
# index for the vast majority (all?) of use cases. netCDF4 datasets
# may be constructed from multiple files selected via file name
# globbing, meaning time steps may not increase monotonically, meaning
# we should select time steps by value.
#
data_array = (dataset[variable_name]
.sel( Cycle=time_step_indices )
.isel( z=xy_slice_indices ))
return data_array | bigcode/self-oss-instruct-sc2-concepts |
def encrypt_letter(letter):
"""Encrypt a single letter
Arguments:
letter {char} -- The character to encrypt
Returns:
char -- The encrypted character
"""
inc_ord_char = ord(letter) + 3
if letter.isupper():
if inc_ord_char > 90:
inc_ord_char = inc_ord_char % 90 + 64
else:
if inc_ord_char > 122:
inc_ord_char = inc_ord_char % 122 + 96
return chr(inc_ord_char) | bigcode/self-oss-instruct-sc2-concepts |
def float_to_pcnt(x):
"""Convert a float to a percentage string, e.g. 0.4 -> '40%'."""
return '{}%'.format(round(x * 100)) | bigcode/self-oss-instruct-sc2-concepts |
def resolve_integer_or_float(*numbers):
"""Cast float values as integers if their fractional parts are close to
zero.
Parameters
----------
numbers : sequence
Number(s) to process.
Returns
-------
A number or list of numbers, appropriately transformed.
"""
if len(numbers) == 1:
number = numbers[0]
return int(number) if number % 1 < 1e-6 else round(number, 4)
else:
return [
int(number) if number % 1 < 1e-6 else round(number, 4)
for number in numbers
] | bigcode/self-oss-instruct-sc2-concepts |
def test_module(client):
"""
Returning 'ok' indicates that the integration works like it suppose to. Connection to the service is successful.
Args:
client: HelloWorld client
Returns:
'ok' if test passed, anything else will fail the test
"""
result = client.say_hello('DBot')
if 'Hello DBot' == result:
return 'ok'
else:
return 'Test failed because ......' | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def groupby_name(bindings, tier=0):
"""
Groups bindings by the name fragment specified by tier. Input bindings
can be not sorted. The order of the bindings remains initial in scope of
its group.
Yields:
(name, [binding(s)...]) tuples.
"""
res = OrderedDict()
for binding in bindings:
name_at_tier = binding.qualname[tier]
if name_at_tier in res:
res[name_at_tier].append(binding)
else:
res[name_at_tier] = [binding]
return res | bigcode/self-oss-instruct-sc2-concepts |
def get_location(datetime, position_df):
"""Create a tuple of the date_time, latitude and longitude of a location in a dataframe from a given date_time."""
latitude = position_df[position_df.date_time == datetime].latitude.item()
longitude = position_df[position_df.date_time == datetime].longitude.item()
location = (datetime, latitude, longitude)
return location | bigcode/self-oss-instruct-sc2-concepts |
import math
def gen_abd_params(N, f, dummy=None):
""" Generate possible values of n, q1, q2
"""
quorum_params = []
quorum_params_append = quorum_params.append
for n in range(2*f+1, N+1):
for q1 in range(math.ceil((N-1)/2), n-f+1):
for q2 in range(math.ceil((N-1)/2), n-f+1):
if q1+q2 > n:
quorum_params_append((n, q1, q2))
return quorum_params | bigcode/self-oss-instruct-sc2-concepts |
def is_close(a, b, rel_tol=1e-09, abs_tol=0):
"""Determines whether two numbers are nearly equal.
The maximum of the relative-based and absolute tolerances is used to test
equality.
This function is taken from `math.isclose` in Python 3 but is explicitly
implemented here for Python 2 compatibility.
Args:
a: a number
b: a number
rel_tol: a relative tolerance to use when testing equality. By default,
this is 1e-09
abs_tol: an absolute tolerance to use when testing equality. By
default, this is 0
Returns:
True/False whether the numbers are close
"""
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pickle_file(file_name, encoding='latin1'):
"""Loads a pickle file.
:param file_name: File name (extension included).
:type file_name: pathlib.Path
:param encoding: Encoding of the file.
:type encoding: str
:return: Loaded object.
:rtype: object | list | dict | numpy.ndarray
"""
with file_name.open('rb') as f:
return pickle.load(f, encoding=encoding) | 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.