seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_areas(objects):
"""
Get rounded area sizes (in m^2) of the geometries in given objects.
The results are rounded to two digits (dm^2 if the unit is metre)
and converted to string to allow easy comparison with equals.
"""
return {str(obj): '{:.2f}'.format(obj.geom.area) for obj in objects} | bigcode/self-oss-instruct-sc2-concepts |
def vec_to_str(vec):
"""
Convert a vec (of supposedly integers) into a str
"""
return ''.join(map(str, map(int, vec))) | bigcode/self-oss-instruct-sc2-concepts |
import math
def _deck_name(current_cnt, total_cnt):
""" Get deck name for DriveThruCards.
"""
if total_cnt > 130:
return 'deck{}/'.format(min(math.floor((current_cnt - 1) / 120) + 1,
math.ceil((total_cnt - 10) / 120)))
return '' | bigcode/self-oss-instruct-sc2-concepts |
def _can_show_deleted(context):
"""
Calculates whether to include deleted objects based on context.
Currently just looks for a flag called deleted in the context dict.
"""
if hasattr(context, 'show_deleted'):
return context.show_deleted
if not hasattr(context, 'get'):
return False
return context.get('deleted', False) | bigcode/self-oss-instruct-sc2-concepts |
def sort_dict_by_value(d, increase=True):
"""sort dict by value
Args:
d(dict): dict to be sorted
increase(bool, optional): increase sort or decrease sort. Defaults to True.
Returns:
[type]: [description]
Examples:
>>> d = Dict()
>>> d.sort_dict_by_value({"a": 1, "b": 2, "c": 3}, increase=False)
[{'c': 3}, {'b': 2}, {'a': 1}]
"""
return dict(sorted(d.items(), key=lambda x: x[1], reverse=not increase)) | bigcode/self-oss-instruct-sc2-concepts |
def _squeeze(lines, width):
"""
Squeeze the contents of a cell into a fixed width column, breaking lines on spaces where possible.
:param lines: list of string lines in the cell
:param width: fixed width of the column
:return: list of lines squeezed to fit
"""
if all(len(line) <= width for line in lines):
return lines
out = []
token_lines = [line.split(" ") for line in lines]
for token_line in token_lines:
line = []
for token in token_line:
if sum(len(token) for token in line) + len(token) + len(line) > width:
if line:
out.append(" ".join(line))
while len(token) > width:
out.append(token[:width])
token = token[width:]
line = [token]
else:
line.append(token)
out.append(" ".join(line))
return out | bigcode/self-oss-instruct-sc2-concepts |
def irc_split(line):
"""Split an event line, with any trailing free-form text as one item."""
try:
rest_pos = line.index(' :')
bits = line[0:rest_pos].split(' ') + [line[rest_pos + 2:]]
except ValueError:
bits = line.split(' ')
return bits | bigcode/self-oss-instruct-sc2-concepts |
def energy_capacity_rule(mod, g, p):
"""
The total energy capacity of dr_new operational in period p.
"""
return mod.DRNew_Energy_Capacity_MWh[g, p] | bigcode/self-oss-instruct-sc2-concepts |
def bollinger_bands(price_col, length=20, std=1.96):
"""
Calculate Bollinger Bands
:param price_col: A series of prices
:param length: Window length
:param std: Standard deviation
:return: A 3-tuple (upper band, mid, lower band)
"""
mid = price_col.rolling(window=length).mean()
upper = mid + std * price_col.rolling(window=length).std()
lower = mid - std * price_col.rolling(window=length).std()
return upper, mid, lower | bigcode/self-oss-instruct-sc2-concepts |
def get_census_params_by_county(columns):
"""Returns the base set of params for making a census API call by county.
columns: The list of columns to request."""
return {"get": ",".join(columns), "for": "county:*", "in": "state:*"} | bigcode/self-oss-instruct-sc2-concepts |
def incremental_mean(mu_i, n, x):
"""
Calculates the mean after adding x to a vector with given mean and size.
:param mu_i: Mean before adding x.
:param n: Number of elements before adding x.
:param x: Element to be added.
:return: New mean.
"""
delta = (x - mu_i) / float(n + 1)
mu_f = mu_i + delta
return mu_f | bigcode/self-oss-instruct-sc2-concepts |
def get_object_id_value(spall_dict):
"""
get the best value for OBJID
:param spall_dict:
:return:
"""
if "BESTOBJID" in spall_dict.keys():
return spall_dict["BESTOBJID"]
else:
return spall_dict["OBJID"] | bigcode/self-oss-instruct-sc2-concepts |
def first(seq, pred=None):
"""Return the first item in seq for which the predicate is true.
If the predicate is None, return the first item regardless of value.
If no items satisfy the predicate, return None.
"""
if pred is None:
pred = lambda x: True
for item in seq:
if pred(item):
return item
return None | bigcode/self-oss-instruct-sc2-concepts |
def multiple_benchmark_thetas(benchmark_names):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying multiple parameter benchmarks.
Parameters
----------
benchmark_names : list of str
List of names of the benchmarks (as in `madminer.core.MadMiner.add_benchmark`)
Returns
-------
output : tuple
Input to various SampleAugmenter functions
"""
return "benchmarks", benchmark_names | bigcode/self-oss-instruct-sc2-concepts |
def convertWCS(inwcs,drizwcs):
""" Copy WCSObject WCS into Drizzle compatible array."""
drizwcs[0] = inwcs.crpix[0]
drizwcs[1] = inwcs.crval[0]
drizwcs[2] = inwcs.crpix[1]
drizwcs[3] = inwcs.crval[1]
drizwcs[4] = inwcs.cd[0][0]
drizwcs[5] = inwcs.cd[1][0]
drizwcs[6] = inwcs.cd[0][1]
drizwcs[7] = inwcs.cd[1][1]
return drizwcs | bigcode/self-oss-instruct-sc2-concepts |
def is_eligible_for_exam(mmtrack, course_run):
"""
Returns True if user is eligible exam authorization process. For that the course must have exam
settings and user must have paid for it.
Args:
mmtrack (dashboard.utils.MMTrack): a instance of all user information about a program.
course_run (courses.models.CourseRun): A CourseRun object.
Returns:
bool: whether user is eligible or not
"""
return course_run.has_future_exam and mmtrack.has_paid(course_run.edx_course_key) | bigcode/self-oss-instruct-sc2-concepts |
import math
def calc_tf_padding(x,
kernel_size,
stride=1,
dilation=1):
"""
Calculate TF-same like padding size.
Parameters:
----------
x : tensor
Input tensor.
kernel_size : int
Convolution window size.
stride : int, default 1
Strides of the convolution.
dilation : int, default 1
Dilation value for convolution layer.
Returns
-------
tuple of 4 int
The size of the padding.
"""
height, width = x.size()[2:]
oh = math.ceil(height / stride)
ow = math.ceil(width / stride)
pad_h = max((oh - 1) * stride + (kernel_size - 1) * dilation + 1 - height, 0)
pad_w = max((ow - 1) * stride + (kernel_size - 1) * dilation + 1 - width, 0)
return pad_h // 2, pad_h - pad_h // 2, pad_w // 2, pad_w - pad_w // 2 | bigcode/self-oss-instruct-sc2-concepts |
def get(server_id, **kwargs):
"""Return one server."""
url = '/servers/{server_id}'.format(server_id=server_id)
return url, {} | bigcode/self-oss-instruct-sc2-concepts |
def bytes_to_human_readable(num, suffix='B'):
"""
Convert number of bytes to a human readable string
"""
for unit in ['','k','M','G','T','P','E','Z']:
if abs(num) < 1024.0:
return '{0:3.1f} {1}b'.format(num, unit)
num /= 1024.0
return '{0:3.1f} {1}b'.format(num, 'Y') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
import math
def measure_to_ma2_time(measure: float, resolution: int) -> Tuple[int, int]:
"""Convert measure in decimal form to ma2's format.
Ma2 uses integer timing for its measures. It does so by taking
the fractional part and multiplying it to the chart's
resolution, then rounding it up. For durations like holds
and slides, both the whole and fractional part are
multiplied by the charts resolution.
Args:
measure: The time a note happened or duration.
resolution: The number of ticks equal to one measure.
Returns:
A tuple (WHOLE_PART, FRACTIONAL_PART).
Raises:
ValueError: When measure is negative.
Examples:
Convert a note that happens in measure 2.5 in ma2 time
with resolution of 384.
>>> print(measure_to_ma2_time(2.5))
(2, 192)
Convert a duration of 3.75 measures in ma2 time with
resolution of 500.
>>> my_resolution = 500
>>> (whole, dec) = measure_to_ma2_time(3.75, my_resolution)
>>> whole*my_resolution + dec
1875.0
"""
if measure < 0:
raise ValueError("Measure is negative. " + str(measure))
(decimal_part, whole_part) = math.modf(measure)
decimal_part = round(decimal_part * resolution)
return int(whole_part), decimal_part | bigcode/self-oss-instruct-sc2-concepts |
import uuid
from datetime import datetime
def make_event(name, payload, safe=True, idempotent=True):
"""
Build an event structure made of the given payload
"""
return {
"id": str(uuid.uuid4()),
"name": name,
"created": datetime.utcnow().isoformat(),
"safe": safe,
"idempotent": idempotent,
"payload": payload
} | bigcode/self-oss-instruct-sc2-concepts |
def as_dict(val, key):
"""Construct a dict with a {`key`: `val`} structure if given `val` is not a `dict`, or copy `val` otherwise."""
return val.copy() if isinstance(val, dict) else {key: val} | bigcode/self-oss-instruct-sc2-concepts |
def multiply(number_1: int, number_2: int) -> int:
"""Multiply two numbers_together"""
return number_1 * number_2 | bigcode/self-oss-instruct-sc2-concepts |
def incrochet(strg):
""" get content inside crochet
Parameters
----------
strg : string
Returns
-------
lbra : left part of the string
inbr : string inside the bracket
Examples
--------
>>> strg ='abcd[un texte]'
>>> lbra,inbr = incrochet(strg)
>>> assert(lbra=='abcd')
>>> assert(inbr=='un texte')
"""
strg = strg.replace('\r', '')
ssp = strg.split('[')
lbra = ssp[0]
rbra = ''
inbr = ''
for k in ssp[1:]:
rbra = rbra+k+'['
rsp = rbra.split(']')
for k in rsp[:-1]:
inbr = inbr+k+']'
inbr = inbr.rstrip(']')
return(lbra, inbr) | bigcode/self-oss-instruct-sc2-concepts |
def fuselage_form_factor(
fineness_ratio: float,
ratio_of_corner_radius_to_body_width: float = 0.5
):
"""
Computes the form factor of a fuselage as a function of various geometrical parameters.
Assumes the body cross section is a rounded square with constant-radius-of-curvature fillets.
Body cross section can therefore vary from a true square to a true circle.
Uses the methodology described in:
Götten, Falk; Havermann, Marc; Braun, Carsten; Marino, Matthew; Bil, Cees.
"Improved Form Factor for Drag Estimation of Fuselages with Various Cross Sections.
AIAA Journal of Aircraft, 2021. DOI: 10.2514/1.C036032
https://arc.aiaa.org/doi/10.2514/1.C036032
Assumes fully turbulent flow. Coefficient of determination found in the paper above was 0.95.
Note: the value returned does not account for any base separation (other than minor aft-closure separation). The
equations were also fit to relatively-shape-optimized fuselages, and will be overly-optimistic for unoptimized
shapes.
Args:
fineness_ratio: The fineness ratio of the body (length / diameter).
ratio_of_corner_radius_to_body_width: A parameter that describes the cross-sectional shape of the fuselage.
Precisely, this is ratio of corner radius to body width.
* A value of 0 corresponds to a true square.
* A value of 0.5 (default) corresponds to a true circle.
Returns: The form factor of the body, defined as:
C_D = C_f * form_factor * (S_wet / S_ref)
"""
fr = fineness_ratio
r = 2 * ratio_of_corner_radius_to_body_width
cs1 = -0.825885 * r ** 0.411795 + 4.0001
cs2 = -0.340977 * r ** 7.54327 - 2.27920
cs3 = -0.013846 * r ** 1.34253 + 1.11029
form_factor = cs1 * fr ** cs2 + cs3
return form_factor | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
import re
def get_entrypoint(doc: Dict[str, Any]) -> Dict[str, Any]:
"""Find and return the entrypoint object in the doc."""
# Search supportedClass
for class_ in doc["supportedClass"]:
# Check the @id for each class
try:
class_id = class_["@id"]
except KeyError:
raise SyntaxError("Each supportedClass must have [@id]")
# Match with regular expression
match_obj = re.match(r'vocab:(.*)EntryPoint', class_id)
# Return the entrypoint object
if match_obj:
return class_
# If not found, raise error
raise SyntaxError("No EntryPoint class found") | bigcode/self-oss-instruct-sc2-concepts |
def get_species_mappings(num_specs, last_species):
"""
Maps species indices around species moved to last position.
Parameters
----------
num_specs : int
Number of species.
last_species : int
Index of species being moved to end of system.
Returns
-------
fwd_species_map : list of `int`
List of original indices in new order
back_species_map : list of `int`
List of new indicies in original order
"""
fwd_species_map = list(range(num_specs))
back_species_map = list(range(num_specs))
#in the forward mapping process
#last_species -> end
#all entries after last_species are reduced by one
back_species_map[last_species + 1:] = back_species_map[last_species:-1]
back_species_map[last_species] = num_specs - 1
#in the backwards mapping
#end -> last_species
#all entries with value >= last_species are increased by one
ind = fwd_species_map.index(last_species)
fwd_species_map[ind:-1] = fwd_species_map[ind + 1:]
fwd_species_map[-1] = last_species
return fwd_species_map, back_species_map | bigcode/self-oss-instruct-sc2-concepts |
def get_data_view_status(data_view_id):
"""
URL for retrieving the statuses of all services
associated with a data view.
:param data_view_id: The ID of the desired data views
:type data_view_id: str
"""
return "data_views/{}/status".format(data_view_id) | bigcode/self-oss-instruct-sc2-concepts |
def merge_args_and_kwargs(param_names, args, kwargs):
"""Merges args and kwargs for a given list of parameter names into a single
dictionary."""
merged = dict(zip(param_names, args))
merged.update(kwargs)
return merged | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def baddir(path: Path) -> bool:
"""
tells if a directory is not a Git repo or excluded.
A directory with top-level file ".nogit" is excluded.
Parameters
----------
path : pathlib.Path
path to check if it's a Git repo
Results
-------
bad : bool
True if an excluded Git repo or not a Git repo
"""
path = path.expanduser()
try:
if not path.is_dir():
return True
except PermissionError:
return True
try:
bad = (path / ".nogit").is_file() or not (path / ".git" / "HEAD").is_file()
except PermissionError: # Windows
bad = True
return bad | bigcode/self-oss-instruct-sc2-concepts |
import re
def findWords(line):
"""Parse string to extract all non-numeric strings"""
return re.findall(r'[a-z]*[A-Z]+', line, re.I) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def hz_to_mel(freqs: torch.Tensor):
"""
Converts a Tensor of frequencies in hertz to the mel scale.
Uses the simple formula by O'Shaughnessy (1987).
Args:
freqs (torch.Tensor): frequencies to convert.
"""
return 2595 * torch.log10(1 + freqs / 700) | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_run_parameter_value(param_name, contents):
"""
Parses outfile contents and extracts the value for the field named as `param_name` from the last row
"""
# read the header + the last line, and strip whitespace from field names
header = ','.join([c.lstrip() for c in contents[0].split(',')]) + '\n'
reader = csv.DictReader([header, contents[-1]])
return float(next(reader)[param_name]) | bigcode/self-oss-instruct-sc2-concepts |
def escapeToXML(text, isattrib = False):
"""Borrowed from twisted.xish.domish
Escape text to proper XML form, per section 2.3 in the XML specification.
@type text: L{str}
@param text: Text to escape
@type isattrib: L{bool}
@param isattrib: Triggers escaping of characters necessary for use as attribute values
"""
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
if isattrib:
text = text.replace("'", "'")
text = text.replace("\"", """)
return text | bigcode/self-oss-instruct-sc2-concepts |
def normalize(a):
"""Normalize array values to 0.0...255.0 range"""
a = a.astype(float)
lo, hi = a.min(), a.max()
a -= lo
a *= 255.0 / (hi - lo)
return a.round() | bigcode/self-oss-instruct-sc2-concepts |
def _nested_lambda_operator_base(string, lambda_operator1, lambda_operator2):
"""
Funcao base que constroi uma consulta usando dois operadores lambda do Odata.
Args:
string (str): String "cru" que serve de base para construir o operador.
Ex.: customFieldValues/items/customFieldItem eq 'MGSSUSTR6-06R'
lambda_operator1 (str): O primeiro operador lambda.
lambda_operator1 (str): O segundo operador lambda.
Returns:
(str): A consulta.
"""
properties, operator, *value = string.split()
value = " ".join(value)
p1, p2, p3 = properties.split("/")
return f"{p1}/{lambda_operator1}(x: x/{p2}/{lambda_operator2}(y: y/{p3} {operator} {value}))" | bigcode/self-oss-instruct-sc2-concepts |
import json
def dethemify(topicmsg):
""" Inverse of themify() """
json0 = topicmsg.find('{')
topic = topicmsg[0:json0].strip()
msg = json.loads(topicmsg[json0:])
return topic, msg | bigcode/self-oss-instruct-sc2-concepts |
def normalize_search_terms(search_terms: str)->str:
"""
Normalize the search terms so that searching for "A b c" is the same as searching for
"a b C", "B C A", etc.
Args:
search_terms (str): Space-delimited list of search terms.
Returns:
(str): Space-delimited search terms, lowercased and sorted.
"""
if not search_terms:
return search_terms
terms = search_terms.lower().split(" ")
terms.sort()
return " ".join(terms) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def candidates_to_bits(candidates: Set[int]) -> int:
"""
Convert a candidates set into its bits representation
The bits are in big endian order
>>> bin(candidates_to_bits({1, 2, 3, 6, 7}))
'0b1100111'
>>> bin(candidates_to_bits({6, 9}))
'0b100100000'
"""
bits = 0
for candidate in candidates:
bits ^= 1 << (candidate - 1)
return bits | bigcode/self-oss-instruct-sc2-concepts |
def get_compute_op_list(job_content):
"""
Get compute op info list from job content info
:param job_content: tbe compilation content info
:return: compute op info list
"""
op_list = job_content["op_list"]
op_compute_list = []
for op in op_list:
if op["type"] != "Data":
op_compute_list.append(op)
return op_compute_list | bigcode/self-oss-instruct-sc2-concepts |
def remove_namespace(tag, name, ns_dict):
"""Used to remove namespaces from tags to create keys in dictionary for quick key lookup.
Attr:
tag(str): Full tag value. Should include namespace by default.
name(str): The namespace key. Usually the ticker of the company.
ns_dict(dictionary): Mapping of all the namespace links.
"""
tag = tag.replace('{}'.format(ns_dict[name]), '')
tag = tag.replace('{', '')
tag = tag.replace('}', '')
return tag | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def flip_v(matrix: List[List]) -> List[List]:
"""Flip a matrix (list of list) vertically
"""
return matrix[::-1] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def int_conversion(string: str) -> Union[int, str]:
"""
Check and convert string that can be represented as an integer
:param string: Input string
:return: Result of conversion
"""
try:
value = int(string)
except ValueError:
value = string
return value | bigcode/self-oss-instruct-sc2-concepts |
def str_to_bool(string, truelist=None):
"""Returns a boolean according to a string. True if the string
belongs to 'truelist', false otherwise.
By default, truelist has "True" only.
"""
if truelist is None:
truelist = ["True"]
return string in truelist | bigcode/self-oss-instruct-sc2-concepts |
def level_to_criticality(level: int) -> str:
"""Translate level integer to Criticality string."""
if level >= 4:
return "Very Malicious"
elif level >= 3:
return "Malicious"
elif level >= 2:
return "Suspicious"
elif level >= 1:
return "Informational"
return "Unknown" | bigcode/self-oss-instruct-sc2-concepts |
def get_title_to_id_dict(titles):
"""Creates a dict mapping each title with an id.
:param titles: list of titles
:type titles: list
:return: dict mapping a title to an id.
:rtype: dict
"""
title_to_id = {title: i for i, title in enumerate(titles)}
return title_to_id | bigcode/self-oss-instruct-sc2-concepts |
def timestep(dtime, time, end_time):
"""
calculates the timestep for a given time
Returns the timestep if the calculation isnt overstepping the endtime
if it would overstep it returns the resttime to calculte to the endtime.
:param dtime: timestep
:param time: current time in simulation
:param end_time: endtime of the simulation
:returns: correct timestep to reach the calculation endtime
"""
return dtime if (time + dtime) <= end_time else (end_time - time) | bigcode/self-oss-instruct-sc2-concepts |
def compose_tbl_filename(
key_names, key_indices=None,
prefix='tbl', suffix='txt',
var_separator='.', idx_separator='-'):
"""compose a file name based on key names
Parameters
----------
key_names : list of str
A list of key names
key_indices : list of str
A list of key indices, which can be a number, ``None``, a
wildcard ``*``, a wildcards in parentheses ``(*)``, a back
reference ``\\n`` (``n`` is a number),
e.g., ``(1, None, '*', '(*)', '\\1')``
prefix : str, default ``tbl``
A prefix of a file name
suffix : str, default ``txt``
A suffix of a file name (filename extension)
var_separator : str, default '.'
A separator between key names
idx_separator : str, default '-'
A separator between a key name and a key index
Returns
-------
str
A file name
"""
if not key_names:
return prefix + '.' + suffix # e.g. "tbl.txt"
if key_indices is None:
colidxs = key_names
# e.g., ('var1', 'var2', 'var3'),
middle = var_separator.join(colidxs)
# e.g., 'var1.var2.var3'
ret = prefix + var_separator + middle + '.' + suffix
# e.g., 'tbl.var1.var2.var3.txt'
return ret
# e.g.,
# key_names = ('var1', 'var2', 'var3', 'var4', 'var5'),
# key_indices = (1, None, '*', '(*)', '\\1')
idx_str = key_indices
# e.g., (1, None, '*', '(*)', '\\1')
idx_str = ['w' if i == '*' else i for i in idx_str]
# e..g, [1, None, 'w', '(*)', '\\1']
idx_str = ['wp' if i == '(*)' else i for i in idx_str]
# e.g., [1, None, 'w', 'wp', '\\1']
idx_str = ['b{}'.format(i[1:]) if isinstance(i, str) and i.startswith('\\') else i for i in idx_str]
# e.g., [1, None, 'w', 'wp', 'b1']
idx_str = ['' if i is None else '{}{}'.format(idx_separator, i) for i in idx_str]
# e.g., ['-1', '', '-w', '-wp', '-b1']
colidxs = [n + i for n, i in zip(key_names, idx_str)]
# e.g., ['var1-1', 'var2', 'var3-w', 'var4-wp', 'var5-b1']
middle = var_separator.join(colidxs)
# e.g., 'var1-1.var2.var3-w.var4-wp.var5-b1'
ret = prefix + var_separator + middle + '.' + suffix
# e.g., tbl.var1-1.var2.var3-w.var4-wp.var5-b1.txt
return ret | bigcode/self-oss-instruct-sc2-concepts |
import random
def _random_value(x = None, min=0, max=10):
"""
(not very eye pleasing ;)
returns a random int between min and max
"""
return random.randint(min,max) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _is_bed_row(bed_row):
"""Checks the format of a row of a bedfile.
The logic is to check the first three fields that should be
chromosome start end."""
if len(bed_row) < 3:
return False
return (
(re.match(r"^chr.+$", bed_row[0]) is not None)
and (re.match(r"^[0-9]+$", bed_row[1]) is not None)
and (re.match(r"^[0-9]+$", bed_row[2]) is not None)
) | bigcode/self-oss-instruct-sc2-concepts |
import collections
def group_train_data(training_data):
"""
Group training pairs by first phrase
:param training_data: list of (seq1, seq2) pairs
:return: list of (seq1, [seq*]) pairs
"""
groups = collections.defaultdict(list)
for p1, p2 in training_data:
l = groups[tuple(p1)]
l.append(p2)
return list(groups.items()) | bigcode/self-oss-instruct-sc2-concepts |
def gcd(a, b):
"""Calculate Greatest Common Divisor (GCD)."""
return b if a == 0 else gcd(b % a, a) | bigcode/self-oss-instruct-sc2-concepts |
def _samples_calls(variant_collection, dataset_id, samples):
"""Count all allele calls for a dataset in variants collection
Accepts:
variant_collection(pymongo.database.Database.Collection)
dataset_id(str): id of dataset to be updated
samples(list): list of dataset samples
Returns:
allele_count(int)
"""
allele_count = 0
for sample in samples:
pipe = [
{
"$group": {
"_id": None,
"alleles": {"$sum": f"$datasetIds.{dataset_id}.samples.{sample}.allele_count"},
}
}
]
aggregate_res = variant_collection.aggregate(pipeline=pipe)
for res in aggregate_res:
allele_count += res.get("alleles")
return allele_count | bigcode/self-oss-instruct-sc2-concepts |
import zlib
def decode_gzip(content):
"""Return gzip-decoded string.
Arguments:
- `content`: bytestring to gzip-decode.
"""
return zlib.decompress(content, 16 + zlib.MAX_WBITS) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
import operator
def prod(iterable):
"""Take product of iterable like."""
return reduce(operator.mul, iterable, 1) | bigcode/self-oss-instruct-sc2-concepts |
def external(cls):
"""
Decorator.
This class or package is meant to be used *only* by code outside this project.
"""
return cls | bigcode/self-oss-instruct-sc2-concepts |
def get_tag(body):
"""Get the annotation tag from the body."""
if not isinstance(body, list):
body = [body]
try:
return [b['value'] for b in body if b['purpose'] == 'tagging'][0]
except IndexError:
return None | bigcode/self-oss-instruct-sc2-concepts |
def check_is_faang(item):
"""
Function checks that record belongs to FAANG project
:param item: item to check
:return: True if item has FAANG project label and False otherwise
"""
if 'characteristics' in item and 'project' in item['characteristics']:
for project in item['characteristics']['project']:
if 'text' in project and project['text'].lower() == 'faang':
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_prediction_data(data, tokenizer):
"""
It process the prediction data as the format used as training.
Args:
data (obj:`List[str]`): The prediction data whose each element is a tokenized text.
tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string.
Returns:
examples (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object.
A Example object contains `text`(word_ids) and `seq_len`(sequence length).
"""
examples = []
for text in data:
# ids = tokenizer.encode(text) # JiebaTokenizer
ids = tokenizer.encode(text)[0].tolist()[
1:-1] # ErnieTokenizer list[ids]
examples.append([ids, len(ids)])
return examples | bigcode/self-oss-instruct-sc2-concepts |
def ListFeatures(font):
"""List features for specified font. Table assumed structured like GPS/GSUB.
Args:
font: a TTFont.
Returns:
List of 3-tuples of ('GPOS', tag, name) of the features in the font.
"""
results = []
for tbl in ["GPOS", "GSUB"]:
if tbl in font.keys():
results += [
(tbl,
f.FeatureTag,
"lookups: [{}]".format(", ".join(map(str, f.Feature.LookupListIndex)))
) for f in font[tbl].table.FeatureList.FeatureRecord
]
return results | bigcode/self-oss-instruct-sc2-concepts |
def split_string_content(content):
"""
Split the string content and returns as a list.
"""
file_contents = content.split("\n")
if file_contents[-1] == '':
file_contents = file_contents[:-1]
return file_contents | bigcode/self-oss-instruct-sc2-concepts |
def is_widget(view):
"""
Returns `True` if @view is a widget.
"""
return view.settings().get('is_widget') | bigcode/self-oss-instruct-sc2-concepts |
def geom_cooling(temp, alpha = 0.95):
"""
Geometric temperature decreasing procedure allows for temperature variations
after every iteration (k).
It returns a value of temperature such that
T(k+1)=alpha*(T)
Parameters
----------
temp: float
Current temperature.
alpha: float
Fixed geometric ratio.
"""
return temp * alpha | bigcode/self-oss-instruct-sc2-concepts |
import time
def apipoll(endpoint, *args, **kwargs):
"""Poll an api endpoint until there is a result that is not None
poll_wait and max_poll can be specified in kwargs to set the polling
interval and max wait time in seconds.
"""
result = endpoint(*args, **kwargs)
if result is not None:
return result
start = time.time()
while True:
poll_wait = kwargs.get('poll_wait', 1)
max_poll = kwargs.get('max_poll', 60)
time.sleep(poll_wait)
result = endpoint(*args, **kwargs)
if result is not None or (time.time() - start) > max_poll:
return result | bigcode/self-oss-instruct-sc2-concepts |
def multiply(a, b):
"""
>>> multiply(3, 5)
15
>>> multiply(-4, 5)
-20
>>> multiply(-4, -2)
8
"""
iterator = 0
value = 0
if iterator < a:
while iterator < a:
value += b
iterator += 1
else:
while iterator > a:
value -= b
iterator -= 1
return value | bigcode/self-oss-instruct-sc2-concepts |
import re
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('Byte', 'KiB', 'MiB', 'GiB', 'T', 'P', 'E', 'Z', 'Y')
num = re.findall(r"[0-9\.]+", s)
assert (len(num) == 1)
num = num[0]
num = float(num)
for i, n in enumerate(symbols):
if n in s:
multiplier = 1 << (i)*10
return int(num * multiplier)
raise Exception('human number not parsable') | bigcode/self-oss-instruct-sc2-concepts |
def print14list(pair14, shift, molecule):
"""Generate pair 14 list line
Parameters
----------
pair14 : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
Returns
-------
pair14 : str
Pair14 line data
"""
ftype = 1
atomApair = molecule.atoms[pair14[0].serialOriginal -1].serial-shift
atomBdihedral = molecule.atoms[pair14[1].serialOriginal -1].serial-shift
return '%5d%5d%5d\n' % (atomApair, atomBdihedral, ftype) | bigcode/self-oss-instruct-sc2-concepts |
import struct
def readu8(file):
""" Reads an unsigned byte from the file."""
data = file.read(1)
return struct.unpack("B", data)[0] | bigcode/self-oss-instruct-sc2-concepts |
def is_float(istring):
"""Convert a string to a float.
Parameters
----------
istring : str
String to convert to a float.
Returns
-------
float
Converted float when successful, ``0`` when when failed.
"""
try:
return float(istring.strip())
except Exception:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def prime_factors(n: int) -> List[int]:
"""Return an ascending list of the (greather-than-one) prime factors of n.
>>> prime_factors(1)
[]
>>> prime_factors(2)
[2]
>>> prime_factors(4)
[2, 2]
>>> prime_factors(60)
[2, 2, 3, 5]
"""
factors = []
d = 2
while d * d <= n:
while (n % d) == 0:
factors.append(d)
n //= d
d += 1
if n > 1:
factors.append(n)
return factors | bigcode/self-oss-instruct-sc2-concepts |
def _proposed_scaling_both(current, desired):
"""
identify a x and y scaling to make the current size into the desired size
Arguments
---------
current : tuple
float tuple of current size of svg object
desired : tuple
float tuple of desired size of svg object
Returns
-------
tuple
float tuple of scalar constants for size change in each dimension
"""
scale_x = desired[0]/current[0]
scale_y = desired[1]/current[1]
return scale_x, scale_y | bigcode/self-oss-instruct-sc2-concepts |
def prometheus_worker_job_count(prometheus, testconfig):
"""
Given a type of a worker job (ReportJob or NotifyJob), returns the value of that metric
"""
def _prometheus_worker_job_count(job_type):
metric_response_codes = prometheus.get_metric(
f"apisonator_worker_job_count{{namespace=\"{testconfig['openshift']['projects']['threescale']['name']}\", "
f"type=\"{job_type}\"}}")
return int(metric_response_codes[0]['value'][1]) if len(metric_response_codes) > 0 else 0
return _prometheus_worker_job_count | bigcode/self-oss-instruct-sc2-concepts |
def truncate_descriptions(requested_user_rooms):
"""
Cut descriptions if too long
"""
for i in range(0, len(requested_user_rooms)):
if len(requested_user_rooms[i]['description']) >= 85:
requested_user_rooms[i]['description'] = requested_user_rooms[i]['description'][0:85] + "..."
return requested_user_rooms | bigcode/self-oss-instruct-sc2-concepts |
def calculate_expected_wins(win_rate, num_games):
"""Calculate current expected wins"""
expected_wins = win_rate * float(num_games)
result = int(round(expected_wins, 0))
return result | bigcode/self-oss-instruct-sc2-concepts |
def get_virtualenv_dir(version):
"""Get virtualenv directory for given version."""
return "version-{}".format(version) | bigcode/self-oss-instruct-sc2-concepts |
def convert_timestamp(timestamp: str) -> int:
"""
Converts a timestamp (MM:SS) to milliseconds.
"""
timestamp_list = timestamp.split(":")
minutes = timestamp_list[0]
seconds = timestamp_list[1]
minutes_in_ms = int(minutes) * 60 * 1000
seconds_in_ms = int(seconds) * 1000
total_ms = minutes_in_ms + seconds_in_ms
if any((len(seconds) > 2, len(seconds) < 2, minutes_in_ms < 0, seconds_in_ms < 0)):
raise ValueError("Invalid format. Proper format is MM:SS.")
return total_ms | bigcode/self-oss-instruct-sc2-concepts |
def chk_keys(keys, src_list):
"""Check the keys are included in the src_list
:param keys: the keys need to check
:param src_list: the source list
"""
for key in keys:
if key not in src_list:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def field(fields, **kwargs):
"""Helper for inserting more fields into a metrics fields dictionary.
Args:
fields: Dictionary of metrics fields.
kwargs: Each argument is a key/value pair to insert into dict.
Returns:
Copy of original dictionary with kwargs set as fields.
"""
f = fields.copy()
f.update(kwargs)
return f | bigcode/self-oss-instruct-sc2-concepts |
def chunkString(string, length):
"""This function returns a generator, using a generator comprehension.
The generator returns the string sliced, from 0 + a multiple of the length of the chunks,
to the length of the chunks + a multiple of the length of the chunks.
Args:
string (String): string to be splitted
length (int): chunk size
Returns:
Generator: generator with chunks
"""
return (string[0+i:length+i] for i in range(0, len(string), length)) | bigcode/self-oss-instruct-sc2-concepts |
def post_process_headways(avg_headway, number_of_trips_per_hour, trip_per_hr_threshold=.5,
reset_headway_if_low_trip_count=180):
"""Used to adjust headways if there are low trips per hour observed in the GTFS dataset.
If the number of trips per hour is below the trip frequency interval, headways are changed to
reset_headway_if_low_trip_count_value (defaults to 180 minutes)."""
if number_of_trips_per_hour <= trip_per_hr_threshold: # If Number of Trips Per Hour is less than .5, set to 180.
avg_headway = reset_headway_if_low_trip_count
return avg_headway | bigcode/self-oss-instruct-sc2-concepts |
def sop_classes(uids):
"""Simple decorator that adds or extends ``sop_classes`` attribute
with provided list of UIDs.
"""
def augment(service):
if not hasattr(service, 'sop_classes'):
service.sop_classes = []
service.sop_classes.extend(uids)
return service
return augment | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_show_ip_ecmp(raw_result):
"""
Parse the 'show ip ecmp' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show ip ecmp in a \
dictionary of the form:
::
{
'global_status': True,
'resilient': False,
'src_ip': True,
'dest_ip': True,
'src_port': True,
'dest_port': True
}
"""
show_ip_ecmp_re = (
r'\s*ECMP Configuration\s*-*\s*'
r'ECMP Status\s*: (?P<global_status>\S+)\s*'
r'(Resilient Hashing\s*: (?P<resilient>\S+))?\s*'
r'ECMP Load Balancing by\s*-*\s*'
r'Source IP\s*: (?P<src_ip>\S+)\s*'
r'Destination IP\s*: (?P<dest_ip>\S+)\s*'
r'Source Port\s*: (?P<src_port>\S+)\s*'
r'Destination Port\s*: (?P<dest_port>\S+)\s*'
)
re_result = re.match(show_ip_ecmp_re, raw_result)
assert re_result
result = re_result.groupdict()
for key, value in result.items():
if value is not None:
if value == 'Enabled':
result[key] = True
elif value == 'Disabled':
result[key] = False
return result | bigcode/self-oss-instruct-sc2-concepts |
import sympy
def DfjDxi(DN,f):
"""
This method defines a gradient. Returns a matrix D such that D(i,j) = D(fj)/D(xi)
This is the standard in fluid dynamics, that is:
D(f1)/D(x1) D(f2)/D(x1) D(f3)/D(x1)
D(f1)/D(x2) D(f2)/D(x2) D(f3)/D(x2)
D(f1)/D(x3) D(f2)/D(x3) D(f3)/D(x3)
Keyword arguments:
- DN -- The shape function derivatives
- f-- The variable to compute the gradient
"""
return sympy.simplify(DN.transpose()*f) | bigcode/self-oss-instruct-sc2-concepts |
def manhattan_distance(p1, p2):
"""
Precondition: p1 and p2 are same length
:param p1: point 1 tuple coordinate
:param p2: point 2 tuple coordinate
:return: manhattan distance between two points p1 and p2
"""
distance = 0
for dim in range(len(p1)):
distance += abs(p1[dim] - p2[dim])
return distance | bigcode/self-oss-instruct-sc2-concepts |
def tags_with_text(xml, tags=None):
"""Return a list of tags that contain text retrieved recursively from an
XML tree
"""
if tags is None:
tags = []
for element in xml:
if element.text is not None:
tags.append(element)
elif len(element) > 0:
tags_with_text(element, tags)
else:
message = 'Unknown XML structure: {0}'.format(element)
raise ValueError(message)
return tags | bigcode/self-oss-instruct-sc2-concepts |
def generate_text_notebook() -> str:
"""Generate `notebook.md` content."""
content = (
"""\
---
file_format: mystnb
kernelspec:
name: python3
---
# Text-based Notebook
```{code-cell}
print("Hello, World!")
```
""".rstrip()
+ "\n"
)
return content | bigcode/self-oss-instruct-sc2-concepts |
def build_vector(image, binary=True):
"""
图像转一维特征向量
:param image: pillow Image object with mode 1 or mode L
:param binary: 黑白图是否生成为0,1向量
:return: list of int
"""
vector = []
for pixel in image.getdata():
if binary:
vector.append(1 if pixel == 255 else 0)
else:
vector.append(pixel)
return vector | bigcode/self-oss-instruct-sc2-concepts |
def combine_docs(docs):
"""
Combine documents from a list of documents.
Only combines if the element is a string.
Parameters
----------
`docs` : `list`. Documents to combine
Returns
-------
`string` : Combined string of documents
"""
combined_docs = ""
for doc in docs:
if isinstance(doc, str):
combined_docs = combined_docs + doc
return combined_docs | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def restore_timestamp(formatted_timestamp):
"""Return a timestamp from a formatted string."""
return datetime.strptime(formatted_timestamp,
"%Y-%m-%d %H:%M:%S").strftime('%Y%m%d%H%M%S') | bigcode/self-oss-instruct-sc2-concepts |
def div(n, d):
"""Divide, with a useful interpretation of division by zero."""
try:
return n/d
except ZeroDivisionError:
if n:
return n*float('inf')
return float('nan') | bigcode/self-oss-instruct-sc2-concepts |
def wrap(ag, compound='atoms'):
"""
Shift the contents of a given AtomGroup back into the unit cell. ::
+-----------+ +-----------+
| | | |
| 3 | 6 | 6 3 |
| ! | ! | ! ! |
| 1-2-|-5-8 -> |-5-8 1-2-|
| ! | ! | ! ! |
| 4 | 7 | 7 4 |
| | | |
+-----------+ +-----------+
Example
-------
.. code-block:: python
ag = u.atoms
transform = mda.transformations.wrap(ag)
u.trajectory.add_transformations(transform)
Parameters
----------
ag: Atomgroup
Atomgroup to be wrapped in the unit cell
compound : {'atoms', 'group', 'residues', 'segments', 'fragments'}, optional
The group which will be kept together through the shifting process.
Notes
-----
When specifying a `compound`, the translation is calculated based on
each compound. The same translation is applied to all atoms
within this compound, meaning it will not be broken by the shift.
This might however mean that not all atoms from the compound are
inside the unit cell, but rather the center of the compound is.
Returns
-------
MDAnalysis.coordinates.base.Timestep
"""
def wrapped(ts):
ag.wrap(compound=compound)
return ts
return wrapped | bigcode/self-oss-instruct-sc2-concepts |
def parse_scripts(scp_path, value_processor=lambda x: x, num_tokens=2):
"""
Parse kaldi's script(.scp) file
If num_tokens >= 2, function will check token number
"""
scp_dict = dict()
line = 0
with open(scp_path, "r") as f:
for raw_line in f:
scp_tokens = raw_line.strip().split()
line += 1
if num_tokens >= 2 and len(scp_tokens) != num_tokens or len(scp_tokens) < 2:
raise RuntimeError(
"For {}, format error in line[{:d}]: {}".format(
scp_path, line, raw_line
)
)
if num_tokens == 2:
key, value = scp_tokens
else:
key, value = scp_tokens[0], scp_tokens[1:]
if key in scp_dict:
raise ValueError(
"Duplicated key '{0}' exists in {1}".format(key, scp_path)
)
scp_dict[key] = value_processor(value)
return scp_dict | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(fjson):
"""
Args:
fjson (str) - file name of json to read
Returns:
dictionary stored in fjson
"""
with open(fjson) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def map_pathogen_id_to_name(pathogen_id):
"""
"""
mapping = {
"p00": "Acinetobacter baumannii",
"p01": "Baceroides fragilis",
"p02": "Burkholderia cepacia",
"p03": "Candida albicans",
"p04": "Candida giabrata",
"p05": "Candida parapsilosis",
"p06": "Candida tropicalis",
"p07": "Citrobacter diversus",
"p08": "Citrobacter freundii",
"p09": "Citrobacter koseri",
"p10": "Clostridium difficile",
"p11": "Enterobacter aerogenes",
"p12": "Enterobacter cloacae",
"p13": "Enterococcus faecalis",
"p14": "Enterococcus faecium",
"p15": "Escherichia coli",
"p16": "Haemophilus influenzae",
"p17": "Klebsiella oxytoca",
"p18": "Klebsiella pneumoniae",
"p19": "Moraxella catarrhalis",
"p20": "Morganella morganii",
"p21": "Proteaus mirabilis",
"p22": "Pseudomonas aeruginosa",
"p23": "Serratia marcescens",
"p24": "Staphylococcus aureus (MSSA, MRSA)",
"p25": "Staphylococcus auricularis",
"p26": "Staphylococcus capitis ssp. capitis",
"p27": "Staphylococcus capitis ssp. unspecified",
"p28": "Staphylococcus coagulase negative",
"p29": "Staphylococcus cohnii",
"p30": "Staphylococcus epidermidis",
"p31": "Staphylococcus gallinarum",
"p32": "Staphylococcus haemolyticus",
"p33": "Staphylococcus hominis",
"p34": "Staphylococcus lentus",
"p35": "Staphylococcus lugdenensis",
"p36": "Staphylococcus saccharolyticus",
"p37": "Staphylococcus saprophyticus",
"p38": "Staphylococcus schleiferi",
"p39": "Staphylococcus sciuri",
"p40": "Staphylococcus simulans",
"p41": "Staphylococcus warneri",
"p42": "Staphylococcus xylosus",
"p43": "Stenotrophomonas maltophilia",
"p44": "Streptococcus group A (Streptococcus pyogenes)",
"p45": "Streptococcus group B (Streptococcus agalactiae)",
"p46": "Streptococcus group D (Sterptococcus bovis)",
"p47": "Streptococcus pneumoniae (pneumococcus)",
"p49": "Strepotcuccus viridans (includes angiosus, bovis, mitis, mutans, salivarius)",
"p48": "Torulopsis glabrata (Candida glabrata)",
"p50": "Other pathogen",
}
pathogen = ''
if pathogen_id in mapping:
pathogen = mapping[pathogen_id]
return pathogen | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_covered_percentage(fuzzer_row_covered_regions,
fuzzer_col_covered_regions):
"""Returns the number of regions covered by the fuzzer of the column
but not by the fuzzer of the row."""
unique_region_count = 0
for region in fuzzer_col_covered_regions:
if region not in fuzzer_row_covered_regions:
unique_region_count += 1
return unique_region_count | bigcode/self-oss-instruct-sc2-concepts |
def check_mid_low(device_name):
"""Check if a device domain contains mid or low"""
domain, *_ = device_name.split("/")
if "mid" in domain or "low" in domain:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def getSonarData(sensor, angle):
"""
Transmits the sonar angle and returns the sonar intensities
Args:
sensor (Ping360): Sensor class
angle (int): Gradian Angle
Returns:
list: Intensities from 0 - 255
"""
sensor.transmitAngle(angle)
data = bytearray(getattr(sensor, '_data'))
return [k for k in data] | bigcode/self-oss-instruct-sc2-concepts |
def _validate_params_epaipm(etl_params):
"""Validate the etl parameters for EPA IPM.
Args:
etl_params (iterable): dictionary of inputs
Returns:
iterable: validated dictionary of inputs
"""
epaipm_dict = {}
# pull out the etl_params from the dictionary passed into this function
try:
epaipm_dict['epaipm_tables'] = etl_params['epaipm_tables']
except KeyError:
epaipm_dict['epaipm_tables'] = []
if not epaipm_dict['epaipm_tables']:
return {}
return(epaipm_dict) | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_emoji(num_emojis: int) -> str:
""" Generates a psuedo-random list of emojis with pasta sprinkled in """
emojis = ["🙄", "😙", "😐", "🤤", "😤", "😲", "😬", "😭", "🥵", "🥺", "🤠", "🤫", "😳", "😢"]
output: str = ""
for _ in range(num_emojis):
output += random.choice(emojis) + "🍝"
return output | bigcode/self-oss-instruct-sc2-concepts |
def try_attribute(node, attribute_name, default=None):
"""Tries to get an attribute from the supplied node. Returns the default
value if the attribute is unavailable."""
if node.hasAttribute(attribute_name):
return node.getAttribute(attribute_name)
return default | 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.