seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import math
def make_line ( length ):
"""
Creates a list of bit strings of at least the given length, such
that the bit strings are all unique and consecutive strings
differ on only one bit.
Args:
length (int): Required length of output list.
Returns:
line (list): Lis... | bigcode/self-oss-instruct-sc2-concepts |
def min_max_vals(vals):
"""
:param vals: an iterable such as list
:return: a tuple in which the first item is the minimum value from the iterable,
and the second item is the maximum value from the iterable
"""
sorted_vals = sorted(vals)
return sorted_vals[0], sorted_vals[-1] | bigcode/self-oss-instruct-sc2-concepts |
def neighbors(i, j, m, n):
"""
Returns the neighboring indices for a given index
in a matrix of m x n shape
"""
# Sets default delta indices
# Adjust delta indices for given index on edge of matrix
inbrs = [-1, 0, 1]
if i == 0:
inbrs = [0, 1]
if i == m-1:
inbrs = [-1... | bigcode/self-oss-instruct-sc2-concepts |
def skip_if(condition):
"""Skips the decorated function if condition is or evaluates to True.
Args:
condition: Either an expression that can be used in "if not condition"
statement, or a callable whose result should be a boolean.
Returns:
The wrapped function
"""
def real_skip_if(fn):
de... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def checkopen(meth):
"""Verify that the file is open before applying a file method. Raises
ValueError if the file is closed.
"""
def wrapper(self, *args, **kw):
if self.handle is None:
raise ValueError("I/O operation on closed file")
return meth(self, *arg... | bigcode/self-oss-instruct-sc2-concepts |
def distance(a, b):
"""Calculate the distance between two points a and b."""
return ((a[0] - b[0])**2 + (a[1] - b[1])**2)**0.5 | bigcode/self-oss-instruct-sc2-concepts |
import logging
def setup_logger(
log_fp=None,
log_stdout=True,
log_format="%(asctime)s %(levelname)-8s [Workbench] %(message)s"
):
"""
Set up and return a logging instance.
Logs will be printed to standard out by default (with log_stdout=True).
If `log_fp` is provided, logs will also be ap... | bigcode/self-oss-instruct-sc2-concepts |
import re
def unir_fragmentos(texto):
"""Une fragmentos de palabras partidas por final de línea.
Parameters
----------
texto : str
Returns
-------
str
Texto con palabras de fin de línea unidas si estaban partidas.
"""
# Asume ord('-') == 45
return re.sub(r'-\n+', '', ... | bigcode/self-oss-instruct-sc2-concepts |
def center_crop(data, crop_shape, labels=None):
"""
Perform random cropping after optional padding
Args:
data: data array representing 1 image [h, w]
labels: labels array [h, w, 2] (unique values limited to (0, 1)), could be None
crop_shape: target shape after cropping
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def create_point_datatype(records):
"""
Creates point datatype to enable fetching GeoJSON from Socrata
:param records: list - List of record dicts
"""
for record in records:
latitude = record["latitude"]
longitude = record["longitude"]
# Socrata rejects point upserts with no ... | bigcode/self-oss-instruct-sc2-concepts |
def _pad_jagged_sequence(seq):
"""
Pads a 2D jagged sequence with the default value of the element type to make it rectangular.
The type of each sequence (tuple, list, etc) is maintained.
"""
columns = max(map(len, seq)) # gets length of the longest row
return type(seq)(
(
... | bigcode/self-oss-instruct-sc2-concepts |
def get_league_scoreboards(league, week):
"""
Returns the scoreboards from the specified sleeper league.
:param league: Object league
:param week: Int week to get the scoreboards of
:return: dictionary of the scoreboards;
https://github.com/SwapnikKatkoori/sleeper-api-wrapper#get_scoreboards... | bigcode/self-oss-instruct-sc2-concepts |
def true_param(p):
"""Check if ``p`` is a parameter name, not a limit/error/fix attributes."""
return (
not p.startswith("limit_")
and not p.startswith("error_")
and not p.startswith("fix_")
) | bigcode/self-oss-instruct-sc2-concepts |
def rotate180_augment(is_training=True, **kwargs):
"""Applies rotation by 180 degree."""
del kwargs
if is_training:
return [('rotate180', {})]
return [] | bigcode/self-oss-instruct-sc2-concepts |
def flatten(nested_list):
"""
Called by loanpy.adrc.Adrc.repair_phonotactics and loanpy.adrc.Adrc.adapt.
Flatten a nested list and discard empty strings (to prevent feeding \
empty strings to loanpy.adrc.Adrc.reconstruct, which would throw an Error)
:param nested_list: a nested list
:type nested_li... | bigcode/self-oss-instruct-sc2-concepts |
def buildCircuit(circuit_string, parameters, frequencies):
""" transforms a circuit_string, parameters, and frequencies into a string
that can be evaluated
Parameters
----------
circuit_string : str
parameters : list of floats
frequencies : list of floats
Returns
-------
eval_s... | bigcode/self-oss-instruct-sc2-concepts |
def fix_location_header(request, response):
"""
Ensures that we always use an absolute URI in any location header in the
response. This is required by RFC 2616, section 14.30.
Code constructing response objects is free to insert relative paths, as
this function converts them to absolute paths.
... | bigcode/self-oss-instruct-sc2-concepts |
def distance_between_sq(x1: float, y1: float, x2: float, y2: float) -> float:
"""
Returns the squared distance between the two points (x1, y1) and (x2, y2)
"""
dx = x2 - x1
dy = y2 - y1
return dx**2 + dy**2 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def round_coordinates(data: Any) -> Any:
"""Recursively round lat,lon floats to 2 digits"""
if isinstance(data, dict):
for key, val in data.items():
if key in ("lat", "lon"):
data[key] = round(val, 2)
else:
data[key] = roun... | bigcode/self-oss-instruct-sc2-concepts |
def create_dummy_class(klass, dependency, message=""):
"""
When a dependency of a class is not available, create a dummy class which throws ImportError
when used.
Args:
klass (str): name of the class.
dependency (str): name of the dependency.
message: extra message to print
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_remote_msg(msg):
""" Figure out the different components of the output of the remote script.
Arguments
---------
msg: str
Unicode string that encodes the output.
Returns
-------
error_msg: str
List of error messages, empty list means no errors.
exe... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_releasability(releasability, user_sources):
"""
Remove any releasability that is for sources a user does not have access to
see.
:param releasability: The releasability list for a top-level object.
:type releasability: list
:param user_sources: The sources a user has access to.
... | bigcode/self-oss-instruct-sc2-concepts |
def _trim_comment(line) -> str:
"""Remove comment from end of line, if any"""
if '#' in line:
icomment = line.index('#')
line = line[:icomment]
return line | bigcode/self-oss-instruct-sc2-concepts |
def cutout_subimage(image2d,
startx=0,
starty=0,
width=100,
height=200):
"""Cutout a subimage ot of a bigger image
:param image2d: the original image
:type image2d: NumPy.Array
:param startx: startx, defaults to 0
:type... | bigcode/self-oss-instruct-sc2-concepts |
def calc_sums(variable):
"""
Aggregates the instance dimension of the variable tensor object (see documentation in ../process_raw_data.py)
by summing up the values of the instances.
note: this function is called after the database check -> all values are available and valid.
:param variable: data s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
import requests
def get_cluster_status() -> Dict[str, Any]:
"""
Returns the Spark cluster status
:return: Dict[str, Any]
"""
spark_status_url = "http://localhost:8080/json/"
r = requests.get(url=spark_status_url)
return r.json() | bigcode/self-oss-instruct-sc2-concepts |
def test(
name: int = 1) -> int:
"""
参数名后跟冒号,冒号后的内容为type hint,表示建议的参数类型,也可以正常赋予默认值,如上所示
括号外的部分用 -> 随后跟随的为返回结果的type hint,表示对结果的建议类型
:param name:
:return:
"""
print(type(name))
print(name)
return name + 2; | bigcode/self-oss-instruct-sc2-concepts |
def list_to_str(lst, item_len=1):
"""Format lists as ,(;) separated strings."""
if item_len == 1:
if lst:
return ",".join(str(lst_itm) for lst_itm in lst)
else:
return "None"
else:
joined_items = []
for sub_lst in lst:
joined_items.append("... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def calculate_adr(bars):
"""
Given a series of bars from the IB client, calculates the ADR
"""
total = reduce(
lambda acc, bar: acc + (bar.high / bar.low),
bars,
0)
return round(100 * ((total / len(bars)) - 1), 1) | bigcode/self-oss-instruct-sc2-concepts |
def set_io_tile_options(opts,
num_io_tiles,
place_ops_on_io_tiles=None,
io_tile_available_memory_proportion=0.9):
"""Set the number of tiles reserved for I/O per IPU.
Args:
num_io_tiles: Number of tiles to reserve I/O.
place_ops_on_io_... | bigcode/self-oss-instruct-sc2-concepts |
def rhog(mw, p, tk):
"""
Calculate gas density from molecular weight, pressure, and temperature.
Parameters
----------
mw : float
Molecular weight of gas [g/mol]
p : float
Pressure of the gas [Pa]
tk : float
Temperature of the gas [K]
Returns
-------
rho... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_valid_remote_clone_id(remote_clone_job_id):
"""
Validates a remote clone job ID, also known as the remote clone job
"job_name". A valid remote clone job name should look like:
dstrclone-00000001 - It should end with 8 hexadecimal characters in
lower case.
:type remote_clone_j... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_config(config_path):
"""read config_path and return options as dictionary"""
result = {}
with open(config_path, 'r') as fd:
for line in fd.readlines():
if '=' in line:
key, value = line.split('=', 1)
try:
result[k... | bigcode/self-oss-instruct-sc2-concepts |
def remove_outliers(compiled, plot_type, data_type = "raw"):
"""[removes outliers from dataframe]
Args:
compiled ([dataframe]): [raw dataframe containing outliers to be removed]
plot_type ([str]): [string can either be 'hist' for histogram data or 'TDP' for TDP data]
data_type (str, opt... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_hpxregion(region):
"""Parse the ``HPX_REG`` header keyword into a list of tokens.
"""
m = re.match(r"([A-Za-z\_]*?)\((.*?)\)", region)
if m is None:
raise ValueError(f"Failed to parse hpx region string: {region!r}")
if not m.group(1):
return re.split(",", m.gr... | bigcode/self-oss-instruct-sc2-concepts |
def doi_identifier(identifiers):
"""Extract DOI from sequence of identifiers."""
doi_identifier = identifiers.get("doi")
return doi_identifier['identifier'] if doi_identifier else None | bigcode/self-oss-instruct-sc2-concepts |
def find_combos(length: int) -> int:
"""
In the data, there are no gaps of two, only gaps of one or three, between
numbers in the sorted list.
The rules are such that the number of combos are the same regardless
of the specific numbers involved--there are the same number of combos
for [0, 1, 2, ... | bigcode/self-oss-instruct-sc2-concepts |
def get_rain_str(risk_of_rain: float) -> str:
"""
Return string in french with risk of rain info
:param risk_of_rain: Risk of rain between 0 and 1
:return: string
"""
if risk_of_rain < 0.33:
return f'Risque de pluie : {int(100*risk_of_rain)}%.'
if risk_of_rain < 0.66:
return ... | bigcode/self-oss-instruct-sc2-concepts |
def truncate(string, length=20):
"""Truncate a string and add ellipsis, if-needed.
Args:
string (str): String to be truncated
length (int, optional): Lenth of string to truncate
Returns:
str: Truncated string
"""
ellipsis = '..'
# Append ellipsis if-needed
if len(... | bigcode/self-oss-instruct-sc2-concepts |
def GetReverseDependencyClosure(full_name, deps_map):
"""Gets the closure of the reverse dependencies of a node.
Walks the tree along all the reverse dependency paths to find all the nodes
that transitively depend on the input node.
"""
s = set()
def GetClosure(name):
s.add(name)
node = deps_map[na... | bigcode/self-oss-instruct-sc2-concepts |
import json
def decode_transaction(raw):
"""Decode a transaction from bytes to a dict."""
return json.loads(raw.decode('utf8')) | bigcode/self-oss-instruct-sc2-concepts |
def compute_response_integral(X, stim_frames):
"""
Compute the integrated/summed response over all stimulus frames
Arguments:
X (array): dF/F of size (trials, time frames, boutons)
stim_frames (array): time frames w/ stimulus
Returns:
Xint (array): summed dF/F during stim frames... | bigcode/self-oss-instruct-sc2-concepts |
def derive_state(state_list):
"""
Compute a derived state an object. This will be based off the states of
the objects based in.
:param state_list: List of objects that have a get_state() method.
:returns: State as a string.
"""
# If there are no ports passed in, we assume it is an internal... | bigcode/self-oss-instruct-sc2-concepts |
def ensure_nest_alts_are_valid_alts(nest_spec, list_elements, all_ids):
"""
Ensures that the alternative id's in `nest_spec` are all in the universal
choice set for this dataset. Raises a helpful ValueError if they are not.
Parameters
----------
nest_spec : OrderedDict, or None, optional.
... | bigcode/self-oss-instruct-sc2-concepts |
def Gt(a, b):
""" Create an SMT greater-than.
See also the __gt__ overload (> operator) for arithmetic SMT expressions.
>>> x, y = Ints('x y')
>>> Gt(x, y)
x > y
"""
return a > b | bigcode/self-oss-instruct-sc2-concepts |
def hamilton_product(q1, q2):
"""
Performs composition of two quaternions by Hamilton product. This is equivalent
of a rotation descried by quaternion_1 (q1), followed by quaternion_2 (q2).
https://en.wikipedia.org/wiki/Quaternion#Hamilton_product
:param q1: 4-item tensor representing unit quaternion.
:pa... | bigcode/self-oss-instruct-sc2-concepts |
def find_highest_multiple_of_three_ints(int_list):
"""Takes in a list of integers and finds the highest multiple of three of them"""
if type(int_list) != list:
raise TypeError(
"The argument for find_highest_multiple_of_three_ints must be of type list.")
elif len(int_list) == 3:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_states(weighted_samples):
"""
Get the states from set of weighted particles.
:param weighted_samples: list of weighted particles
:return: list of particle states without weights
"""
return [ws[1] for ws in weighted_samples] | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_required_kw_args(fn):
"""
获取函数命名关键参数,且非默认参数
:param fn: function
:return:
"""
args = []
# 获取函数fn的参数, orderd mapping
params = inspect.signature(fn).parameters
for name, param in params.items():
# *或者 *args 后面的参数, 且没有默认值
if param.kind == param.K... | bigcode/self-oss-instruct-sc2-concepts |
def get_portgroup_by_id(task, portgroup_id):
"""Lookup a portgroup by ID on a task object.
:param task: a TaskManager instance
:param portgroup_id: ID of the portgroup.
:returns: A Portgroup object or None.
"""
for portgroup in task.portgroups:
if portgroup.id == portgroup_id:
... | bigcode/self-oss-instruct-sc2-concepts |
def enquote1(text):
"""Quotes input string with single-quote"""
in_str = text.replace("'", r"\'")
return "'%s'" % text | bigcode/self-oss-instruct-sc2-concepts |
def get_strptime_pattern(s):
"""
:param s: str
:return: get strptime pattern
NOTE: be careful with microseconds. It is not handled properly
"""
if len(s) > 20:
raise Exception("Too big string")
return "%Y%m%d%H%M%S%f"[: int(len(s) - 2)] | bigcode/self-oss-instruct-sc2-concepts |
def compute_field_capacity(clay_val, oc_val, sand_val):
"""
Calculate Field Capacity based on Clay, Organic Matter and sand value
:param clay_val: percentage of clay
:param oc_val: percentage of organic carbon
:param sand_val: percentage of sand
:return: a float value representing FC
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def _add_missing_parameters(flattened_params_dict):
"""Add the standard etl parameters if they are missing."""
standard_params = ['ferc1_years',
'eia923_years',
'eia860_years',
'epacems_years',
'epacems_states']
for ... | bigcode/self-oss-instruct-sc2-concepts |
def completions_sorting_key(word):
"""key for sorting completions
This does several things:
- Lowercase all completions, so they are sorted alphabetically with
upper and lower case words mingled
- Demote any completions starting with underscores to the end
- Insert any %magic and %%cellmagic... | bigcode/self-oss-instruct-sc2-concepts |
def noop(x=None, *args, **kwargs):
"""Do nothing"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def filter_blacklist(genes, blacklist, field='gene_id'):
"""Filters potential hits against given blacklist."""
return genes.loc[~genes[field].isin(blacklist)] | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def optimise_autopkg_recipes(recipe):
"""If input is an AutoPkg recipe, optimise the yaml output in 3 ways to aid
human readability:
1. Adjust the Processor dictionaries such that the Comment and Arguments keys are
moved to the end, ensuring the Processor key is firs... | bigcode/self-oss-instruct-sc2-concepts |
def remove_quotes(string: str) -> str:
"""
Removes quotes from around a string, if they are present.
:param string: The string to remove quotes from.
:return: The string without quotes.
"""
# If starts and ends with double-quotes, remove them
if string.startswith('\"') and string.e... | bigcode/self-oss-instruct-sc2-concepts |
def find_range(arr: list[int], val: int) -> list[int]:
"""Binary search to find the range of a given number ‘val’.
The range of val will be the first and last position of val in the arr.
Complexity:
Time: Θ(logn) <=> O(logn) & Ω(logn) (since we must consider duplicates)
Space: O(1)
Ar... | bigcode/self-oss-instruct-sc2-concepts |
def _get_csr_submatrix_major_axis(Ap, Aj, Ax, start, stop):
"""Return a submatrix of the input sparse matrix by slicing major axis.
Args:
Ap (cupy.ndarray): indptr array from input sparse matrix
Aj (cupy.ndarray): indices array from input sparse matrix
Ax (cupy.ndarray): data array from... | bigcode/self-oss-instruct-sc2-concepts |
def decode(seqIdx, idxToToken, delim=None, stopAtEnd=True):
"""
Given seqIdx (list of token_ixs), decode to a sentence.
"""
tokens = []
for idx in seqIdx:
tokens.append(idxToToken[idx])
if stopAtEnd and tokens[-1] == '<END>':
break
if delim is None:
return tokens
else:
return delim... | bigcode/self-oss-instruct-sc2-concepts |
import difflib
def DiffFileContents(expected_path, actual_path):
"""Check file contents for equality and return the diff or None."""
with open(expected_path) as f_expected, open(actual_path) as f_actual:
expected_lines = f_expected.readlines()
actual_lines = f_actual.readlines()
if expected_lines == ac... | bigcode/self-oss-instruct-sc2-concepts |
def strip_dav_path(path):
"""Removes the leading "remote.php/webdav" path from the given path.
:param str path: path containing the remote DAV path "remote.php/webdav"
:return: path stripped of the remote DAV path
:rtype: str
"""
if 'remote.php/webdav' in path:
return path.split('remote... | bigcode/self-oss-instruct-sc2-concepts |
def findTrend(trend, trendList):
""" Finds a specific trend tuple within a list of tuples """
# Assuming the lack of duplicates
for tIndex in range(len(trendList)):
if len(trendList[tIndex]) == 2:
if trendList[tIndex][0] == trend:
return tIndex, trendList[tIndex]
retu... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def latex_repr(item: Any) -> str:
"""
Return a str if the object, 'item', has a special repr method
for rendering itself in latex. If not, returns str(result).
"""
if hasattr(item, "_repr_latex_"):
return item._repr_latex_().replace("$", "")
elif hasattr(item, "... | bigcode/self-oss-instruct-sc2-concepts |
def _scalar(x):
"""Convert a scalar tensor into a Python value."""
assert x.numel() == 1
return x[0] | bigcode/self-oss-instruct-sc2-concepts |
def look_ahead_line(fd):
"""
Read and return a line from the given file object. Saves the current
position in the file before the reading occurs and then, after the reading,
restores the saved (original) position.
"""
lastpos = fd.tell()
line = fd.readline()
fd.seek(lastpos)
return ... | bigcode/self-oss-instruct-sc2-concepts |
def GetComplementaryColor(hexStr):
"""Returns complementary RGB color
Example Usage:
>>> GetComplementaryColor('#FFFFFF')
'#000000'
"""
if hexStr[0] == '#':
hexStr = hexStr[1:]
rgb = (hexStr[0:2], hexStr[2:4], hexStr[4:6])
compColor = '#'
for a in rgb:
comp... | bigcode/self-oss-instruct-sc2-concepts |
def is_in_grid(index, maximum):
"""Check if index is within grid range."""
return 0 <= index <= maximum | bigcode/self-oss-instruct-sc2-concepts |
def reduce_vector(V, p):
"""
Reduces a vector over finite field.
"""
for i, element in enumerate(V):
V[i] = element % p
return V | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_doxygen_default_conf_path() -> Path:
"""Get the path to the doxygen configuration file included with
Documenteer.
Returns
-------
defaults_path : `pathlib.Path`
Path the the ``doxygen.defaults.conf`` file included with Documenteer
as a basis for Sc... | bigcode/self-oss-instruct-sc2-concepts |
def _line_labels(last, pos='value', sep=1, delta=0.1, max_iters=20):
"""Calculate y-position of line labels, minimizing label overlap."""
labels = last.copy()
for _ in range(max_iters):
changed = False
for i, row_i in labels.iterrows():
for j, row_j in labels.iterrows():
if j <= i: continue
... | bigcode/self-oss-instruct-sc2-concepts |
def strip_suffixes(s, suffixes):
"""
Helper function to remove suffixes from given string.
At most, a single suffix is removed to avoid removing portions
of the string that were not originally at its end.
:param str s: String to operate on
:param iter<str> tokens: Iterable of suffix strings
... | bigcode/self-oss-instruct-sc2-concepts |
def split_by_two_strings(line, str1, str2):
"""Split the input line into three parts separated by two given strings."""
# Start of second part in the input string.
i1 = line.index(str1) + len(str1)
# End of second part in the input string.
i2 = line.index(str2)
# Now we know where the second p... | bigcode/self-oss-instruct-sc2-concepts |
import re
import itertools
def replace_wcs(hdu, wcs):
"""Replaces WCS information in the header.
Removes the current WCS information in the input
`~astropy.io.fits.ImageHDU` and replace it with new one.
Parameters
----------
hdu : `~astropy.io.fits.ImageHDU`:
The `~astropy.io.fits.Im... | bigcode/self-oss-instruct-sc2-concepts |
def get_last_build_number(job_info):
"""Given a job info dict, returns the last build number."""
if job_info['lastCompletedBuild']:
return job_info['lastCompletedBuild']['number']
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def create_word_set() -> set:
"""
Generate a set of words from a unix based word file
"""
word_list = []
with open("/usr/share/dict/words", "r") as word_file:
for line in word_file:
word_list.append(line.strip())
return set(word_list) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_x_data(x_data):
"""
This function will normalize the training and testing images.
Parameters
----------
x_data : ndarray
The training and/or testing images.
Returns
-------
numpy.ndarray
A normalized training and/or testing image values.
"""
max_va... | bigcode/self-oss-instruct-sc2-concepts |
def renders(col_name):
"""
Use this decorator to map your custom Model properties to actual
Model db properties. As an example::
class MyModel(Model):
id = Column(Integer, primary_key=True)
name = Column(String(50), unique = True, nullable=False)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_entity_id_attribute(self, entity, id_attribute_name = "object_id"):
"""
Retrieves the id attribute (value) from the given entity that may
be both an entity object or an entity map represented by a dictionary.
In case the given entity is a map the id attribute name value is used
to retrieve t... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def check_dependencies(*executables, raise_error=True):
"""Check if the given executables are existing in $PATH.
:param tuple executables: A tuple of executables to check for their
existence in $PATH. Each element of the tuple can be either a string
(e. g. `pdfimages`) or a itself a... | bigcode/self-oss-instruct-sc2-concepts |
def get_module_by_name(model, module_name):
"""
Get a module specified by its module name
Parameters
----------
model : pytorch model
the pytorch model from which to get its module
module_name : str
the name of the required module
Returns
-------
module, module
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def collate_fn(data):
"""Pad data in a batch.
Parameters
----------
data : list((tensor, int), )
data and label in a batch
Returns
-------
tuple(tensor, tensor)
"""
max_len = max([i[0].shape[0] for i in data])
labels = torch.tensor([i[1] for i in data], dty... | bigcode/self-oss-instruct-sc2-concepts |
import string
def get_number(text):
"""
Return the number at the start of text, as a string.
text -- string starting with a number
"""
char = 0
number = ""
while char < len(text):
if text[char] in string.digits + "-":
number = number + text[char]
char += 1
... | bigcode/self-oss-instruct-sc2-concepts |
def manhattenPath(position1, position2):
"""
calculates grid deltas between two positions relative to
first position
:param position1:
:param position2:
:return: dx (int), dy (int)
"""
dx = position2[0] - position1[0]
dy = position2[1] - position1[1]
return dx, dy | bigcode/self-oss-instruct-sc2-concepts |
def gather_columns(rule_name, columns, prefix, additions=None):
"""Build a list of all columns matching a prefix allong with potential additional rules."""
raw_rule_name = rule_name.split(".")[0]
if additions is None:
additions = []
# Reduce a pair of parens around a type back to itself.
pa... | bigcode/self-oss-instruct-sc2-concepts |
def is_list_like(obj):
"""
Check whether a variable is a sequence other than a string.
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) | bigcode/self-oss-instruct-sc2-concepts |
def PHMS2RA (rast, sep=":"):
"""
Convert a right ascension string to degrees
return RA in degrees
* rast = RA string as "hh:mm:ss.s"
* sep = sympol to use to separate components instead of ":"
"""
################################################################
pp = rast.split(se... | bigcode/self-oss-instruct-sc2-concepts |
def verify(df, check, *args, **kwargs):
"""
Generic verify. Assert that ``check(df, *args, **kwargs)`` is
true.
Parameters
==========
df : DataFrame
check : function
Should take DataFrame and **kwargs. Returns bool
Returns
=======
df : DataFrame
same as the inpu... | bigcode/self-oss-instruct-sc2-concepts |
import re
def changeStrokeOpacity(text, opacity):
"""
Change all stroke opacities in a given string of text to the provided
opacity. Returns the text with modifications made.
"""
newData = None
regularExpression = re.compile(r'stroke-opacity:[0-9]*[.]?[0-9]+[;|"]')
matchOb = regularExpres... | bigcode/self-oss-instruct-sc2-concepts |
def find_bound_tuple(a, b, bounds):
"""If a and b are both included in a bounds tuple, return it.
Otherwise return None.
"""
def inside(num, spanish):
return num >= spanish[0] and num <= spanish[1]
for span in bounds:
if inside(a, span) and inside(b, span):
retu... | bigcode/self-oss-instruct-sc2-concepts |
import re
def fixChromName(name, orgn="medicago"):
"""
Convert quirky chromosome names encountered in different
release files, which are very project specific, into a more
general format.
For example, in Medicago
Convert a seqid like
`Mt3.5.1_Chr1` to `chr1`
`Mt3.5... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _getname(infile):
"""
Get file names only.
Examples
--------
>>> _getname("drop/path/filename.txt")
'filename.txt'
>>> _getname(["drop/path/filename.txt", "other/path/filename2.txt"])
['filename.txt', 'filename2.txt']
"""
if isinstance(infile, (... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def guess_zarr_path(path):
"""Guess whether string path is part of a zarr hierarchy.
Parameters
----------
path : str
Path to a file or directory.
Returns
-------
bool
Whether path is for zarr.
>>> guess_zarr_path('dataset.zarr')
True
... | bigcode/self-oss-instruct-sc2-concepts |
def find_key(key_list, key):
"""Find the index of a key in a list of keys.
This is a wrapper for the list method `index`
that can search any interable (not just lists)
and will return None if the key is not found.
Parameters
----------
key_list : iterable
key : object to be searched
... | bigcode/self-oss-instruct-sc2-concepts |
def get_worksheet_data(worksheet, data_range, expected_header=None):
"""Read a range of cells from a worksheet into a list of dictionaries
treating the first row as a header.
:param worksheet: a pygsheets Worksheet object
:param data_range: cell range tuple, e.g. ('A', 'D'), ('A1', 'A17')
:param ex... | bigcode/self-oss-instruct-sc2-concepts |
def remove_copies(data: list) -> list:
"""Creates a unique list of arrays given a list of arrays containing
identical arrays.
Param:
data (list[list[float or int]]): a list of lists of comparable items
Return
arrays: the unique list with no repeated arrays
"""
arrays = []
f... | bigcode/self-oss-instruct-sc2-concepts |
def pick_bpart(df, bpart):
"""
Create a sub dataset of particular body part.
:param df: dataframe to process
:param bpart: body part to extract
:return: trimmed dataframe
"""
if bpart == "all":
return df
return df[df["body_part"] == bpart].reset_index() | bigcode/self-oss-instruct-sc2-concepts |
def _format_syntax_error_message(exception):
"""Returns a nicely formatted SyntaxError message that emulates
what the Python interpreter outputs, e.g.:
> File "raven.py", line 3
> st.write('Hello world!!'))
> ^
> SyntaxError: invalid syntax
Parameters
-----... | 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.