seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def remove_namespace(xml):
"""
Strips the namespace from XML document contained in a string.
Returns the stripped string.
"""
regex = re.compile(' xmlns(:ns2)?="[^"]+"|(ns2:)|(xml:)')
return regex.sub("", xml) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_to_iso(date):
"""
Converts a datetime to the ISO8601 format, like: 2014-05-20T06:11:41.733900.
Parameters:
date -- a `datetime` instance.
"""
if not isinstance(date, datetime):
date = datetime.combine(date, datetime.min.time())
return dat... | bigcode/self-oss-instruct-sc2-concepts |
def mean(*args):
"""
Calculates the mean of a list of numbers
:param args: List of numbers
:return: The mean of a list of numbers
"""
index = 0
sum_index = 0
for i in args:
index += 1
sum_index += float(i)
return (sum_index / index) if index != 0 else "Division by z... | bigcode/self-oss-instruct-sc2-concepts |
def _expand_dim_specification(image_shape, dim_spec):
"""Expand mex dimension specification.
The dimension specification can be 2 or 3 long, it is
processed in two steps:
1. If it is of length 2, a -1 is prepended to it
2. Each dimension with -1 is replaced with the whole corresponding image dimens... | bigcode/self-oss-instruct-sc2-concepts |
def atttyp(att: str) -> str:
"""
Helper function to return attribute type as string.
:param str: attribute type e.g. 'U002'
:return: type of attribute as string e.g. 'U'
:rtype: str
"""
return att[0:1] | bigcode/self-oss-instruct-sc2-concepts |
def test_single_threaded_tree() -> list:
"""Return tree data for building a test single threaded tree."""
return [
(4, ""),
(1, ""),
(7, ""),
(3, ""),
(5, ""),
(8, ""),
(2, ""),
(6, ""),
] | bigcode/self-oss-instruct-sc2-concepts |
def createDictFromAttr(objList, attr):
"""\
Group the objects in objList based on their value for a specific attribute.
Return: A dict where each key is one of the values attested for the attribute. The value associated with each key is a list of objects whose value for attr was the same as the key.
Parameters:
... | bigcode/self-oss-instruct-sc2-concepts |
def normal_range(mean, sd, treshold=1.28):
"""
Returns a bottom and a top limit on a normal distribution portion based on a treshold.
Parameters
----------
treshold : float
maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = keeping 99%, 2.33... | bigcode/self-oss-instruct-sc2-concepts |
def grouping(df, col_name):
"""
:param df: Pandas DataFrame.
:param col_name: Name of column.
:return DataFrame grouped by given column with count aggregation function
"""
return df.groupby(col_name)['rating'].count() | bigcode/self-oss-instruct-sc2-concepts |
def has_shape(a):
"""Returns True if the input has the shape attribute, indicating that it is
of a numpy array type.
Note that this also applies to scalars in jax.jit decorated functions.
"""
try:
a.shape
return True
except AttributeError:
return False | bigcode/self-oss-instruct-sc2-concepts |
import logging
def stylesheets(soup=None):
"""Find stylesheet URLs in HTML code.
:param soup: The parsed HTML, defaults to None
:param soup: BeautifulSoup, optional
:return: All stylesheet URLs from link tags
:rtype: list
"""
if soup is None:
logging.info('⚠️ No HTML content avail... | bigcode/self-oss-instruct-sc2-concepts |
def build_traversal_spec(client_factory, name, type, path, skip,
select_set):
"""Builds the traversal spec object.
:param client_factory: Factory to get API input specs
:param name: Name for the traversal spec
:param type: Type of the managed object reference
:param path: P... | bigcode/self-oss-instruct-sc2-concepts |
def two_sum(target, ls):
"""
Check if two numbers within input array sum to target
"""
complements = set()
for num in ls:
if num in complements:
return True
complements.add(target - num)
return False | bigcode/self-oss-instruct-sc2-concepts |
def tuple_remove(tup, *items):
"""Return a copy of a tuple with some items removed.
:param tup: The tuple to be copied.
:param items: Any number of items. The first instance of each item will
be removed from the tuple.
"""
tuple_list = list(tup)
for item in items:
tuple_list.rem... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def stft3d(x: torch.Tensor, *args, **kwargs):
"""Multichannel functional wrapper for torch.stft
Args:
x (Tensor): audio waveform of
shape (nb_samples, nb_channels, nb_timesteps)
Returns:
STFT (Tensor): complex stft of
shape (nb_samples, nb_channels, nb... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def time_until(next_mins):
"""
Given N minutes, this function calculates the
timestamp (in UTC) when the Nth minute next occurs.
Example: If the time is 16:43:02 and we run time_until(15)
the string 17:15:00 will be returned.
Args:
next_mins (int): The n... | bigcode/self-oss-instruct-sc2-concepts |
def num_occurance_atob(a,b,df):
"""
find num occurance of activity a followed by activity b in dataframe df
args: a: activity number (dtype: int)
b: activity number (dtype: int)
df: dataframe (pandas) where a, b occur (must have ActivityID column)
returns: num_occurance (dtype: int... | bigcode/self-oss-instruct-sc2-concepts |
def createICDdictionary(filename):
"""This function takes the sorted_icd_codes file as an arg. and create the following dictionary:
ex. {'1': 'BEXT', '3': 'CALI', '2': 'BINT',....,'35': 'XTRN'}"""
fh = open(filename)
ICDdict = {}
for line in fh:
line = line.strip().split()
ICDdict[li... | bigcode/self-oss-instruct-sc2-concepts |
def files_changed(ctx):
"""
Return the list of file changed in the current branch compared to `master`
"""
changed_files = ctx.run('git diff --name-only master...', hide='out').stdout.splitlines()
# Remove empty lines
return [f for f in changed_files if f] | bigcode/self-oss-instruct-sc2-concepts |
def parse_payload_v1(event):
"""
Get HTTP request method/path/body for v1 payloads.
"""
body = event.get('body')
method = event.get('httpMethod')
try:
package, *_ = event['pathParameters']['package'].split('/')
except KeyError:
package = None
return (method, package, body... | bigcode/self-oss-instruct-sc2-concepts |
import json
def getConfigNames(xen, session, logger, ref):
"""
Return all config names associated with the given disk by reading the disk's other config in Xen.
:param logger: A logger used for logging possible errors.
:type logger: seealso:: :class:`logging:Logger`
:param ref: Xen reference of ... | bigcode/self-oss-instruct-sc2-concepts |
def initial_sigmoid_params(x, y):
"""Reasonable initial guesses for the parameters."""
b = 7.0 / max(x)
r = max(y)
m = (max(x) + min(x)) / 2.0
return [b, r, m] | bigcode/self-oss-instruct-sc2-concepts |
def s_hint(ans):
"""
:param ans: str, the answer for user to guess
:return: str, dashed version of "ans" to show number of character within this word as a hint for user
"""
hint = ''
for i in range(len(ans)):
hint += '-'
return hint | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
import calendar
def get_first_and_last_dates_of_month(month: int, year: int):
"""Return first and last dates for a given month and year."""
start_date = datetime.now().replace(day=1, year=year, month=month)
end_date = start_date.replace(day=calendar.monthrange(year=year, mont... | bigcode/self-oss-instruct-sc2-concepts |
def total_seconds(delta):
"""Return the total seconds of datetime.timedelta object.
Compute total seconds of datetime.timedelta, datetime.timedelta
doesn't have method total_seconds in Python2.6, calculate it manually.
"""
try:
return delta.total_seconds()
except AttributeError:
... | bigcode/self-oss-instruct-sc2-concepts |
def clean_value(value):
"""
Clean the value; if N/A or empty
:param value: original value
:return: cleaned value
"""
if value:
value = value.strip()
if value.lower() == 'n/a':
value = None
if value == '':
value = None
return value | bigcode/self-oss-instruct-sc2-concepts |
def update_keeper(keeper, next_point):
"""
Update values of the keeper dict.
"""
keeper["prev_point"] = keeper["curr_point"]
keeper["curr_point"] = next_point
keeper["coverage_path"].append(next_point)
# If everything works this conditional
# should evaluate to True always
if not ke... | bigcode/self-oss-instruct-sc2-concepts |
def id2trc(s_id, grid_dim):
"""
Convert state id to row, col, cell type
"""
t = s_id // (grid_dim[0] * grid_dim[1])
r = (s_id - t * grid_dim[0] * grid_dim[1]) // grid_dim[1]
c = (s_id - t * grid_dim[0] * grid_dim[1] - r * grid_dim[1]) // 1
return t, r, c | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import List
def indent(level: int, lines: Iterable[str]) -> List[str]:
"""
Indent the lines by the specified level.
"""
return [' ' * level + line for line in lines] | bigcode/self-oss-instruct-sc2-concepts |
def gaussian_kl(q, p):
"""
computes the KL divergence per batch between two Gaussian distributions
parameterized by q and p
Args:
q (list) Gaussian distribution parametrized by
q[0] (torch tensor): mean of q [batch_size, *latent_dims]
q[1] (torch tensor): varianc... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def make_features(x):
"""Builds features i.e. a matrix with colums [x,x^2,x^3]. """
x=x.unsqueeze(1)
return torch.cat([x**i for i in range(1,4)],1) | bigcode/self-oss-instruct-sc2-concepts |
def slice2gridspec(key):
"""Convert a 2-tuple of slices to start,stop,steps for x and y.
key -- (slice(ystart,ystop,ystep), slice(xtart, xstop, xstep))
For now, the only accepted step values are imaginary integers (interpreted
in the same way numpy.mgrid, etc. do).
"""
if ((len(key) != 2) or
... | bigcode/self-oss-instruct-sc2-concepts |
def make_shell_logfiles_url(host, shell_port, _, instance_id=None):
"""
Make the url for log-files in heron-shell
from the info stored in stmgr.
If no instance_id is provided, the link will
be to the dir for the whole container.
If shell port is not present, it returns None.
"""
if not shell_port:
r... | bigcode/self-oss-instruct-sc2-concepts |
def leaves(G):
"""
Return the nodes of G with out-degree zero in a list.
G-- nx.Digraph
return-- List of leaves nodes.
Example:
>>> G=random_dag(10,20)
>>> leaves_list=leaves(G)
>>> len(leaves_list)>0
True
>>> any([G.out_degree(x)>0 for x in leaves_list])
False
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def removeMacColons(macAddress):
""" Removes colon character from Mac Address """
return macAddress.replace(':', '') | bigcode/self-oss-instruct-sc2-concepts |
import torch
def load_model(load_path, net, device):
""" Loads a stored network with pytorch. """
checkpoint = torch.load(load_path, map_location=device)
net.load_state_dict(checkpoint)
net.to(device)
net.eval()
return net | bigcode/self-oss-instruct-sc2-concepts |
def prefix_strip(mystring, prefixes=["rust_"]):
""" strip passed in prefixes from the beginning of passed in string and return it
"""
if not isinstance(prefixes, list):
prefixes = [prefixes]
for prefix in prefixes:
if mystring.startswith(prefix):
return mystring[len(prefix):]... | bigcode/self-oss-instruct-sc2-concepts |
def method_available(klass, method):
"""Checks if the provided class supports and can call the provided method."""
return callable(getattr(klass, method, None)) | bigcode/self-oss-instruct-sc2-concepts |
def punnettParse(s : str) -> list:
"""Take a str and turn it into a list of strings punnett can accept"""
if len(s) % 2: raise ValueError('Even number of alleles required')
return ["".join(sorted(s[i:i+2])) for i in range(0,len(s),2)] | bigcode/self-oss-instruct-sc2-concepts |
def str_month(month):
"""Transforms datetime month object into a "%m/%y" string.
Args:
month (datetime/datetime.date): Month.
Returns:
A "%m/%y" string representation.
"""
return month.strftime("%m/%y") | bigcode/self-oss-instruct-sc2-concepts |
def _ReadCsv(path):
"""Returns the contents of the .csv as a list of (int, int)."""
ret = []
with open(path) as f:
for line in f:
parts = line.rstrip().split(',')
if len(parts) == 2 and parts[0] != 'revision':
ret.append((int(parts[0]), int(float(parts[1]))))
return ret | bigcode/self-oss-instruct-sc2-concepts |
import requests
def getJson(url):
"""
HTTP GET request
:param url: - api url
:return: - json object, if response status is OK
"""
response = requests.get(url)
if response.status_code == 200:
return response.text
raise Exception(response.text) | bigcode/self-oss-instruct-sc2-concepts |
def mt_loss(theta, R, beta):
"""Compute objective function for multi task group lasso."""
n_samples = len(R)
obj = 0.
for n in range(n_samples):
obj += R[n] ** 2
obj *= 0.5
return obj | bigcode/self-oss-instruct-sc2-concepts |
import re
def RemoveMatchingTests(test_output, pattern):
"""Removes output of specified tests from a Google Test program's output.
This function strips not only the beginning and the end of a test but also
all output in between.
Args:
test_output: A string containing the test output.
pattern: ... | bigcode/self-oss-instruct-sc2-concepts |
def reconcile_countries_by_code(codeinfo, plot_countries, gdp_countries):
"""
Inputs:
codeinfo - A country code information dictionary
plot_countries - Dictionary whose keys are plot library country codes
and values are the corresponding country name
gdp_countries ... | bigcode/self-oss-instruct-sc2-concepts |
def is_cdap_entity_role(role):
"""
CDAP create roles for entities by default. These roles are in the format of '.namespace', '.program' etc.
:param role: The role to judge
:return: bool: if role is a cdap entity role
"""
return role['name'].startswith(('.artifact', '.application', '.program', '.dataset', 's... | bigcode/self-oss-instruct-sc2-concepts |
def islice(vals, inds):
"""Returns a list of values from `vals` at the indices in `inds`."""
sliced = []
for (i, v) in enumerate(vals):
if i in inds:
sliced.append(v)
return sliced | bigcode/self-oss-instruct-sc2-concepts |
def merge_ranges(ranges):
"""Merge short, fragmental ranges into long, continuous ones.
Parameters
----------
ranges : list of int
Ranges to merge.
Returns
-------
list of int
Merged ranges.
Notes
-----
Ranges that have overlaps will be merged into one. For exa... | bigcode/self-oss-instruct-sc2-concepts |
def crop_border(img_list, crop_border):
"""Crop borders of images
Args:
img_list (list [Numpy]): HWC
crop_border (int): crop border for each end of height and weight
Returns:
(list [Numpy]): cropped image list
"""
if crop_border == 0:
return img_list
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def argmax(x):
"""
Arg max of a torch tensor (2 dimensional, dim=1)
:param x: torch tensor
:return: index the of the max
"""
return torch.max(x, dim=1)[1] | bigcode/self-oss-instruct-sc2-concepts |
def nos_unknown_host_cb(host, fingerprint):
"""An unknown host callback.
Returns `True` if it finds the key acceptable,
and `False` if not. This default callback for NOS always returns 'True'
(i.e. trusts all hosts for now).
"""
return True | bigcode/self-oss-instruct-sc2-concepts |
async def async_handle_google_actions(cloud, payload):
"""Handle an incoming IoT message for Google Actions."""
return await cloud.client.async_google_message(payload) | bigcode/self-oss-instruct-sc2-concepts |
def check_status(status):
"""
A little helper function that checks an API error code and returns a nice message.
Returns None if no errors found
"""
if status == 'REQUEST_DENIED':
return 'The geocode API is off in the Google Developers Console.'
elif status == 'ZERO_RESULTS':
ret... | bigcode/self-oss-instruct-sc2-concepts |
def surface_area(l, w, h):
"""Return the total surface area of a box"""
return (2 * l * w) + (2 * w * h) + (2 * h * l) | bigcode/self-oss-instruct-sc2-concepts |
def get(isdsAppliance, check_mode=False, force=False):
"""
Get information on existing snapshots
"""
return isdsAppliance.invoke_get("Retrieving snapshots", "/snapshots") | bigcode/self-oss-instruct-sc2-concepts |
def solidity_library_symbol(library_name):
""" Return the symbol used in the bytecode to represent the `library_name`. """
# the symbol is always 40 characters in length with the minimum of two
# leading and trailing underscores
length = min(len(library_name), 36)
library_piece = library_name[:leng... | bigcode/self-oss-instruct-sc2-concepts |
def hostname_valid(hostname):
""" Test if specified hostname should be considered valid
Args:
hostname (str): hostname to test
Returns:
bool: True if valid, otherwise False
"""
if (not hostname or
hostname.startswith('localhost') or
hostname.e... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def global_integration_cli_args(integration_config_paths):
"""
The first arguments to pass to a cli command for integration test configuration.
"""
# List of a config files in order.
return list(itertools.chain(*(('--config_file', f) for f in integration_config_paths))) | bigcode/self-oss-instruct-sc2-concepts |
def euclidean_dist_vec(y1, x1, y2, x2):
"""
Calculate Euclidean distances between pairs of points.
Vectorized function to calculate the Euclidean distance between two
points' coordinates or between arrays of points' coordinates. For accurate
results, use projected coordinates rather than decimal de... | bigcode/self-oss-instruct-sc2-concepts |
def streak_next(values, i):
"""Given a list of numbers, skip forward over consecutive streaks
Used by DfView.find()
If i references a value within a consecutive streak, the value
returned will be the index of the end of the streak. If i references
a value at the end of a streak, the value retu... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def epoch_to_date(s):
""" UNIX epoch timestamp in string or float to datetime object """
return datetime.utcfromtimestamp(float(s)) | bigcode/self-oss-instruct-sc2-concepts |
def clean_matrix_U_invalid_object_id(_U):
"""
in pipeline object_ids that couldn't be processed and end up having no OBJID ('')
should be removed
:param _U:
:return: invalid records from _U where OBJID missing
"""
return _U[_U.OBJID != ""] | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_timezone(timezone: str) -> float:
"""Parse timezone to offset."""
match = re.match(
r"^(?P<sign>[-+])(?P<hours>\d{1,2}):(?P<minutes>\d{1,2})$", timezone
)
if match:
if match.group("sign") == "-":
sign = -1.0
else:
sign = 1.0
r... | bigcode/self-oss-instruct-sc2-concepts |
def _confirm_no_logfile_not_web_flac(params):
"""
Gazelle trackers require a logfile for lossless releases
If no logfile is indicated, ask if the user wants to change the release
type to "web" (no logfile required), ignore the lack of logfile and
continue the upload or cancel it
:returns conti... | bigcode/self-oss-instruct-sc2-concepts |
def roc_to_common_era(date: str):
"""Turn ROC era string to common era
e.g. 105/01/01 -> 2016/01/01
"""
year = int(date[:3]) + 1911
return f"{year}{date[3:]}" | bigcode/self-oss-instruct-sc2-concepts |
def inv_min_max_norm(x, min_x, max_x):
"""
Computes the inverse min-max-norm of input x with minimum min_x and maximum max_x.
"""
return x * (max_x - min_x) + min_x | bigcode/self-oss-instruct-sc2-concepts |
def is_top(module_index):
"""Returns True if module is in the top cap"""
return ( (module_index>=736)&(module_index<832) ) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
from typing import Any
def prepare_queue_details_get_output(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Prepares context output for queue_details_get command.
:param records: List containing dictionaries of queue records.
:return: prepar... | bigcode/self-oss-instruct-sc2-concepts |
def _get_histogram_settings(agg):
"""
Get the settings for a histogram aggregation
:param agg: the histogram aggregation json data
:return: dict of {setting_name: setting_value}
"""
histogram_settings = dict(field=agg['field'])
settings = agg['settings']
histogram_settings['interval'] ... | bigcode/self-oss-instruct-sc2-concepts |
def escaped(val):
""" escapes a string to allow injecting it into a json conf """
val = val.replace('\\', '/')
val = val.replace('"', '\"')
return val | bigcode/self-oss-instruct-sc2-concepts |
def calc_an_sparsity(L, q, K):
"""Calculates sparsity of Adjacent Neighborhood scheme"""
return 1 + L*(q-1)*q**(K-1) | bigcode/self-oss-instruct-sc2-concepts |
def rightjustify(linetext, linecount, max_countwidth):
"""Justify ordered line to the right
Arguments:
linetext {str} -- a text to justify
linecount {int} -- a line count (1-based)
max_countwidth {int} -- a maximum count width
Returns:
str -- a justified line
"""
fi... | bigcode/self-oss-instruct-sc2-concepts |
def getInputs(tx):
"""
The getInputs function is a small helper function that returns
input addresses for a given transaction
:param tx: A single instance of a Bitcoin transaction
:return: inputs, a list of inputs
"""
inputs = []
for input_addr in tx['inputs']:
inputs.append(... | bigcode/self-oss-instruct-sc2-concepts |
import json
import codecs
def write_json(filename, obj):
"""Write JSON."""
fail = False
try:
j = json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
with codecs.open(filename, 'w', encoding='utf-8') as f:
f.write(j + "\n")
except Exception:
fail = Tr... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_amp_references(txt: str) -> str:
"""Remove references to amp."""
txt = re.sub("^amp/", "", txt, flags=re.MULTILINE)
txt = re.sub("/amp/", "/", txt, flags=re.MULTILINE)
txt = re.sub("/amp:", ":", txt, flags=re.MULTILINE)
return txt | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def list_run(dname):
"""List all .dat files in a directory."""
path = Path(dname)
return sorted(list(path.glob('*.dat'))) | bigcode/self-oss-instruct-sc2-concepts |
def residue_points(m):
"""Return a dictionary with each residue and the numbers that produce it"""
D = {}
for i in range(m):
r = (i**2) % m
if str(r) in D:
D[str(r)].append(i)
else:
D[str(r)] = [i]
return D | bigcode/self-oss-instruct-sc2-concepts |
def transpose(matlist, K):
"""
Returns the transpose of a matrix
Examples
========
>>> from sympy.matrices.densetools import transpose
>>> from sympy import ZZ
>>> a = [
... [ZZ(3), ZZ(7), ZZ(4)],
... [ZZ(2), ZZ(4), ZZ(5)],
... [ZZ(6), ZZ(2), ZZ(3)]]
>>> transpose(a, ZZ)
... | bigcode/self-oss-instruct-sc2-concepts |
def _block_len_in_section(block, section):
"""Return the length of a block in a section [start, end]."""
len_start = max(block.start, section.start)
len_end = min(block.end, section.end)
return len_end - len_start + 1 | bigcode/self-oss-instruct-sc2-concepts |
def wrap(command: bytes):
"""
Wrap the given command into the padding bytes \x02 and \x03
:param command: bytes
:return: padded command: bytes
"""
start = b"\x02"
stop = b"\x03"
return start + command + stop | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import yaml
from functools import reduce
def get_config_value(keys: str) -> Any:
"""Retrieves a configuration value from the Pavo configuration file.
Args:
keys (str): The string of (nested) dictionary values.
Note:
You can find nested keys by introducing '.' in yo... | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_exponential_backoff_interval(
factor,
retries,
maximum,
full_jitter=False
):
"""Calculate the exponential backoff wait time."""
# Will be zero if factor equals 0
countdown = min(maximum, factor * (2 ** retries))
# Full jitter according to
# https://www.awsarch... | bigcode/self-oss-instruct-sc2-concepts |
def split_namespace(tag):
"""returns a tuple of (namespace,name) removing any fragment id
from namespace"""
if tag[:1] == "{":
namespace, name = tag[1:].split("}", 1)
return namespace.split("#")[0], name
else:
return (None, tag) | bigcode/self-oss-instruct-sc2-concepts |
import re
def replace_unescaped_utf_8_chars(input_text):
"""
Unescapes characters like "ä" with their equivalents,
e.g. "ö". Only necessary to support Python 2.7+.
"""
pattern = re.compile(r"�(\w{2});�(\w{2});")
def replace(match):
byte_array = bytearray(map(lam... | bigcode/self-oss-instruct-sc2-concepts |
def make_dnp(pid: int, gid: int, team: int) -> list:
"""Player was labeled DNP (Did Not Play)
:param pid: (int) Player ID
:param gid: (int) Game ID
:param team: (int) Team ID
:return: (lst) Player Stats
"""
player_stat = []
player_stat.append(pid) # Player ID
player_stat.app... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_substr_index(ls_string: List[str], substring: str) -> int:
"""
Parameters
----------
ls_string : list of strings to find the substring in
substring : the substring
Returns
-------
int of index of the first substr match in the list, -1 if the substr does... | bigcode/self-oss-instruct-sc2-concepts |
import heapq
def find_k_largest_numbers(nums: list[int], k: int) -> list[int]:
"""
Complexity:
Time: O(nlogk)
Space O(k)
Args:
nums: array of numbers for which to find the largest k elements
k: num largest elements to find
Returns: the k largest elements in `nums`
... | bigcode/self-oss-instruct-sc2-concepts |
def valid_age(person, i, min_age):
"""Verify age requirement of person in given iteration."""
return person["birth"] <= (i - min_age) and person["death"] >= i | bigcode/self-oss-instruct-sc2-concepts |
def narrow(checked, DASHRlut):
"""Returns dictionary mapping selected DASHRs to local drives.
:param checked: array of integer pins
:param DASHRlut: dictionary mapping of all locally detected DASHRs
:returns: dictionary mapping only user-selected DASHRs
"""
for_harvest = {}
for pin in check... | bigcode/self-oss-instruct-sc2-concepts |
def factorial_pythonic(number: int) -> int:
"""Factorial with reduce function (pythonic approach).
Examples:
>>> assert factorial_pythonic(0) == 1
>>> assert factorial_pythonic(1) == 1
>>> assert factorial_pythonic(2) == 2
>>> assert factorial_pythonic(3) == 6
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
import re
def camelcase_to_snakecase(_str: str) -> str:
"""camelcase_to_snakecase.
Transform a camelcase string to snakecase
Args:
_str (str): String to apply transformation.
Returns:
str: Transformed string
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', _str)
return re.sub... | bigcode/self-oss-instruct-sc2-concepts |
def assign(domino_set):
"""Assigns 7 domino pieces to each player and returns each players set of tiles and the list of remaining tiles"""
player_hand = []
computer_hand = []
for _ in range(7):
player_hand += [domino_set.pop()]
computer_hand += [domino_set.pop()]
return player_hand,... | bigcode/self-oss-instruct-sc2-concepts |
def order_slaves_on_gtid(slaves):
"""Function: order_slaves_on_gtid
Description: Take a Slave array and sort them on their GTID positions,
with the top(first) slave being the best Slave.
Arguments:
(input) slaves -> Slave instance array.
(output) slave_list -> List of slaves in ... | bigcode/self-oss-instruct-sc2-concepts |
def clean_sheet_value(value):
"""
Takes a spreadsheet cell value and returns a cleaned version
Args:
value (str): A raw spreadsheet cell value
Returns:
str or None: A string with whitespace stripped, or None if the resulting value was an empty string
"""
stripped = value.strip(... | bigcode/self-oss-instruct-sc2-concepts |
def my_formatter_1f(x,p):
"""Format tick marks to have 1 significant figure."""
return "%.1f" % (x) | bigcode/self-oss-instruct-sc2-concepts |
def scurve(start,end,n,s):
"""Return an S-Curve with a constant velocity section from start to end with
n points. The start and end S-curves each have s points"""
ys,ye = start,end
s1 = [ (ye-ys)*(x*x-s*s)/(2*s*float(n-1))+ys for x in range(0,s) ]
cv = [ (ye-ys)*(x-s)/float(n-1)+ys for x in range(s,s+n) ]
s2 = [ ... | bigcode/self-oss-instruct-sc2-concepts |
def sort_files(files):
"""Sort a list of file names.
Parameters
----------
files : list of str
List of file names, to sort.
Returns
-------
list of str
Sorted list of files.
"""
return sorted(files) | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_99_percent_confidence(margin_of_error):
"""
Converts a margin of error from the U.S. Census Bureau to the 99% confidence level.
Args:
margin_or_error (float): A margin of error at the bureau's standard 90% confidence level
Returns:
The adjusted margin of error (float).
... | bigcode/self-oss-instruct-sc2-concepts |
def awk(s: str, n: int, d: str = ' ') -> str:
"""Act like awk and select the nth element
Args:
s: string to split up
n: the element to select
d: the delimiter between elements
Returns:
"""
split = s.strip().split(d)
if len(split) >= n:
# awk is 1-indexed
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def ReadFile(f, tsv=False):
"""Read the CSV file, returning the column names and rows."""
if tsv:
c = csv.reader(f, delimiter='\t', doublequote=False,
quoting=csv.QUOTE_NONE)
else:
c = csv.reader(f)
# The first row of the CSV is assumed to be a header. The rest are dat... | 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.