seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_ray_num(file_path):
"""
extract the ray's number from it's file name
Parameters:
file_path : string: full path to ray file
Returns:
num :string : the number corresponding to the ray
"""
filename = file_path.split('/')[-1]
num = filename[3:-3]
return num | bigcode/self-oss-instruct-sc2-concepts |
def stats_file_keys(gene_number):
"""Return fiels in stats file, ordered, as a list of string"""
return [
'popsize',
'genenumber',
'generationnumber',
'diversity',
] + ['viabilityratio' + str(i) for i in range(gene_number)
] + ['viabilityratioDB' + str(i) for i in range(gene_number)
] | bigcode/self-oss-instruct-sc2-concepts |
def knight_amount(board_state, player):
"""
Returns amount of knights the player has
"""
board = board_state
knight_amt = 0
for row in board:
for column in row:
if player == 1 and column == "k":
knight_amt += 1
elif player == 0 and column == "K":
knight_amt += 1
return knight_amt | bigcode/self-oss-instruct-sc2-concepts |
def enum(**named_values):
"""Creates an enum type."""
return type('Enum', (), named_values) | bigcode/self-oss-instruct-sc2-concepts |
def assign_pre_id_to_inner_nodes(phylo_tree):
"""
Replace the name of the inner nodes of a given phylogenetic tree with
its preorder number in the tree.
"""
idx = 0
for node in phylo_tree.find_clades(terminal=False, order='preorder'):
node.name = '%d' % (idx)
idx += 1
return phylo_tree | bigcode/self-oss-instruct-sc2-concepts |
def get_column_names(path_to_test, key_to_infer):
"""
Get a list containing the names of the columns in your table minus the column that
you want to infer.
=Parameters=
path_to_test: Path where your test.csv is saved.
key_to_infer: The name of the column that you want to infer.
"""
with open(path_to_test, 'r') as f:
list_of_columns = f.readline()[:-1].split(',')
list_of_columns.remove(key_to_infer[0])
return list_of_columns | bigcode/self-oss-instruct-sc2-concepts |
def list_of_lists_to_md_table(rows):
"""Convert a list (rows) of lists (columns) to a Markdown table.
The last (right-most) column will not have any trailing whitespace so that
it wraps as cleanly as possible.
Based on solution provided by antak in http://stackoverflow.com/a/12065663
CC-BY-SA 4.0 (International)
https://creativecommons.org/licenses/by-sa/4.0/
"""
lines = []
widths = [max(map(len, map(str, col))) for col in zip(*rows)]
for r, row in enumerate(rows):
formatted = []
last_col = len(row) - 1
for i, col in enumerate(row):
if i == last_col:
formatted.append(str(col))
else:
formatted.append(str(col).ljust(widths[i]))
lines.append(f"| {' | '.join(formatted)} |")
formatted = []
last_col = len(rows[0]) - 1
for i, col in enumerate(rows[0]):
if i == last_col:
formatted.append("-" * (len(col)))
else:
formatted.append("-" * widths[i])
lines.insert(1, f"| {' | '.join(formatted)} |")
return "\n".join(lines) | bigcode/self-oss-instruct-sc2-concepts |
def read_lines(file_path):
""" Read lines from the file and return then as a list. """
lines = []
with open(file_path, 'r', encoding='utf8') as asm_file:
lines = asm_file.readlines()
return lines | bigcode/self-oss-instruct-sc2-concepts |
import random
def between(min_wait, max_wait):
"""
Returns a function that will return a random number between min_wait and max_wait.
Example::
class MyUser(User):
# wait between 3.0 and 10.5 seconds after each task
wait_time = between(3.0, 10.5)
"""
return lambda instance: min_wait + random.random() * (max_wait - min_wait) | bigcode/self-oss-instruct-sc2-concepts |
def _recolumn(tmy3_dataframe):
"""
Rename the columns of the TMY3 DataFrame.
Parameters
----------
tmy3_dataframe : DataFrame
inplace : bool
passed to DataFrame.rename()
Returns
-------
Recolumned DataFrame.
"""
# paste in the header as one long line
raw_columns = 'ETR (W/m^2),ETRN (W/m^2),GHI (W/m^2),GHI source,GHI uncert (%),DNI (W/m^2),DNI source,DNI uncert (%),DHI (W/m^2),DHI source,DHI uncert (%),GH illum (lx),GH illum source,Global illum uncert (%),DN illum (lx),DN illum source,DN illum uncert (%),DH illum (lx),DH illum source,DH illum uncert (%),Zenith lum (cd/m^2),Zenith lum source,Zenith lum uncert (%),TotCld (tenths),TotCld source,TotCld uncert (code),OpqCld (tenths),OpqCld source,OpqCld uncert (code),Dry-bulb (C),Dry-bulb source,Dry-bulb uncert (code),Dew-point (C),Dew-point source,Dew-point uncert (code),RHum (%),RHum source,RHum uncert (code),Pressure (mbar),Pressure source,Pressure uncert (code),Wdir (degrees),Wdir source,Wdir uncert (code),Wspd (m/s),Wspd source,Wspd uncert (code),Hvis (m),Hvis source,Hvis uncert (code),CeilHgt (m),CeilHgt source,CeilHgt uncert (code),Pwat (cm),Pwat source,Pwat uncert (code),AOD (unitless),AOD source,AOD uncert (code),Alb (unitless),Alb source,Alb uncert (code),Lprecip depth (mm),Lprecip quantity (hr),Lprecip source,Lprecip uncert (code),PresWth (METAR code),PresWth source,PresWth uncert (code)' # noqa: E501
new_columns = [
'ETR', 'ETRN', 'GHI', 'GHISource', 'GHIUncertainty',
'DNI', 'DNISource', 'DNIUncertainty', 'DHI', 'DHISource',
'DHIUncertainty', 'GHillum', 'GHillumSource', 'GHillumUncertainty',
'DNillum', 'DNillumSource', 'DNillumUncertainty', 'DHillum',
'DHillumSource', 'DHillumUncertainty', 'Zenithlum',
'ZenithlumSource', 'ZenithlumUncertainty', 'TotCld', 'TotCldSource',
'TotCldUnertainty', 'OpqCld', 'OpqCldSource', 'OpqCldUncertainty',
'DryBulb', 'DryBulbSource', 'DryBulbUncertainty', 'DewPoint',
'DewPointSource', 'DewPointUncertainty', 'RHum', 'RHumSource',
'RHumUncertainty', 'Pressure', 'PressureSource',
'PressureUncertainty', 'Wdir', 'WdirSource', 'WdirUncertainty',
'Wspd', 'WspdSource', 'WspdUncertainty', 'Hvis', 'HvisSource',
'HvisUncertainty', 'CeilHgt', 'CeilHgtSource', 'CeilHgtUncertainty',
'Pwat', 'PwatSource', 'PwatUncertainty', 'AOD', 'AODSource',
'AODUncertainty', 'Alb', 'AlbSource', 'AlbUncertainty',
'Lprecipdepth', 'Lprecipquantity', 'LprecipSource',
'LprecipUncertainty', 'PresWth', 'PresWthSource',
'PresWthUncertainty']
mapping = dict(zip(raw_columns.split(','), new_columns))
return tmy3_dataframe.rename(columns=mapping) | bigcode/self-oss-instruct-sc2-concepts |
def get_insertion_excess(cigar):
"""Return excess insertions over deletions.
Using pysam cigartuples
sum all insertions and softclips (operation 1 and 4)
minus sum of all deletions (operation 2)
"""
return sum([l for o, l in cigar if o in [1, 4]]) - sum([l for o, l in cigar if o == 2]) | bigcode/self-oss-instruct-sc2-concepts |
def merge_pred_gt_boxes(pred_dict, gt_dict=None):
"""
Merge data from precomputed and ground-truth boxes dictionaries.
Args:
pred_dict (dict): a dict which maps from `frame_idx` to a list of `boxes`
and `labels`. Each `box` is a list of 4 box coordinates. `labels[i]` is
a list of labels for `boxes[i]`.
gt_dict (Optional[dict]): a dict which maps from `frame_idx` to a list of `boxes`
and `labels`. Each `box` is a list of 4 box coordinates. `labels[i]` is
a list of labels for `boxes[i]`. Note that label is -1 for predicted boxes.
Returns:
merged_dict (dict): merged dictionary from `pred_dict` and `gt_dict` if given.
It is a dict which maps from `frame_idx` to a list of [`is_gt`, `boxes`, `labels`],
where `is_gt` is a boolean indicate whether the `boxes` and `labels` are ground-truth.
"""
merged_dict = {}
for key, item in pred_dict.items():
merged_dict[key] = [[False, item[0], item[1]]]
if gt_dict is not None:
for key, item in gt_dict.items():
if merged_dict.get(key) is None:
merged_dict[key] = [[True, item[0], item[1]]]
else:
merged_dict[key].append([True, item[0], item[1]])
return merged_dict | bigcode/self-oss-instruct-sc2-concepts |
def _bop_and(obj1, obj2):
"""Boolean and."""
return bool(obj1) and bool(obj2) | bigcode/self-oss-instruct-sc2-concepts |
def b2h(num, suffix='B'):
"""Format file sizes as human readable.
https://stackoverflow.com/a/1094933
Parameters
----------
num : int
The number of bytes.
suffix : str, optional
(default: 'B')
Returns
-------
str
The human readable file size string.
Examples
--------
>>> b2h(2048)
'2.0kB'
"""
try:
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return '{0:3.1f}{1}{2}'.format(num, unit, suffix)
num /= 1024.0
return '{0:.1f}{1}{2}'.format(num, 'Y', suffix)
except:
return '-' | bigcode/self-oss-instruct-sc2-concepts |
def indent(string_in: str, tabs: int = 0):
"""Returns the str intended using spaces"""
return str(" " * tabs) + string_in | bigcode/self-oss-instruct-sc2-concepts |
def no_error_check(func_name, result, func, args):
"""Nothing special"""
return args | bigcode/self-oss-instruct-sc2-concepts |
import re
def br_with_n(text):
""" Replace br with \n """
return re.sub(r'<br.*?>','\n', text, flags=re.IGNORECASE) | bigcode/self-oss-instruct-sc2-concepts |
def S_M_to_mS_cm(CTM_S_M):
"""
Seabird eq: ctm [mS/cm] = ctm [S/m] * 10.0
"""
ctm_mS_cm = CTM_S_M * 10.0
return ctm_mS_cm | bigcode/self-oss-instruct-sc2-concepts |
import _ast
def Dict(keys=(), values=()):
"""Creates an _ast.Dict node. This represents a dict literal.
Args:
keys: A list of keys as nodes. Must be the same length as values.
values: A list of values as nodes. Must be the same length as values.
Raises:
ValueError: If len(keys) != len(values).
Returns:
An _ast.Dict node.
"""
if len(keys) != len(values):
raise ValueError(
'len(keys)={} != len(values)={}'.format(len(keys), len(values)))
return _ast.Dict(list(keys), list(values)) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def format_iso_date(d):
"""
If the parameter is datetime format as iso, otherwise returns the same value
"""
if type(d) is datetime:
return d.isoformat()
return d | bigcode/self-oss-instruct-sc2-concepts |
def local_scheme(version: str) -> str: # pylint: disable=unused-argument
"""Skip the local version (eg. +xyz) to upload to Test PyPI"""
return "" | bigcode/self-oss-instruct-sc2-concepts |
def cmp_dicts(dict1, dict2):
"""
Returns True if dict2 has all the keys and matching values as dict1.
List values are converted to tuples before comparing.
"""
result = True
for key, v1 in dict1.items():
result, v2 = key in dict2, dict2.get(key)
if result:
v1, v2 = (tuple(x) if isinstance(x, list) else x for x in [v1, v2])
result = (v1 == v2)
if not result:
break # break for key, v1
return result | bigcode/self-oss-instruct-sc2-concepts |
def breaklines(s, maxcol=80, after='', before='', strip=True):
"""
Break lines in a string.
Parameters
----------
s : str
The string.
maxcol : int
The maximum number of columns per line. It is not enforced when it is
not possible to break the line. Default 80.
after : str
Characters after which it is allowed to break the line, default none.
before : str
Characters before which it is allowed to break the line, default none.
strip : bool
If True (default), remove leading and trailing whitespace from each
line.
Return
------
lines : str
The string with line breaks inserted.
"""
pieces = [c for c in s[:1]]
for i in range(1, len(s)):
if s[i - 1] in after or s[i] in before:
pieces.append('')
pieces[-1] += s[i]
lines = [p for p in pieces[:1]]
for p in pieces[1:]:
if len(lines[-1]) + len(p) <= maxcol:
lines[-1] += p
else:
lines.append(p)
if strip:
lines = [line.strip() for line in lines]
return '\n'.join(lines) | bigcode/self-oss-instruct-sc2-concepts |
def sum_digits(n):
"""Recursively calculate the sum of the digits of 'n'
>>> sum_digits(7)
7
>>> sum_digits(30)
3
>>> sum_digits(228)
12
"""
"""BEGIN PROBLEM 2.4"""
return n % 10 + (0 if n < 10 else sum_digits(n // 10))
"""END PROBLEM 2.4""" | bigcode/self-oss-instruct-sc2-concepts |
import re
def escape(pathname: str) -> str:
"""Escape all special characters."""
return re.sub(r"([*?[\\])", r"[\1]", pathname) | bigcode/self-oss-instruct-sc2-concepts |
import requests
from bs4 import BeautifulSoup
import re
def get_apps_ids(play_store_url):
"""Scrape play store to gather App IDs.
Returns a list of App IDs
Keyword arguments:
play_store_url -- URL from a Play Store Search
:rtype: list
"""
page = requests.get(play_store_url)
soup = BeautifulSoup(page.content, 'html.parser')
link_elements = soup.find_all('a', class_='')
# Save unique App IDs on set (to avoid having to deduplicate)
app_ids = set()
app_id_regex_pattern = re.compile(r'/store/apps/details\?id=(.+)')
for link_element in link_elements:
if 'href' in link_element.attrs:
result = app_id_regex_pattern.search(link_element.attrs['href'])
if result is not None:
app_ids.add(result.group(1))
return list(app_ids) | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_config(path):
"""
Load the yaml file into a dictionary.
"""
with open(path) as f:
return yaml.load(f, Loader=yaml.FullLoader) | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalizeName(name):
"""Transforms a name to deal with common misspellings."""
# Only use the first of several names.
oneName = name.split(' ', 1)[0].lower()
REPLACEMENTS = [
['y$', 'a'], # Szczęsny = Szczęsna
['i$', 'a'], # Nowicki = Nowicka
['ę', 'e'],
['ą', 'a'],
['ó', 'o'],
['ł', 'l'],
['ś', 's'],
['ż', 'z'],
['ź', 'z'],
['ć', 'c'],
['ń', 'n'],
['rz', 'z'], # rz == ż
['en', 'e'], # en == ę
['em', 'e'], # em == ę
['on', 'a'], # on == ą
['om', 'a'], # om == ą
['u', 'o'], # u == ó
['x', 'ks'],
['tt', 't'],
['nn', 'n'],
['ff', 'f'],
['of', 'ow'],
['nka$', 'na'], # Irenka = Irena
]
for repl in REPLACEMENTS:
oneName = re.sub(repl[0], repl[1], oneName)
return oneName | bigcode/self-oss-instruct-sc2-concepts |
def join_query_keys(keys):
"""Helper to join keys to query."""
return ",".join(["\"{}\"".format(key) for key in keys]) | bigcode/self-oss-instruct-sc2-concepts |
def defaultparse(wordstags, rightbranching=False):
"""A default parse to generate when parsing fails.
:param rightbranching:
when True, return a right branching tree with NPs,
otherwise return all words under a single constituent 'NOPARSE'.
>>> print(defaultparse([('like','X'), ('this','X'), ('example', 'NN'),
... ('here','X')]))
(NOPARSE (X like) (X this) (NN example) (X here))
>>> print(defaultparse([('like','X'), ('this','X'), ('example', 'NN'),
... ('here','X')], True))
(NP (X like) (NP (X this) (NP (NN example) (NP (X here)))))"""
if rightbranching:
if wordstags[1:]:
return "(NP (%s %s) %s)" % (wordstags[0][1],
wordstags[0][0], defaultparse(wordstags[1:], rightbranching))
return "(NP (%s %s))" % wordstags[0][::-1]
return "(NOPARSE %s)" % ' '.join("(%s %s)" % a[::-1] for a in wordstags) | bigcode/self-oss-instruct-sc2-concepts |
def string_to_int(string):
"""
Problem 7.1
convert a string to an integer, without using `int`
"""
negative = string[0] == '-'
if negative:
string = string[1:]
idx = 0
output = 0
while idx < len(string):
low = ord(string[idx]) - ord('0')
output = (output * 10) + low
idx += 1
if negative:
output *= -1
return output | bigcode/self-oss-instruct-sc2-concepts |
def apply_LLD(spectrum, LLD=10):
"""
Applies a low level discriminator (LLD) to a channel.
Parameters:
-----------
spectrum : vector
The spectrum
LLD : int
The channel where the low level discriminator is applied
Returns:
--------
spectrum : vector
The spectrum with channels in the LLD set to 0
"""
spectrum[0:LLD] = 0
return spectrum | bigcode/self-oss-instruct-sc2-concepts |
def wants_json_resp(request):
"""
Decide whether the response should be in json format based on the request's
accept header.
Code taken from: http://flask.pocoo.org/snippets/45/
"""
best = request.accept_mimetypes.best_match(['application/json',
'text/html'])
return (
best == 'application/json' and
request.accept_mimetypes[best] > request.accept_mimetypes['text/html']) | bigcode/self-oss-instruct-sc2-concepts |
def route_business_logic(logicFn):
"""
Decorates a function to indicate the business logic that should be executed after security checks pass.
:param logicFn: The business logic function to assign.
:return: The decorated function.
"""
def decorator(fn):
fn.route_business_logic = logicFn
return fn
return decorator | bigcode/self-oss-instruct-sc2-concepts |
def _schema_sql_to_bq_compatibility(
schema_dict: dict
) -> dict:
"""
Convert sql schema to be compatible with the bq ui.
Args:
schema_dict: column name-sql column type as key-value pairs
e.g. {'uid': 'STRING', 'clicks': 'INTEGER'}
Returns:
schema_dict: column name-sql column type as key-value pairs
e.g. {'uid': 'STRING', 'clicks': 'INT64'}
"""
for k, v in schema_dict.items():
if v == "INTEGER":
schema_dict[k] = "INT64"
elif v == "FLOAT":
schema_dict[k] = "FLOAT64"
return schema_dict | bigcode/self-oss-instruct-sc2-concepts |
def nodes_within_bounds(indices, bounds):
"""
nodes_within_bounds filters a set of indices to those that are within the bounding box
:param indices: a set of indices
:param bounds: upper bounds for each axis, implicit minimum at 0
:return: filtered indices within bounds
"""
filtered = set()
for index in indices:
invalid = False
for axis in zip(index, bounds):
if axis[0] < 0 or axis[0] >= axis[1]:
invalid = True
if not invalid:
filtered.add(index)
return filtered | bigcode/self-oss-instruct-sc2-concepts |
def _GetRegionalGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.regionHealthChecks, 'Get',
client.messages.ComputeRegionHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project,
region=health_check_ref.region)) | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(name=None):
"""Return a logger to use"""
return logging.getLogger("dandi" + (".%s" % name if name else "")) | bigcode/self-oss-instruct-sc2-concepts |
def _divide_if_possible(x, y):
"""
EXAMPLES::
sage: from sage.combinat.free_module import _divide_if_possible
sage: _divide_if_possible(4, 2)
2
sage: _.parent()
Integer Ring
::
sage: _divide_if_possible(4, 3)
Traceback (most recent call last):
...
ValueError: 4 is not divisible by 3
"""
q, r = x.quo_rem(y)
if r != 0:
raise ValueError("%s is not divisible by %s"%(x, y))
else:
return q | bigcode/self-oss-instruct-sc2-concepts |
def make_progress_bar_text(percentage: float, bar_length: int = 2) -> str:
"""
Get the progress bar used by seasonal challenges and catalysts and more
Translations:
"A" -> Empty Emoji
"B" -> Empty Emoji with edge
"C" -> 1 Quarter Full Emoji
"D" -> 2 Quarter Full Emoji
"E" -> 3 Quarter Full Emoji
"F" -> 4 Quarter Full Emoji
"""
to_beat = 1 / bar_length / 4
bar_text = ""
for i in range(bar_length):
# 100%
if percentage >= (x := (to_beat * 4)):
bar_text += "F"
percentage -= x
# 75%
elif percentage >= (x := (to_beat * 3)):
bar_text += "E"
percentage -= x
# 50%
elif percentage >= (x := (to_beat * 2)):
bar_text += "D"
percentage -= x
# 25%
elif percentage >= (x := (to_beat * 1)):
bar_text += "C"
percentage -= x
# 0%
else:
# if it's the first one or the last one was empty too, set it to completely empty
if bar_text == "" or bar_text[-1:] != "F":
bar_text += "A"
# else keep the tiny edge
else:
bar_text += "B"
return bar_text | bigcode/self-oss-instruct-sc2-concepts |
import copy
def offset_bonds(bonds, offset):
"""
Offset all of the numbers in the bonds array by value
offset; useful for adding molecules to a system that's
already established because the bond arrays start at 0.
For a system with N atoms, all indices in the new molecule
to be added's bonds array need to be increased by N.
bonds : Psi-OMM Bonds Array
offset : Integer
number to increase indices in bonds by
Returns
-------
List of lists of lists in the form of the bonds array.
"""
bc = copy.deepcopy(bonds)
for b0 in bc[0]:
# Increment the indices at b0[0] and b0[1] by the offset.
b0[0] += offset
b0[1] += offset
for b1 in bc[1]:
# Increment every value in the list by offset.
for ix in range(len(b1)):
b1[ix] += offset
return bc | bigcode/self-oss-instruct-sc2-concepts |
def get_primitive_matrix_by_centring(centring):
"""Return primitive matrix corresponding to centring."""
if centring == "P":
return [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
elif centring == "F":
return [[0, 1.0 / 2, 1.0 / 2], [1.0 / 2, 0, 1.0 / 2], [1.0 / 2, 1.0 / 2, 0]]
elif centring == "I":
return [
[-1.0 / 2, 1.0 / 2, 1.0 / 2],
[1.0 / 2, -1.0 / 2, 1.0 / 2],
[1.0 / 2, 1.0 / 2, -1.0 / 2],
]
elif centring == "A":
return [[1, 0, 0], [0, 1.0 / 2, -1.0 / 2], [0, 1.0 / 2, 1.0 / 2]]
elif centring == "C":
return [[1.0 / 2, 1.0 / 2, 0], [-1.0 / 2, 1.0 / 2, 0], [0, 0, 1]]
elif centring == "R":
return [
[2.0 / 3, -1.0 / 3, -1.0 / 3],
[1.0 / 3, 1.0 / 3, -2.0 / 3],
[1.0 / 3, 1.0 / 3, 1.0 / 3],
]
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def _get_children(heap, idx):
"""Get the children index-value of the input index."""
length = len(heap)
idx_left = 2 * idx + 1
val_left = heap._idx2val(idx_left) if idx_left < length else None
idx_right = idx_left + 1
val_right = heap._idx2val(idx_right) if idx_right < length else None
return idx_left, val_left, idx_right, val_right | bigcode/self-oss-instruct-sc2-concepts |
def load_metadata_for_docs(conn_meta, query, split_metadata=False):
"""
loads the metadata for documents
@param conn_meta: connection to the database which includes PubMed metadata
@param query: the query to contain metadata (must project pmid and metadata)
@param split_metadata: if true the metadata attribute is first split and afterwise stored as a set
@return: a dict mapping a pmid to a set of metadata values
"""
cur = conn_meta.cursor()
cur.execute(query)
rows = cur.fetchall()
doc2meta = {}
for r in rows:
pmid, metadata = str(r[0]), str(r[1])
if split_metadata:
metadata = metadata.lower().split()
else:
# to avoid automatic splitting in sets
metadata = [metadata]
if pmid not in doc2meta:
doc2meta[pmid] = set()
doc2meta[pmid].update(metadata)
return doc2meta | bigcode/self-oss-instruct-sc2-concepts |
import getpass
def password(name, default=None):
"""
Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
rv = getpass.getpass(prompt)
if rv:
return rv
if default is not None:
return default | bigcode/self-oss-instruct-sc2-concepts |
def getPatternPercentage(df, column, pattern):
"""This function counts the number of df[column] which have the given pattern and returns the percentage based on the total number of rows."""
found = df.apply(lambda x: True if(isinstance(x[column], str) and x[column].startswith(pattern)) else False, axis=1).sum()
return (found*100)/len(df.index) | bigcode/self-oss-instruct-sc2-concepts |
import tempfile,gzip
def gunzip_string(string):
"""
Gunzip string contents.
:param string: a gzipped string
:return: a string
"""
with tempfile.NamedTemporaryFile() as f:
f.write(string)
f.flush()
g = gzip.open(f.name,'rb')
return g.read() | bigcode/self-oss-instruct-sc2-concepts |
def truncate_latitudes(ds, dp=10, lat_dim="lat"):
"""
Return provided array with latitudes truncated to specified dp.
This is necessary due to precision differences from running forecasts on
different systems
Parameters
----------
ds : xarray Dataset
A dataset with a latitude dimension
dp : int, optional
The number of decimal places to truncate at
lat_dim : str, optional
The name of the latitude dimension
"""
for dim in ds.dims:
if "lat" in dim:
ds = ds.assign_coords({dim: ds[dim].round(decimals=dp)})
return ds | bigcode/self-oss-instruct-sc2-concepts |
def RenamePredicate(e, old_name, new_name):
"""Renames predicate in a syntax tree."""
renames_count = 0
if isinstance(e, dict):
if 'predicate_name' in e and e['predicate_name'] == old_name:
e['predicate_name'] = new_name
renames_count += 1
# Field names are treated as predicate names for functors.
if 'field' in e and e['field'] == old_name:
e['field'] = new_name
renames_count += 1
if isinstance(e, dict):
for k in e:
if isinstance(e[k], dict) or isinstance(e[k], list):
renames_count += RenamePredicate(e[k], old_name, new_name)
if isinstance(e, list):
for idx in range(len(e)):
if isinstance(e[idx], dict) or isinstance(e[idx], list):
renames_count += RenamePredicate(e[idx], old_name, new_name)
return renames_count | bigcode/self-oss-instruct-sc2-concepts |
import pipes
def get_command_quoted(command):
"""Return shell quoted command string."""
return ' '.join(pipes.quote(part) for part in command) | bigcode/self-oss-instruct-sc2-concepts |
def divide_into_chunks(array, chunk_size):
"""Divide a given iterable into pieces of a given size
Args:
array (list or str or tuple): Subscriptable datatypes (containers)
chunk_size (int): Size of each piece (except possibly the last one)
Returns:
list or str or tuple: List of chunks
"""
return [array[i:i + chunk_size] for i in range(0, len(array), chunk_size)] | bigcode/self-oss-instruct-sc2-concepts |
def remove_italics(to_parse: str) -> str:
"""
A utility function for removing the italic HTML tags.
Parameters
----------
to_parse: str
The string to be cleaned.
Returns
-------
str
The cleaned string.
"""
return to_parse.replace("<i>", "").replace("</i>", "") | bigcode/self-oss-instruct-sc2-concepts |
def km_to_meters(kilometers):
"""
>>> km_to_meters(1)
1000.0
>>> km_to_meters(0)
0.0
>>> km_to_meters(-1)
Traceback (most recent call last):
ValueError: Argument must be not negative
>>> km_to_meters([1, 2])
Traceback (most recent call last):
TypeError: Invalid argument type
>>> km_to_meters('one')
Traceback (most recent call last):
TypeError: Invalid argument type
>>> km_to_meters(1.5)
1500.0
>>> km_to_meters(True)
Traceback (most recent call last):
TypeError: Invalid argument type
"""
if type(kilometers) not in {int, float}:
raise TypeError('Invalid argument type')
if kilometers < 0:
raise ValueError('Argument must be not negative')
return float(kilometers * 1000) | bigcode/self-oss-instruct-sc2-concepts |
def find_index(to_search, target):
"""Find the index of a value in a sequence"""
for index, value in enumerate(to_search):
if value == target:
return index
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def get_available_difficulties(metadata_record):
"""Gets the difficulty levels that are present for a song in a metadata record."""
levels = []
for key, value in metadata_record['metadata']['difficulties'].items():
if value == True or value == 'True':
levels.append(key)
return levels | bigcode/self-oss-instruct-sc2-concepts |
import math
def _map_tile_count(map_size: int, lod: int) -> int:
"""Return the number of map tiles for the given map.
Args:
map_size (int): The base map size in map units
lod (int): The LOD level for which to calculate the tile count
Returns:
int: The number of tiles in the given map's tile grid
"""
return math.ceil(4 ** (int(math.log2(map_size)) - 8 - lod)) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def delta_path(input_base_path: Path, item_path: Path, output_base_path: Path) -> Path:
"""
Removes a base path from an item, and appends result to an output path.
Parameters
----------
input_base_path : Path
The sub Path to be removed from item_path.
item_path : Path
The Path to be deltad
output_base_path : Path
The new base Path for item_path.
Returns
-------
Path
The new combined path.
Raises
------
ValueError
If input_base_path is not a sub Path of item_path.
"""
path_stub = item_path.relative_to(input_base_path)
output_item_path = output_base_path / path_stub
return output_item_path | bigcode/self-oss-instruct-sc2-concepts |
def mean_hr_bpm(num_beats, duration):
"""Average heart rate calculation
This is a simple function that converts seconds to minutes and divides
the total number of beats found by the total minutes in the strip.
:param num_beats: a single integer of the number of total beats in a strip
:param duration: a single float for the time duration of the strip
:returns: a single float of the average heart rate in the strip
"""
minutes = duration/60
mean_hr_bpm = num_beats/minutes
return mean_hr_bpm | bigcode/self-oss-instruct-sc2-concepts |
def is_pdb(datastr):
"""Detect if `datastr` if a PDB format v3 file."""
assert isinstance(datastr, str), \
f'`datastr` is not str: {type(datastr)} instead'
return bool(datastr.count('\nATOM ') > 0) | bigcode/self-oss-instruct-sc2-concepts |
def findall(sub, string):
"""
>>> text = "Allowed Hello Hollow"
>>> tuple(findall('ll', text))
(1, 10, 16)
"""
index = 0 - len(sub)
o = []
if not sub in string:
return []
while True:
try:
index = string.index(sub, index + len(sub))
except:
break
o.append(index)
return o
#except ValueError:
# pass | bigcode/self-oss-instruct-sc2-concepts |
def similar_exact(a, b):
"""Exact comparison between `a` and `b` strings."""
return a == b | bigcode/self-oss-instruct-sc2-concepts |
def make_wget(urls):
"""Download multiple URLs with `wget`
Parameters
----------
urls : list
A list of URLs to download from
"""
return 'wget -c {}'.format(' '.join(urls)) | bigcode/self-oss-instruct-sc2-concepts |
def text2hex(text):
""" Takes in a string text, returns the encoded text in hex."""
hex_string = " ".join(format(ord(x), "x") for x in text)
return hex_string | bigcode/self-oss-instruct-sc2-concepts |
def isascii(c):
"""Check if character c is a printable character, TAB, LF, or CR"""
try:
c = ord(c) # convert string character to decimal representation
except TypeError: # it's already an int? (Py3)
pass
return 32 <= c <= 127 or c in [9, 10, 13] | bigcode/self-oss-instruct-sc2-concepts |
def _format_syslog_config(cmd_ret):
"""
Helper function to format the stdout from the get_syslog_config function.
cmd_ret
The return dictionary that comes from a cmd.run_all call.
"""
ret_dict = {"success": cmd_ret["retcode"] == 0}
if cmd_ret["retcode"] != 0:
ret_dict["message"] = cmd_ret["stdout"]
else:
for line in cmd_ret["stdout"].splitlines():
line = line.strip()
cfgvars = line.split(": ")
key = cfgvars[0].strip()
value = cfgvars[1].strip()
ret_dict[key] = value
return ret_dict | bigcode/self-oss-instruct-sc2-concepts |
def get_versions(cfmclient):
"""
Function takes input cfmclient type object to authenticate against CFM API and queries
versions API to return the version number of the system represented by the CFCMclient object
Current supported params are
:param cfmclient: object of type CFMClient
:return: list of dicts
"""
path = 'versions'
response = cfmclient.get(path)
return response.json().get('result') if response else None | bigcode/self-oss-instruct-sc2-concepts |
import re
def matching_segment_range(segments, regexp, invert=False):
"""Returns a range object that yields the indices of those segments that
match 'regexp' from all segments that are returned by function
'segment_data'.
Args:
segments (list): List of segments as returned by function
'segment_data'.
regexp (string or regex object): the regular expression object or
string that has been used to divide the data into segments with
function 'segment_data'.
invert(boolean): If True, return the range of segments that do not
match regexp
Returns:
range object. Indices of the matching segments.
"""
if isinstance(regexp, str):
regexp = re.compile(regexp)
if invert:
return range(1 if regexp.match(segments[0]) else 0, len(segments), 2)
else:
return range(0 if regexp.match(segments[0]) else 1, len(segments), 2) | bigcode/self-oss-instruct-sc2-concepts |
def _is_equal_mne_montage(montage_a, montage_b, verbose="info"):
""" compare two mne montages for identity"""
# fall through for msgs when verbose=True
attrs_a = sorted(montage_a.__dict__.keys())
attrs_b = sorted(montage_b.__dict__.keys())
if not attrs_a == attrs_b:
if verbose:
msg = f"montage attributes differ: {attrs_a} {attrs_b}"
print(msg)
return False
# report the mismatches
for attr in attrs_a:
val_a = getattr(montage_a, attr)
val_b = getattr(montage_b, attr)
if val_a != val_b:
print(f"mismatch {attr} {val_a} != {val_b}")
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def get_std_color(client, color_type):
"""Get one of Creo's standard colors.
Args:
client (obj):
creopyson Client.
color_type (str):
Color type.
Valid values: letter, highlight, drawing, background, half_tone,
edge_highlight, dimmed, error, warning, sheetmetal, curve,
presel_highlight, selected, secondary_selected, preview,
secondary_preview, datum, quilt.
Returns:
(dict):
red (int): Red value (0-255)
green (int): Green value (0-255)
blue (int): Blue value (0-255)
"""
data = {"color_type": color_type}
return client._creoson_post("creo", "get_std_color", data) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def bth2bht(t: torch.Tensor) -> torch.Tensor:
"""Transpose the 2nd and 3rd dim of a tensor"""
return t.transpose(1, 2).contiguous() | bigcode/self-oss-instruct-sc2-concepts |
def epoch_span_overlap(span1, span2):
"""Find the overlap between two epoch spans.
Args:
span1 (tuple of Time): Range of epochs in increasing order.
span2 (tuple of Time): Range of epochs in increasing order.
Returns:
overlap_range (tuple of Time or None): Overlapping epoch range or None
if there is no overlap.
"""
max_start = max(span1[0], span2[0])
min_end = min(span1[1], span2[1])
if max_start < min_end:
overlap_range = (max_start, min_end)
else:
overlap_range = None
return overlap_range | bigcode/self-oss-instruct-sc2-concepts |
def _flatten(obj_to_vars):
"""
Object section is prefixed to variable names except the `general` section
[general]
warning = red
>> translates to: warning = red
[panel]
title = white
>> translates to: panel_title = white
"""
all_vars = dict()
for obj, vars_ in obj_to_vars.items():
if obj == 'general':
all_vars.update(vars_)
else:
all_vars.update({f"{obj}_{k}": v for k, v in vars_.items()})
return all_vars | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def marker_smoothing_exceptions(all_exceptions: Dict[str, Any], trial_name: str, marker_name: str) -> Dict[str, Any]:
"""Given all exceptions (all_exceptions) return just the ones for the specified marker (marker_name) and trial
(trial_name)."""
trial_exceptions = all_exceptions.get(trial_name, {})
return trial_exceptions.get(marker_name, {}) | bigcode/self-oss-instruct-sc2-concepts |
def clip_point(xmin, ymin, xmax, ymax, x, y):
"""Clips the point (i.e., determines if the point is in the clip
rectangle).
Parameters
----------
xmin, ymin, xmax, ymax, x, y : float
Returns
-------
bool
`True`, if the point is inside the clip rectangle; otherwise,
`False`.
"""
return xmin <= x <= xmax and ymin <= y <= ymax | bigcode/self-oss-instruct-sc2-concepts |
def get_fixed_hyperparams(parser):
""" Hyperparameters that remain fixed across all experiments """
parser.add_argument('--pred_logvar_domain', type=bool, default=True)
parser.add_argument('--use_l2_sigma_reg', type=bool, default=True)
parser.add_argument('--dataset', type=str, default='imagenet_bboxes')
parser.add_argument('--dataset_path', type=str, default='') # '/vision/group/CIFAR-10')
parser.add_argument('--num_classes', type=int, default=1000) # 10 for CIFAR-10
parser.add_argument('--std', type=float, default=0.02, help='for weight')
parser.add_argument('--weight_decay', default=1e-4, type=float)
parser.add_argument('--lr_decay_every', default=5, type=int, help='decay by 10 every n epoch') # or every 40
parser.add_argument('--num_epochs', type=int, default=200)
parser.add_argument('--print_every', type=int, default=100)
parser.add_argument('--use_bn', type=bool, default=True)
parser.add_argument('--cuda', type=bool, default=True)
parser.add_argument('--noise_mu', default=1.0, type=float)
parser.add_argument('--image_size', type=int, default=224) # 32 for cifar-10
parser.add_argument('--num_epochs_tolerate_no_acc_improv', type=int, default=5)
parser.add_argument('--use_identity_at_test_time', type=bool, default=True)
parser.add_argument('--share_conv_layers', type=bool, default=True)
parser.add_argument('--xstar_backprop_through_conv', type=bool, default=False)
# purely for the localization task
parser.add_argument('--new_localization_train_path', type=str, default='')
parser.add_argument('--new_localization_val_path', type=str, default='')
parser.add_argument('--new_localization_test_path', type=str, default='')
parser.add_argument('--new_localization_annotation_path', type=str, default='')
parser.add_argument('--num_imagenet_classes_to_use', type=int, default=1000)
parser.add_argument('--fc_size', type=int, default=4096 ) # CHANGE BACK TO 20
parser.add_argument('--momentum', default=0.9, type=float )
parser.add_argument('--num_workers', type=int, default=20) # CHANGE BACK TO 20
parser.add_argument('--ckpt_path', type=str, default='')
parser.add_argument('--percent_of_xstar_to_use_in_train', type=float,
default=100.0 )# )3.92 ) # ) # corresponds to 8,660 / 75k (* 100) to make it a percent
parser.add_argument('--info_dropout_activation_fn', type=str, default='softplus') # 'relu'
parser.add_argument('--sigma_regularization_multiplier', default=100.0, type=float)
# Normally, we want this to be true, unless generating random values
parser.add_argument('--use_python_random_seed', default=True, type=bool )
parser.add_argument('--use_full_imagenet', default=False, type=bool )
parser.add_argument('--percent_x_to_train_with', type=float, default=1.0) # 1.00 means 100%
parser.add_argument('--num_dropout_computations', type=int, default=2 )
parser.add_argument('--xstar_loss_multiplier', default=0.0, type=float)
parser.add_argument('--num_channels', type=int, default=3) # just use 1 for CIFAR-10
parser.add_argument('--use_dcgan_autoencoder', type=bool, default=False)
parser.add_argument('--start_num_encoder_filt', type=int, default=64)
parser.add_argument('--end_num_decoder_filt', type=int, default=64)
parser.add_argument('--max_grad_norm', type=float, default=10)
return parser | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_lower_from_list(upper_array_items: List[str]) -> List[str]:
"""
Convert a list/tuple objects to lower case character and return it.
"""
return list(map(lambda x: x.lower(), upper_array_items)) | bigcode/self-oss-instruct-sc2-concepts |
def format_date(date):
"""Converts date to string in d. m. Y format."""
return date.strftime('%d. %m. %Y').lower() | bigcode/self-oss-instruct-sc2-concepts |
def epsg_string_to_epsg(epsg_string: str) -> int:
"""From a string of the form 'EPSG:${code}' return
the epsg code as a integer
Raise a ValueError if the epsg_string cannot
be decoded
"""
epsg_string = epsg_string.lower()
epsg_string = epsg_string.strip()
epsg_string = epsg_string.replace("epsg:", "")
return int(epsg_string) | bigcode/self-oss-instruct-sc2-concepts |
def sl(c, s, l):
""" This accountancy function computes straight line
depreciation for an asset purchase for cash with
a known life span and salvage value.
c = historical cost or price paid (1000)
s = the expected salvage proceeds at disposal
l = expected useful life of the fixed asset
Example: sl(1000, 350, 10)
"""
return (c - s)/l | bigcode/self-oss-instruct-sc2-concepts |
import re
def natural_sort(iterable):
"""Sort an iterable by https://en.wikipedia.org/wiki/Natural_sort_order."""
def _convert(text):
return int(text) if text.isdigit() else text.lower()
def _alphanum_key(key):
return [_convert(c) for c in re.split("([0-9]+)", key)]
return sorted(iterable, key=_alphanum_key) | bigcode/self-oss-instruct-sc2-concepts |
def std_ver_major_uninst_valid_known(request):
"""Return a value that is a correctly formatted representation of a known major version number."""
return request.param | bigcode/self-oss-instruct-sc2-concepts |
def minimumDeletions(s: str) -> int:
"""Return minimum number of deletions to make 's' balanced, i.e.
no 'b' comes before 'a' in string consisting of just 'a's and 'b's."""
deletions = 0
countOfBs = 0
for c in s:
if c == 'a' and countOfBs > 0:
# Only need to delete 'b' if it comes before an 'a'.
countOfBs -= 1
deletions += 1
elif c == 'b':
# Keep track of number of 'b's seen.
countOfBs += 1
return deletions | bigcode/self-oss-instruct-sc2-concepts |
import copy
def dc(o):
"""
Some of the testing methods modify the datastructure you pass into them.
We want to deepcopy each structure so one test doesn't break another.
"""
return copy.deepcopy(o) | bigcode/self-oss-instruct-sc2-concepts |
import re
def cleantext(text):
"""
Custom function to clean enriched text
:param text(str): Enriched ytext from Ekstep Content.
:returns: Cleaned text.
"""
replace_char = [
"[",
"]",
"u'",
"None",
"Thank you",
"-",
"(",
")",
"#",
"Done",
">",
"<",
"-",
"|",
"/",
"\"",
"Hint",
"\n",
"'"]
for l in replace_char:
text = text.replace(l, "")
text = re.sub(' +', ' ', text)
return text | bigcode/self-oss-instruct-sc2-concepts |
def get_after(end_cursor):
""" Get the "after" portion of the pagination query
"""
return 'after: "{}", '.format(end_cursor) if end_cursor else "" | bigcode/self-oss-instruct-sc2-concepts |
def _and(queries):
"""
Returns a query item matching the "and" of all query items.
Args:
queries (List[str]): A list of query terms to and.
Returns:
The query string.
"""
if len(queries) == 1:
return queries[0]
return f"({' '.join(queries)})" | bigcode/self-oss-instruct-sc2-concepts |
def proto_check(proto):
"""Checks if protocol is TCP or UDP
Parameters
----------
proto: int
The protocol number in the FCN/CN message
Returns
-------
The protocol name if TCP/UDP else returns nothing
"""
# Check for TCP
if proto == 6:
return 'tcp'
# Check for UDP
elif proto == 17:
return 'udp'
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
def common_replacements(setting, item):
"""Maps keys to values from setting and item for replacing string
templates.
"""
return {"$name": setting.lower(),
"$setting": setting,
"$prettyname": item.py_name,
"$doc_str": item.doc_str} | bigcode/self-oss-instruct-sc2-concepts |
def loadStopWords(filename) :
"""
loads a Set of stopwords from a standard file
input :
file path containing stop words (format expected is one word per line)
return :
lines : a set of words
"""
lines = []
with open(filename,"r") as fileHandle:
for line in fileHandle.readlines() :
lines.append(line.strip())
return set(lines) | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def get_resource_bytes(path):
"""
Helper method to get the unicode contents of a resource in this repo.
Args:
path (str): The path of the resource
Returns:
unicode: The unicode contents of the resource at the given path
"""
resource_contents = pkg_resources.resource_string(__name__, path)
return resource_contents.decode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def first_match(predicate, list):
"""
returns the first value of predicate applied to list, which
does not return None
>>>
>>> def return_if_even(x):
... if x % 2 is 0:
... return x
... return None
>>>
>>> first_match(return_if_even, [1, 3, 4, 7])
4
>>> first_match(return_if_even, [1, 3, 5, 7])
>>>
:param predicate: a function that returns None or a value.
:param list: A list of items that can serve as input to ``predicate``.
:rtype: whatever ``predicate`` returns instead of None. (or None).
"""
for item in list:
val = predicate(item)
if val is not None:
return val
return None | bigcode/self-oss-instruct-sc2-concepts |
def split_data(msg, expected_fields):
"""
Helper method. gets a string and number of expected fields in it. Splits the string
using protocol's data field delimiter (|#) and validates that there are correct number of fields.
Returns: list of fields if all ok. If some error occured, returns None
"""
count=0
List=[]
temp_str=""
for x in msg:
if x=="#":
count+=1
List.append(temp_str)
temp_str=""
else:
temp_str=temp_str+x
if count==expected_fields:
List.append(temp_str)
return List
else:
return [None] | bigcode/self-oss-instruct-sc2-concepts |
def load_synapses_tsv_data(tsv_path):
"""Load synapse data from tsv.
Args:
tsv_path (str): path to the tsv synapses data file
Returns:
list of dicts containing each data for one synapse
"""
synapses = []
with open(tsv_path, "r", encoding="utf-8") as f:
# first line is dimensions
for line in f.readlines()[1:]:
syn = {}
items = line.strip().split("\t")
syn["sid"] = int(items[0])
syn["pre_cell_id"] = int(items[1])
syn["sectionlist_id"] = int(items[2])
syn["sectionlist_index"] = int(items[3])
syn["seg_x"] = float(items[4])
syn["synapse_type"] = int(items[5])
syn["dep"] = float(items[6])
syn["fac"] = float(items[7])
syn["use"] = float(items[8])
syn["tau_d"] = float(items[9])
syn["delay"] = float(items[10])
syn["weight"] = float(items[11])
syn["Nrrp"] = float(items[12])
syn["pre_mtype"] = int(items[13])
synapses.append(syn)
return synapses | bigcode/self-oss-instruct-sc2-concepts |
import torch
def softplus(x):
"""Alias for torch.nn.functional.softplus"""
return torch.nn.functional.softplus(x) | bigcode/self-oss-instruct-sc2-concepts |
def _index_name(self, name):
"""
Generate the name of the object in which to store index records
:param name: The name of the table
:type name: str
:return: A string representation of the full table name
:rtype: str
"""
return '_{}_{}'.format(self._name, name) | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
import torch
def transfer_data_to_numpy(data_map: dict) -> dict:
""" Transfer tensors in data_map to numpy type.
Will recursively walk through inner list, tuple and dict values.
Args:
data_map (dict): a dictionary which contains tensors to be transferred
Returns:
A dict which has same structure with input `data_map`.
"""
if not isinstance(data_map, dict):
return data_map
ret = OrderedDict()
for key, value in data_map.items():
if isinstance(value, torch.Tensor):
ret[key] = value.detach().cpu().numpy()
elif isinstance(value, dict):
ret[key] = transfer_data_to_numpy(value)
elif isinstance(value, (list, tuple)):
ret[key] = type(value)([transfer_data_to_numpy(t) for t in value])
else:
ret[key] = value
return ret | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def time_crop_or_pad_intensity_helper(metadata: Dict[str, Any]) -> float:
"""
Computes intensity of a transform that consists of temporal cropping or
padding. For these types of transforms the intensity is defined as the
percentage of video time that has been cut out (for cropping) or added
(for padding). When computing the percentage, the denominator should be
the longer of the src & dst durations so the resulting percentage isn't
greater than 100.
"""
dst_duration = metadata["dst_duration"]
src_duration = metadata["src_duration"]
larger_duration = max(src_duration, dst_duration)
return (abs(dst_duration - src_duration) / larger_duration) * 100.0 | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pickle(filepath_to_load):
"""Load pickle file"""
with open(filepath_to_load, "rb") as inp:
return pickle.load(inp) | bigcode/self-oss-instruct-sc2-concepts |
def _flattenText(elem):
"""
Returns the text in an element and all child elements, with the tags
removed.
"""
text = ""
if elem.text is not None:
text = elem.text
for ch in elem:
text += _flattenText(ch)
if ch.tail is not None:
text += ch.tail
return text | bigcode/self-oss-instruct-sc2-concepts |
import math
def distance(x1, y1, x2, y2, x0, y0):
"""Calculate distance from a point x0, y0 to a line defined by x1, y1 and x2, y2"""
num = (y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1
den = math.sqrt((y2 - y1) ** 2 + (x2 - x1) ** 2)
return float(num) / float(den) | 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.