seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def is_ipynb_file(file_name: str) -> bool:
"""
Return whether a file is a jupyter notebook file.
"""
return file_name.endswith(".ipynb") | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import MutableSequence
def is_adjacency_matrix(item: Any) -> bool:
"""Returns whether 'item' is an adjacency matrix."""
if isinstance(item, tuple):
item = item[0]
return (isinstance(item, MutableSequence)
and all(isinstance(i, MutableSequence) for i ... | bigcode/self-oss-instruct-sc2-concepts |
def truncate_path(full_path, chars=30, skip_first=True):
"""Truncate the path of a category to the number of character.
Only the path is truncated by removing nodes, but the nodes
themselves are never truncated.
If the last node is longer than the ``chars`` constraint, then it is
returned as is (w... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_dictionary(input_dict, parent_key='', separator='.'):
"""Flatten a given dictionary with nested dictionaries if any.
Example: { 'a' : {'b':'c', 'd': {'e' : 'f'}}, 'g' : 'h'} will be flattened
to {'a.b': 'c', 'a.d.e': 'f', 'g': 'h'}
This will flatten only the values of dict type.
:para... | bigcode/self-oss-instruct-sc2-concepts |
def convert_emotion_metric_entity_to_dict(e_metric):
"""Convert a datastore EmotionMetric entity into a dictionary.
Args:
e_metric: an EmotionMetric datastore entity.
Returns:
A dictionary with keys as emotions and values are confidences
"""
e_dict = {}
e_dict['amusement'] = e_metric.amusement
e... | bigcode/self-oss-instruct-sc2-concepts |
def classpath(klass):
"""Return the full class path
Args:
klass (class): A class
"""
return f"{klass.__module__}.{klass.__name__}" | bigcode/self-oss-instruct-sc2-concepts |
import glob
def glob_all(args):
"""Given a list of command line arguments, expand all of them with glob."""
result = []
for arg in args:
if arg[0]=="@":
with open(arg[1:],"r") as stream:
expanded = stream.read().split("\n")
expanded = [s for s in expanded if... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_action(state):
"""
Plays a game using random actions until a terminal state is reached.
Returns score of that game.
"""
while not state.is_terminal():
valid = state.get_valid_actions()
if not valid:
raise Exception("Non-terminal state has no v... | bigcode/self-oss-instruct-sc2-concepts |
def remove_at(i, s):
"""Removes character from string at provided position"""
return s[:i] + s[i + 1 :] | bigcode/self-oss-instruct-sc2-concepts |
def MakeSpecificSKUAllocationMessage(
messages, vm_count, accelerators, local_ssds, machine_type,
min_cpu_platform):
"""Constructs a single specific sku allocation message object."""
prop_msgs = (
messages.AllocationSpecificSKUAllocationAllocatedInstanceProperties)
return messages.AllocationSpecific... | bigcode/self-oss-instruct-sc2-concepts |
import string
def deriveArtistFromName(name):
"""
Ensure that the given name doesnt have usual suspects like "Featuring" or "Ft" or " with" to attempt to return just
the artist name
:param name: str
:return: str
"""
if not name:
return name
removeParts = [" ft. ", " ft ", " fe... | bigcode/self-oss-instruct-sc2-concepts |
def rvShift(wavelength, rv):
"""
Perform the radial velocity correction.
Parameters
----------
wavelength : numpy array
model wavelength (in Angstroms)
rv : float
radial velocity shift (in km/s)
Returns
-------
wavelength : numpy array
shifted model wavelength (in Angstroms)
"""
r... | bigcode/self-oss-instruct-sc2-concepts |
def jaccard(macs1, macs2):
"""Returns jaccard similarity between two lists of MAC Addresses"""
union = list(set(macs1) | set(macs2))
intersection = list(set(macs1) & set(macs2))
return len(intersection) / len(union) | bigcode/self-oss-instruct-sc2-concepts |
def upper_bound(arr, value, first, last):
"""Find the upper bound of the value in the array
upper bound: the first element in arr that is larger than value
Args:
arr : input array
value : target value
first : starting point of the search, inclusive
last ... | bigcode/self-oss-instruct-sc2-concepts |
def subdict(dic, keys):
"""
Returns a new dictionary dic2 such that
dic2[i] = dic[i] for all i in keys
dic -- a dictionary
keys -- a list of keys
"""
dic2 = {}
for key in keys:
if key in dic:
dic2[key] = dic[key]
return dic2 | bigcode/self-oss-instruct-sc2-concepts |
def _minimize(obj):
"""Remove lists with only one entry"""
if isinstance(obj, list):
if len(obj) == 1:
return _minimize(obj[0])
else:
result = []
for x in obj:
y = _minimize(x)
if y:
result.append(y)
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_local_paths(root, pattern):
"""Returns a generator of files matching the glob_pattern under the root directory ."""
path = Path(root)
return path.glob(pattern)
# find the columns that are not common | bigcode/self-oss-instruct-sc2-concepts |
def is_strf_param(nm):
"""Check if a parameter name string is one of STRF parameters."""
return any(n in nm for n in ("rates_", "scales_", "phis_", "thetas_")) | bigcode/self-oss-instruct-sc2-concepts |
def get_params(**override):
"""Returns default parameters dictionary for model."""
params = dict(
# Model args
num_channels=3,
multiscale='Steerable', # 'Steerable', Laplacian', None
nscales=3,
steerable_filter_type=1,
cnn='Conv',
num_filters=[64, 64, 64, 3],
paddi... | bigcode/self-oss-instruct-sc2-concepts |
def _is_virtio_blk(device_path):
"""
Check whether the supplied device path is a virtio_blk device.
We assume that virtio_blk device name always begin with `vd` whereas
Xen devices begin with `xvd`.
See https://www.kernel.org/doc/Documentation/devices.txt
:param FilePath device_path: The devic... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def pad_to_multiple(tensor, pad_base):
"""
This function pads the sequence with zeros to be divisible by pad_base.
Assumed tensor is of shape (batch, seq_len, channels)
"""
new_len = ((tensor.shape[1] - 1) // pad_base + 1) * pad_base
# one is subtracted for the case when tensor.sh... | bigcode/self-oss-instruct-sc2-concepts |
def fraction(count, value):
"""Divides the given character count by the length of the string
representation for the given value.
Parameters
----------
count: int
Character count returned by one of the count functions.
value: scalar
Scalar value in a data stream.
Returns
... | bigcode/self-oss-instruct-sc2-concepts |
def cc_is_manager(ctx):
"""Check if command sender has channel managment permissions."""
return (ctx.guild == None) or (ctx.author.permissions_in(ctx.channel).manage_channels) | bigcode/self-oss-instruct-sc2-concepts |
def ChanModDS(ds, chan, mod=lambda x: x):
"""
apply any well-behaved lambda function to a specific channel within a dataset
:param ds: xarray dataset
:param chan: channel to apply modification too
:param mod: well-behaved lambda function
:return: adds a channel with the modified data
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def IsPalindromePermutation(s):
""" check if the string s is a permutation of a palindrome"""
chars = {k : 0 for k in set(s)}
for i in s:
chars[i] += 1
odd_nums = 0
for k, v in chars.items():
if (v % 2) != 0:
odd_nums += 1
if odd_nums > 1:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def find_closest_pixel(pos, pixel_tab):
"""
Compute the closest pixel of a given position
Parameters
----------
pos : 1D Numpy array giving a position
pixel_tab : N-dim Numpy array of pixels positions [X,Y]
Returns
-------
Pixel index in the given pixel_tab, corresponding distance t... | bigcode/self-oss-instruct-sc2-concepts |
def is_divisible(m: int, n: int) -> bool:
"""
predicate to be divisible
Args:
m: dividend
n: divisor
Returns:
True if divisible
"""
return m % n == 0 | bigcode/self-oss-instruct-sc2-concepts |
import ast
def get_edgesID(row, columns):
"""
The ABM stores the sequence of edgeIDs traversed in each route in different columns, given the 254 characters limit per field.
This functions merges such lists in one List.
Parameters
----------
row: Pandas Series
A row of the GeoData... | bigcode/self-oss-instruct-sc2-concepts |
def get_ap_os_version(ap):
"""Parses os_version from AP data
Removes model from start of os version if found.
Args:
ap (dict): ap data returned from FortiOS managed-ap REST endpoint
Returns:
str: OS version on 'unknown' id not detected
"""
if 'os_version' not in ap:
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def min_groups(mag, ins, filt, sub, mod, band, infile):
"""Estimates the minimum number of groups to reach
target acq sat requirements.
Parameters
----------
mag : float
Magnitude of star.
ins : str
Instrument.
filt : str
Filter.
sub : str
... | bigcode/self-oss-instruct-sc2-concepts |
def add_edge(locations, edge):
"""
Add edge to list of locations, returning a list of edge-added locations
"""
if edge is None:
return locations
return [tuple([i + j for i, j in zip(edge, l)]) for l in locations] | bigcode/self-oss-instruct-sc2-concepts |
import locale
def asunicode_win(s):
"""Turns bytes into unicode, if needed."""
if isinstance(s, bytes):
return s.decode(locale.getpreferredencoding())
else:
return s | bigcode/self-oss-instruct-sc2-concepts |
def _call_signature(callable, *args, **kwargs):
"""
Generate a human-friendly call signature
From recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307970
"""
argv = [repr(arg) for arg in args] + ["%s=%r" % x for x in kwargs.items()]
return "%s(%s)" % (callable.__name__, ", ".join(... | bigcode/self-oss-instruct-sc2-concepts |
def pos_distribution(doc):
"""Get POS distribution from a processed text.
Let us suppose that a given sentence has the following pos tags:
``[NOUN, VERB, ADJ, VERB, ADJ]``. The PoS distribution would be
* ``NOUN: 1``
* ``VERB: 2``
* ``ADJ: 2``
This function returns this distrubution as a ... | bigcode/self-oss-instruct-sc2-concepts |
def origin_volume(origin_str):
"""Extracts original phisical volume name from origin record"""
return origin_str.split("@")[0].split("/")[1] | bigcode/self-oss-instruct-sc2-concepts |
def _unit_conll_map(value, empty):
"""
Map a unit value to its CoNLL-U format equivalent.
Args:
value: The value to convert to its CoNLL-U format.
empty: The empty representation for a unit in CoNLL-U.
Returns:
empty if value is None and value otherwise.
"""
return empty if value i... | bigcode/self-oss-instruct-sc2-concepts |
def make_optic_canula_cylinder(
atlas,
root,
target_region=None,
pos=None,
offsets=(0, 0, -500),
hemisphere="right",
color="powderblue",
radius=350,
alpha=0.5,
**kwargs,
):
"""
Creates a cylindrical vedo actor to scene to render optic cannulas. By default
thi... | bigcode/self-oss-instruct-sc2-concepts |
def strong_emphasis(text: str) -> str:
"""Strongly emphasizes (bolds) the given text by placing <strong> tags around it.
:param text: The text to be strongly emphasized
"""
return f'<strong>{text}</strong>' | bigcode/self-oss-instruct-sc2-concepts |
def ParsePlaceId(json_obj):
"""Parse the place id from the 'place' twitter tag if it exists."""
if not json_obj:
return None
return json_obj.get('id', '') | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_response(url, params) :
"""
Handle GET response and convert to json.
"""
response = requests.get(url, params)
response.raise_for_status()
data = response.json()
return data | bigcode/self-oss-instruct-sc2-concepts |
def _get_block_sizes(resnet_size):
"""Retrieve the size of each block_layer in the ResNet model."""
choices = {
18: [2, 2, 2, 2],
34: [3, 4, 6, 3],
50: [3, 4, 6, 3],
101: [3, 4, 23, 3],
152: [3, 8, 36, 3],
200: [3, 24, 36, 3]
}
return choices[resnet_size] | bigcode/self-oss-instruct-sc2-concepts |
import socket
def findFreePort(interface="127.0.0.1", family=socket.AF_INET, type=socket.SOCK_STREAM):
"""
Ask the platform to allocate a free port on the specified interface, then
release the socket and return the address which was allocated.
@param interface: The local address to try to bind the po... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_dump_file(filename):
"""Parse dump file data."""
with open(filename, 'r') as dump_file:
results = dict()
for line in dump_file:
match = re.search(r'Janky frames: (\d+) \(([\d\.]+)%\)', line)
if match is not None:
results['jankNum'] = ... | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def process_border_size_arg(border_size_arg):
"""Handle borderSize arg in vidstab.__main__
Convert strings that aren't 'auto' to 0
:param border_size_arg: borderSize arg in vidstab.__main__
:return: int or 'auto'
>>> process_border_size_arg('a')
0
>>> process_border_size... | bigcode/self-oss-instruct-sc2-concepts |
def mocked_user_input_macos(mocked_user_input):
"""Mocking user input and return `macos`"""
mocked_user_input.return_value = "macos"
return mocked_user_input | bigcode/self-oss-instruct-sc2-concepts |
def get_hounsfield_coeffs(ds_open_file):
"""Returns the slope-intercept pair needed to convert an image
to Hounsfield units"""
rescale_slope = ds_open_file[0x28, 0x1053].value
rescale_intercept = ds_open_file[0x28,0x1052].value
return (rescale_slope,rescale_intercept) | bigcode/self-oss-instruct-sc2-concepts |
def check_elements(string):
"""Check for chemical letters outside of the CHNOPS set.
If the string only contains CHNOPS, returns True.
Otherwise, returns False.
Note: does not cover Scandium :(
"""
bad_elements = "ABDEFGIKLMRTUVWXYZsaroudlefgibtn" # chem alphabet -CHNOPS
return not any(n i... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_code(code):
"""
Sanitize code removing unnecessary characters
Params:
code (str): target code
Returns: the sanitized code
"""
if code:
code = code.replace('-', '')
code = code.ljust(7, '0')
return code | bigcode/self-oss-instruct-sc2-concepts |
def str_list_oconv(x):
"""
Convert list into a list literal.
"""
return ','.join(x) | bigcode/self-oss-instruct-sc2-concepts |
def is_order_constrained(paths, constraints, j, k):
"""Is the order of the sequences between j and k constrained. Such that reversing this order will violate
the constraints."""
for q in range(j, k):
# search between j and k.
first_path = paths[q]
for constraint in constraints:
... | bigcode/self-oss-instruct-sc2-concepts |
def to_applescript(b):
"""Convert a Python boolean to a string to be passed back to AppleScript"""
return str(b) | bigcode/self-oss-instruct-sc2-concepts |
def multi_arity(*funcs):
"""Returns a new multi-arity function which dispatches to `funcs`.
The returned function will dispatch to the provided functions based on the
number of positional arguments it was called with. If called with zero
arguments it will dispatch to the first function in `funcs`, if c... | bigcode/self-oss-instruct-sc2-concepts |
def how_many_squares_in_shape(input_shape, feature_shape, delta):
"""
Computes the shape of an output layer that can be plugged into the input
layer with respect to their shapes and the delta
Parameters;
`input_shape`: The shape of the input layer
`feature_shape`: The shape of the feat... | bigcode/self-oss-instruct-sc2-concepts |
def eval_datasets_flist_reader(flist):
"""
:param flist format: impath,impath\nimpath impath\n ...
:return: (impath, label) list
"""
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
q,r = line.strip().split(',')
if q == 'query_id':
... | bigcode/self-oss-instruct-sc2-concepts |
def getHdbCopyBase(ctx):
""" Get base directory where SAP HANA database snapshots are copied to """
return f'{ctx.cf.nfs.bases.copy}/{ctx.cf.refsys.hdb.host.name}/{ctx.cf.refsys.hdb.sidU}' | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load(fname):
"""Load a hierarchical model saved to file via
model.save(fname)
"""
with open(fname, 'rb') as f:
model = pickle.load(f)
return model | bigcode/self-oss-instruct-sc2-concepts |
def h(params, sample):
"""This evaluates a generic linear function h(x) with current parameters. h stands for hypothesis
Args:
params (lst) a list containing the corresponding parameter for each element x of the sample
sample (lst) a list containing the values of a sample
Returns:
Evaluation of h(x)
"""
ac... | bigcode/self-oss-instruct-sc2-concepts |
def get_pipe_dict(d, i):
"""
given a dictionary d for a given instrument, return the dictionary for the
ith pipeline version
"""
pipe_versions = list(d.keys())
k = pipe_versions[i]
mode = list(d[k].keys())[0]
return d[k][mode] | bigcode/self-oss-instruct-sc2-concepts |
def get_image_topic(bag):
""" Returns the name of the topic for the main camera """
topics = bag.get_type_and_topic_info()[1].keys()
for t in topics:
if 'camera_node/image/compressed' in t:
return t
msg = 'Cannot find the topic: %s' % topics
raise ValueError(msg) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_drive_time(apiKey, origin, destination):
"""
Returns the driving time between using the Google Maps Distance Matrix API.
API: https://developers.google.com/maps/documentation/distance-matrix/start
# INPUT ------------------------------------------------------------------... | bigcode/self-oss-instruct-sc2-concepts |
def get_symbol_map(source_nodes):
"""Generates a dict of {'id': SourceUnit} used for linking nodes.
Arguments:
source_nodes: list of SourceUnit objects."""
symbol_map = {}
for node in source_nodes:
for key, value in ((k, x) for k, v in node.exportedSymbols.items() for x in v):
... | bigcode/self-oss-instruct-sc2-concepts |
def dictStructure(dictionary, indent=4, level=0):
"""
Get the structure of a dictionary. Returns an ``OrderedDict`` with the same keys
as the one passed as input but the values replaced with its type.
Args:
dictionary (`dict`): dictionary to traverse
indent (`int`): number of spaces to ... | bigcode/self-oss-instruct-sc2-concepts |
def get_num_iterations(iterations_per_utterance, examples):
"""Returns the number of iterations to run for in this batch of examples
Args:
iterations_per_utterance (int): iterations per utterance config
examples (list[Example])
Returns:
int: number of iterations
"""
return ... | bigcode/self-oss-instruct-sc2-concepts |
def first_not_none_param(params, default):
"""
Given a list of `params`, use the first param in the list that is
not None. If all are None, fall back to `default`.
"""
for param in params:
if param is not None:
return param
return default | bigcode/self-oss-instruct-sc2-concepts |
def get_headers(depth=1):
"""
Return the standard request headers
"""
return {'accept': 'application/json;depth=' + str(depth)} | bigcode/self-oss-instruct-sc2-concepts |
def _reconstruct_token(key):
"""Reconstruct a token from a key in a graph ('SomeName_<token>')"""
if len(key) < 34 or key[-33] != "_":
return
token = key[-32:]
try:
int(token, 16)
except ValueError:
return None
return token.lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Union
from typing import Any
def flatten_list(lst: List[Union[List, Any]]) -> List[Any]:
"""Flatten list of lists"""
result = []
for elm in lst:
if isinstance(elm, list):
result.extend(elm)
else:
result.append(elm)
retu... | bigcode/self-oss-instruct-sc2-concepts |
def Yindex(ell, m, ell_min=0):
"""Compute index into array of mode weights
Parameters
----------
ell : int
Integer satisfying ell_min <= ell <= ell_max
m : int
Integer satisfying -ell <= m <= ell
ell_min : int, optional
Integer satisfying 0 <= ell_min. Defaults to 0.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_profdata_file_name(trial_id):
"""Returns the profdata file name for |trial_id|."""
return 'data-{id}.profdata'.format(id=trial_id) | bigcode/self-oss-instruct-sc2-concepts |
def readList(confDict, list_in, constructor, cryomodule_entry=None):
"""
Generic function to read list of components.
Takes the global configuration dictionary, cycles through the list of components
(list of names, list_in), uses the names to identify the configuration entries in
the global dictiona... | bigcode/self-oss-instruct-sc2-concepts |
def get_qstar(inv, extrapolation=None):
"""
Get invariant value (Q*)
"""
return inv.get_qstar(extrapolation) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
from typing import Any
from typing import Dict
def _find_self(param_names: List[str], args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Any:
"""Find the instance of ``self`` in the arguments."""
instance_i = None
try:
instance_i = param_names.index(... | bigcode/self-oss-instruct-sc2-concepts |
def _validate_dict(s, accept_none=False):
"""
A validation method to check if the input s is a dictionary otherwise raise error if it is not convertable
"""
if s is None and accept_none:
return None
if isinstance(s, dict):
return s
else:
raise ValueError('{} is not a dictionary!'.format(s)) | bigcode/self-oss-instruct-sc2-concepts |
def gcd(a, b): # (1)
"""
Returns the greatest commond divisor of a and b.
Input:
a -- an integer
b -- an integer
Output:
an integer, the gcd of a and b
Examples:
>>> gcd(97,100)
1
>>> gcd(97 * 10**15, 19**20 * 97**2) ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def refind(regex, text):
"""Find a regex in some text, and return the matched text, or None."""
m = re.search(regex, text)
if m:
return m.group()
else:
return None | bigcode/self-oss-instruct-sc2-concepts |
import csv
def parse_csv_file(file_path, expected_num_columns):
"""
Reads the specified csv file. Checks for a value number of columns in
each row. Returns the csv file values as a list of tuples.
"""
values = []
with open(file_path) as csv_file:
csv_reader = csv.reader(csv_file, del... | bigcode/self-oss-instruct-sc2-concepts |
def clear_sesam_attributes(sesam_object: dict):
"""
Return same dict but without properties starting with "_"
:param sesam_object: input object from Sesam
:return: object cleared from Sesam properties
"""
return {k: v for k, v in sesam_object.items() if not k.startswith('_')} | bigcode/self-oss-instruct-sc2-concepts |
def card(n : int, text: str) -> str:
"""Create a HTML Card"""
html = f"""
<div class='card'>
<h4 class='card_text' id='test'->{n}<h4>
<span>{text}</span>
</div>
"""
return html | bigcode/self-oss-instruct-sc2-concepts |
def sign_max(X, axis = 0, n_jobs = 1):
"""
[Added 19/11/2018] [Edited 24/11/2018 Uses NUMBA]
Returns the sign of the maximum absolute value of an axis of X.
input: 1 argument, 2 optional
----------------------------------------------------------
X: Matrix X to be processed. Must b... | bigcode/self-oss-instruct-sc2-concepts |
def median(nums):
"""
Find median of a list of numbers.
>>> median([0])
0
>>> median([4,1,3,2])
2.5
Args:
nums: List of nums
Returns:
Median.
"""
sorted_list = sorted(nums)
med = None
if len(sorted_list) % 2 == 0:
mid_index_1 = len(sorted_list) ... | bigcode/self-oss-instruct-sc2-concepts |
def major_version(v):
"""
Return the major version for the given version string.
"""
return v.split('.')[0] | bigcode/self-oss-instruct-sc2-concepts |
def has22(list_one:list)->bool:
"""Returns True if the list contains a 2 next to a
2. Otherwise, the function returns False .
>>>has22([1,2,2,3])
True
>>>has22([1,2,3,4])
False
"""
if ', 2, 2' in str(list_one):
return True
elif list_one[0] == 2 and list_on... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Any
def unique(it: Iterable[Any]) -> bool:
""" check if all elements of an iterable of unqiue
Parameters
----------
it : Iterable[Any]
The iterable to be checked for unique elements
Returns
-------
bool:
True if all elements ... | bigcode/self-oss-instruct-sc2-concepts |
def split_by_length(str, length, rejoin_with=None):
"""
split a string by a given length
"""
str_arr = []
counter = 0
while counter<len(str):
str_arr.append(str[counter:counter+length])
counter += length
if rejoin_with:
return rejoin_with.join(str_arr)
else:
return str_arr | bigcode/self-oss-instruct-sc2-concepts |
def split(seq):
"""
Split a sequence on zeros.
The given sequence is split into chunks separated by one or more
zeros. The start (inclusive) and end (exclusive) indices of the
chunks are returned as a list of 2-tuples.
"""
indices = []
start = None
for i, s in enumerate(seq):
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_caller(offset=0):
"""
lookup the caller of the current function from the stack,
with optional offset to climb higher up the stack.
"""
_, filename, linenum, funcname, _, _ = inspect.stack()[offset]
return {'filename': filename,
'linenum': linenum,
... | bigcode/self-oss-instruct-sc2-concepts |
def convert_iob_to_bio(seq):
"""Convert a sequence of IOB tags to BIO tags.
The difference between IOB and BIO (also called IOB2) is that in IOB
the B- prefix is only used to separate two chunks of the same type
while in BIO the B- prefix is used to start every chunk.
:param seq: `List[str]` The l... | bigcode/self-oss-instruct-sc2-concepts |
def filter_measurements(measurements, csc_name, topic_name):
"""Filter full list of measurements looking for CSC plus topic name.
Parameters
----------
measurements : list[str]
The list of all available measurements.
csc_name : str
Name of the CSC to filter on.
topic_name : str
... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def has_exactly_one_list_item(toc: str) -> bool:
"""Check if the toc has exactly one list item."""
assert toc
soup = BeautifulSoup(toc, "html.parser")
if len(soup.find_all("li")) == 1:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def getCheckCategoriesTemplate(usage, galleries, ncats):
"""Build the check categories template with all parameters."""
result = ('{{Check categories|year={{subst:CURRENTYEAR}}|month={{subst:'
'CURRENTMONTHNAME}}|day={{subst:CURRENTDAY}}\n')
usageCounter = 1
for (lang, project, article) in... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def pascal_case_to_enum(pascal_case: str) -> str:
"""Convert PascalCase to ENUM_CASE."""
word_arrays: List[List[str]] = [[]]
for c in pascal_case:
if c.isupper() and word_arrays[-1]:
word_arrays.append([c])
else:
word_arrays[-1].append(c.upp... | bigcode/self-oss-instruct-sc2-concepts |
import threading
def thread() -> int:
"""Return thread id."""
return threading.current_thread().ident or -1 | bigcode/self-oss-instruct-sc2-concepts |
def simple_hash(int_list, prime1, prime2, prime3):
"""Compute a hash value from a list of integers and 3 primes"""
result = 0
for integer in int_list:
result += ((result + integer + prime1) * prime2) % prime3
return result | bigcode/self-oss-instruct-sc2-concepts |
def gen_tagset(tags):
"""Create TagSet value from a dict."""
return [{'Key': key, 'Value': value} for key, value in tags.items()] | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def project_root_dir_path() -> Path:
"""
Get the project root directory as a Path object.
Returns
-------
project root directory
"""
# root = ../..
return Path(__file__).parent.parent | bigcode/self-oss-instruct-sc2-concepts |
def sort_by_index_key(x):
"""
Used as key in sorted() to order items of a dictionary by the @index
entries in its child-dicts if present.
"""
if isinstance(x[1], dict) and '@index' in x[1]:
return x[1]['@index']
else:
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def maybe_parentheses(obj, operator: str = " ") -> str:
"""
Wrap the string (or object's string representation) in parentheses, but only if required.
:param obj:
The object to (potentially) wrap up in parentheses. If it is not a string, it is converted
to a string first.
:param operator:... | bigcode/self-oss-instruct-sc2-concepts |
def condense_border_none(css: str) -> str:
"""Condense border:none; to border:0;.
"""
return css.replace('border:none;', 'border:0;') | bigcode/self-oss-instruct-sc2-concepts |
def flatten_obj(obj, fields, *, rest_val=None):
"""
>>> class A: pass
>>> a = A(); a.a = 1; a.b=2
>>> flatten_obj(a, ('a', 'b'))
[1, 2]
>>> flatten_obj(a, ('a', 'b', 'c'))
Traceback (most recent call last):
...
AttributeError: 'A' object has no attribute 'c'
>>> flatten_obj... | bigcode/self-oss-instruct-sc2-concepts |
def validate_bookcover(book_details):
"""
Check if goodreads returns a nophoto
Use open library to fetch the book cover
based on ISBN
Args:
book_details: Book info returned as json by goodreads API
Returns:
This API checks for book cover, and returns with a valid
bookco... | 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.