seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def fake_agent() -> str:
"""
The original FAKE_USER_AGENT in config.py:
'Mozilla/5.0 (Windows NT 6.1; rv:84.0) Gecko/20100101 Firefox/84.0'
Works with Startpage when nothing else will.
:return: static user agent string.
"""
# NOTE that the Firefox ver can be any from firefox_agent()
re... | bigcode/self-oss-instruct-sc2-concepts |
import math
def optimum_qubit_size(precision: int, error: float) -> int:
"""
Return the number of qubit required for targeted number of decimal
and error rate.
"""
return math.ceil(precision + math.log2(2+1/(2*error))) | bigcode/self-oss-instruct-sc2-concepts |
def get_current_weather_desc(data):
"""Get the current weather description. These values are undocumented.
:param data:
:return: e.g. 'Partly Cloudy', 'Light Rain'
"""
return data['current_condition'][0]['weatherDesc'][0]['value'] | bigcode/self-oss-instruct-sc2-concepts |
import csv
def save_to_csv(data: list, file_name: str) -> bool:
"""
Saved given data to .csv file.
Parameters
----------
data: list, required
Data produced by function prepare_data_to_save().
file_name: str, required
Path and file name to where save file. It should not include... | bigcode/self-oss-instruct-sc2-concepts |
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value)):
"""Format an argument spec from the 4 values ret... | bigcode/self-oss-instruct-sc2-concepts |
def get_roi_names(contour_data):
"""
This function will return the names of different contour data,
e.g. different contours from different experts and returns the name of each.
Inputs:
contour_data (dicom.dataset.FileDataset): contour dataset, read by dicom.read_file
Returns:
roi_se... | bigcode/self-oss-instruct-sc2-concepts |
def is_empty(any_structure):
"""Helper method to check if structure is empty."""
if any_structure:
return False
else:
return True | bigcode/self-oss-instruct-sc2-concepts |
def shift_induction_times(exp, min_start=20, min_end=30):
"""
Shifts the induction start and end times forward or backward by separately
specified numbers of minutes. Returns an experiment object with a new
induction record.
:param min_start: int
Number of minutes to shift induction start ... | bigcode/self-oss-instruct-sc2-concepts |
def phalf_from_ps(bk, pk, ps):
"""Compute pressure of half levels of hybrid sigma-pressure coordinates."""
return ps*bk + pk | bigcode/self-oss-instruct-sc2-concepts |
def get_shape_points(cur, shape_id):
"""
Given a shape_id, return its shape-sequence.
Parameters
----------
cur: sqlite3.Cursor
cursor to a GTFS database
shape_id: str
id of the route
Returns
-------
shape_points: list
elements are dictionaries containing th... | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_rsa_key(key_str):
"""Make Android and iOS RSA keys compatible with cryptography library.
Android and iOS have slightly wonky, non-standard key formats. This updates
the key to be standardized and compatible with pyca/cryptography.
"""
if key_str.startswith("-----BEGIN CERTIFICATE"):
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def reproduce(parent1, parent2):
"""generate offspring using random crossover"""
# random crossover point
crossover = random.randrange(0, len(parent1))
# construct children
child1 = parent1[0:crossover] + parent2[crossover:]
child2 = parent2[0:crossover] + parent1[crossover:]
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def transfer_weights(tf_model, torch_model):
""" Example function on how to transfer weights from tensorflow model to pytorch model
Parameters
----------
tf_model : tensorflow model
Weight donor
torch_model : pytorch model (torch.nn.Modules)
Weight recipient
... | bigcode/self-oss-instruct-sc2-concepts |
def service_level(orders_received, orders_delivered):
"""Return the inventory management service level metric, based on the percentage of received orders delivered.
Args:
orders_received (int): Orders received within the period.
orders_delivered (int): Orders successfully delivered within the p... | bigcode/self-oss-instruct-sc2-concepts |
def easy_emptylist(l):
"""Takes a list and returns True for empty list, False for nonempty"""
return not l | bigcode/self-oss-instruct-sc2-concepts |
def remove_dash(string):
"""
Removes the dash from the end of the string if there is one there.
:string: (str) an input string
:returns: (str) input string with no dash at the end of it
"""
if string[-1]=='-':
return string[:-1]
else:
return string | bigcode/self-oss-instruct-sc2-concepts |
def skewed_percentile_to_label(percentile):
"""
Assigns a descriptive term to the MMSE T-score based on its degree of skewness.
"""
if percentile > 24:
return 'WNL'
elif 9 <= percentile <= 24:
return 'Low Average'
elif 2 <= percentile <= 8:
return 'Below Average'
elif... | bigcode/self-oss-instruct-sc2-concepts |
def deleted_genes_to_reactions(model, genes):
""" Convert a set of deleted genes to the respective deleted reactions.
Arguments:
model (CBModel): model
genes (list): genes to delete
Returns:
list: list of deleted reactions
"""
if isinstance(genes, str):
genes = [ge... | bigcode/self-oss-instruct-sc2-concepts |
def paramsDictNormalized2Physical(params, params_range):
"""Converts a dictionary of normalized parameters into a dictionary of physical parameters."""
# create copy of dictionary
params = dict(params)
for key, val in params.items():
params[key] = val * (params_range[key][1]-params_ran... | bigcode/self-oss-instruct-sc2-concepts |
def REDUCE(_input, initial_value, _in):
"""
Applies an expression to each element in an array and combines them into a single value.
See https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/
for more details
:param _input: Can be any valid expression that resolves to an array.
:... | bigcode/self-oss-instruct-sc2-concepts |
def linear(x: float) -> float:
""" Linear activation function (simply returns the input, unchanged). """
return x | bigcode/self-oss-instruct-sc2-concepts |
def _pop_next_function(function_list):
"""Pops and returns the next function in the list."""
if not function_list:
raise IndexError('in _pop_next_function: list of functions is empty')
return function_list.pop(0) | bigcode/self-oss-instruct-sc2-concepts |
def get_symbols(bv):
"""Return all symbols in binary.
Args:
bv (BinaryView): top-level binary view handler. Lots of
interesting methods can be accessed.
Returns:
list: list of symbols in binary.
"""
total_symbols = list()
for s in bv.symbols.values():
... | bigcode/self-oss-instruct-sc2-concepts |
def _flatten_list(nested_list):
"""
Given a nested list, returns flat list of all its elements
:param nested_list: nested list
:return: flat list
"""
if not isinstance(nested_list, list):
return [nested_list]
res = []
for sub_list in nested_list:
res += _flatten_list(su... | bigcode/self-oss-instruct-sc2-concepts |
def dict_subset(d, keys):
"""Return a dict with the specified keys"""
result = {}
for key in keys:
if '.' in key:
field, subfield = key.split('.', 1)
if isinstance(d.get(field), dict):
subvalue = dict_subset(d[field], [subfield])
result.setdef... | bigcode/self-oss-instruct-sc2-concepts |
def ALMAGetBandLetter( freq ):
"""
Return the project observing band letter from frequency
* freq = Frequency in Hz
"""
if freq<117.0e9:
return "A3"
elif freq<163.0e9:
return "A4"
elif freq<211.0e9:
return "A5"
elif freq<275.0e9:
return "A6"
elif fre... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def is_active(url:str) -> bool:
"""Checks if the url we are parsing is active link.
Args:
url (str): [description]
Returns:
bool: True if get a 200 response else
"""
resp = requests.get(url)
return True if resp.status_code == 200 else False | bigcode/self-oss-instruct-sc2-concepts |
def is_peer_tuple(p):
"""Is p a (str,int) tuple? I.E. an (ip_address,port)"""
if type(p) == tuple and len(p) == 2:
return type(p[0]) == str and type(p[1]) == int
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def convert_to_int(s):
"""
Convert string to integer
:param s: Input string
:return: Interpreted value if successful, 0 otherwise
"""
try:
nr = int(s)
except (ValueError, TypeError):
nr = 0
return nr | bigcode/self-oss-instruct-sc2-concepts |
def create_language_method(language_code):
""" Creates a manager method that filters given language code """
def get_language(self):
return self.filter(i18n_language=language_code)
return get_language | bigcode/self-oss-instruct-sc2-concepts |
def addArray(pdo, field, vtkArray):
"""
Adds an array to a vtkDataObject given its field association
"""
# Point Data
if field == 0:
pdo.GetPointData().AddArray(vtkArray)
# Cell Data:
elif field == 1:
pdo.GetCellData().AddArray(vtkArray)
# Field Data:
elif field == 2:... | bigcode/self-oss-instruct-sc2-concepts |
def to_bytes(value, bytes_num, order='big', signed=False) -> bytes:
"""
Convert value to bytes representation.
# Arguments
value: int, Value to be converted.
bytes_num: int > 0, Number of bytes in representation of `value`.
Must be sufficiently big to store `value`
order: 'big' or 'small', Ordering of byte... | bigcode/self-oss-instruct-sc2-concepts |
def bunch(**kw):
"""
Create object with given attributes
"""
x = type('bunch', (object, ), {})()
for k, v in kw.items():
setattr(x, k, v)
return x | bigcode/self-oss-instruct-sc2-concepts |
def str2seq(st, func=int, sep=None):
""" "1 2 3" -> [func('1'), func('2'), func('3')]"""
# XXX check usage of this, check if we need list() at all
if sep is None:
return list(map(func, st.split()))
else:
return list(map(func, st.split(sep))) | bigcode/self-oss-instruct-sc2-concepts |
def detection_collate_fn(batch):
"""
Collate function used when loading detection datasets using a DataLoader.
"""
return tuple(zip(*batch)) | bigcode/self-oss-instruct-sc2-concepts |
def set_combinations(iterable):
"""
Compute all combinations of sets of sets
example:
set_combinations({{b}},{{e},{f}}) returns {{b,e},{b,f}}
"""
def _set_combinations(iter):
current_set = next(iter, None)
if current_set is not None:
sets_to_combine_with = _set_combin... | bigcode/self-oss-instruct-sc2-concepts |
def _tuple_2_id(num_single, idx):
"""Transfrom from tuple representation to id.
If idx is a tuple representation of a member of a couple, transform it to
id representation. Otherwise do nothing.
Raises:
TypeError if idx is neither an integer or a tuple
"""
if isinstance(idx, int):
return idx
el... | bigcode/self-oss-instruct-sc2-concepts |
def remove_title(soup):
"""
Remove the title element and return the str representation.
Args:
soup (BeautifulSoup): HTML parsed notebook.
Effect:
Changes soup object to have title (h1) element removed.
Returns:
(str): Title text
"""
title = str(soup.h1.contents[0])... | bigcode/self-oss-instruct-sc2-concepts |
def translate_points(points, translation):
"""
Returns the points translated according to translation.
"""
return points + translation | bigcode/self-oss-instruct-sc2-concepts |
def _check_byte_size(size: int) -> bool:
"""
Checks whether size is a valid size. Sizes include None or >= 0
:param size: The size to check
:type size: int
:return: Whether the size is valid
:rtype: bool
"""
if size is None:
return True
return size >= 0 | bigcode/self-oss-instruct-sc2-concepts |
def _check_boolean(input, name):
"""Exception raising if input is not a boolean
Checks whether input is not ``None`` and if not checks that the input is a
boolean.
Parameters
----------
input: any
The input parameter to be checked
name: str
The name of the variable for prin... | bigcode/self-oss-instruct-sc2-concepts |
def time_at_timestamp(timestamp_ms: int) -> float:
"""Convert millisecond Epoch timestamp to Python float time value.
Args:
timestamp_ms: Epoch timestamp in milliseconds.
Returns:
Python time value in float.
"""
return float(timestamp_ms) / 1000.0 | bigcode/self-oss-instruct-sc2-concepts |
def args_to_str(
args,
positional_arg=None,
fields=None,
to_flag=True,
arg_joiner=' ',
val_sep=' ',
list_joiner=' ',
):
"""Convert an argparse.ArgumentParser object back into a string,
e.g. for running an external command."""
def val_to_str(v):... | bigcode/self-oss-instruct-sc2-concepts |
def _acer_input(endfin, pendfin, aceout, dirout, mat,
temp=293.6, iprint=False, itype=1, suff=".00",
header="sandy runs acer",
photons=True,
**kwargs):
"""Write acer input for fast data.
Parameters
----------
endfin : `int`
tap... | bigcode/self-oss-instruct-sc2-concepts |
def _splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number."""
host, delim, port = host.rpartition(':')
if not... | bigcode/self-oss-instruct-sc2-concepts |
def create_draft_files_bp(app):
"""Create draft files blueprint."""
ext = app.extensions["invenio-rdm-records"]
return ext.draft_files_resource.as_blueprint() | bigcode/self-oss-instruct-sc2-concepts |
def list_pairs(validation_dates):
"""
For a set of ndates dates, return a list of indexes and IDs for all possible unique pairs.
For example, for ndates=3 -> [(0, 1), (0,2), (1,2)]
"""
ndates = len(validation_dates)
indexes = []
pair_ids = []
for k1 in range(ndates):
for k2 in r... | bigcode/self-oss-instruct-sc2-concepts |
def _right_child(node):
"""
Args:
node: index of a binary tree node
Returns:
index of node's right child
"""
return 2 * node + 2 | bigcode/self-oss-instruct-sc2-concepts |
def have_program(c, name):
"""
Returns whether connected user has program ``name`` in their ``$PATH``.
"""
return c.run("which {}".format(name), hide=True, warn=True) | bigcode/self-oss-instruct-sc2-concepts |
def has_remote(repo, remote_name):
"""Returns true if the given repository already has the named remote.
Args:
repo: The git.Repo object representing the repository.
remote_name: The remote name to be looked for.
"""
return remote_name in [x.name for x in repo.remotes] | bigcode/self-oss-instruct-sc2-concepts |
def count_format_specifiers(format_string):
"""Return the number of format specifiers in string format_string.
>>> count_format_specifiers("foo bar foo")
0
>>> count_format_specifiers("foo %d bar foo")
1
>>> count_format_specifiers("foo %d bar %i foo")
2
>>> count_format_specifiers("foo... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def cached_property(fun):
"""A memoize decorator for class properties.
Adapted from: http://code.activestate.com/recipes/576563-cached-property/
"""
@functools.wraps(fun)
def get(self):
try:
return self._cache[fun]
except AttributeError:
se... | bigcode/self-oss-instruct-sc2-concepts |
def merge(source1, source2):
"""Merge two dicts, source2 could override existing keys based on source1"""
return {**source1, **source2} | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def make_multidim(col, ndim):
"""Take a col with length=2 and make it N-d by repeating elements.
For the special case of ndim==1 just return the original.
The output has shape [3] * ndim. By using 3 we can be sure that repeating
the two input elements gives an output that is suffici... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_image_value_list(csv_file_name):
"""
Expects a csv file with header/structure:
filename, TE, mean_background
skips the first (header) line
returns a list of tuples with (filename, TE)
"""
image_value_list = []
with open(csv_file_name) as csvfile:
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_json_from_file(file_path):
"""Load json from a json file"""
with open(file_path) as json_data:
return json.load(json_data) | bigcode/self-oss-instruct-sc2-concepts |
async def in_voice_channel(ctx):
"""Checks that the command sender is in the same voice channel as the bot."""
voice = ctx.author.voice
bot_voice = ctx.guild.voice_client
if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel:
return True
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def place(cards, pos, card):
"""
Replaces the card at a given position in a list.
Example:
> place([1,4,7,10,12], 2, 9)
[1,4,9,10,12]
"""
result = cards[:]
result[pos] = card
return result | bigcode/self-oss-instruct-sc2-concepts |
def text_of_list(t):
"""
Convert a string list to multiline text.
"""
return '\n'.join(t) | bigcode/self-oss-instruct-sc2-concepts |
def trapmf(x, a, b, c, d):
"""
Trapezoidal membership function generator.
Parameters
========
x : single element array like
abcd : 1d array, length 4
Four-element vector. Ensure a <= b <= c <= d.
Returns
========
y : 1d array
Trapezoidal membership function.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Set
def import_declarations(import_set: Set[str]) -> str:
"""
Generate the import declaration(s) given the import specs.
:param import_set: import specs
:return: Go import declaration
>>> import_declarations(set())
''
>>> import_declarations({'time'})
'import "tim... | bigcode/self-oss-instruct-sc2-concepts |
def get_version(fname):
"""Reads PKG-INFO file generated by setuptools and extracts the Version
number."""
res = "UNK"
with open(fname, "r") as f:
for line in f.readlines():
line = line[:-1]
if line.startswith("Version:"):
res = line.replace("Version:", ""... | bigcode/self-oss-instruct-sc2-concepts |
def to_subscription_key(uid, event):
"""Build the Subscription primary key for the given guid and event"""
return u'{}_{}'.format(uid, event) | bigcode/self-oss-instruct-sc2-concepts |
def format_pathname(
pathname,
max_length):
"""
Format a pathname
:param str pathname: Pathname to format
:param int max_length: Maximum length of result pathname (> 3)
:return: Formatted pathname
:rtype: str
:raises ValueError: If *max_length* is not larger than 3
This... | bigcode/self-oss-instruct-sc2-concepts |
def encode_binary(x, width):
"""Convert integer x to binary with at least width digits."""
assert isinstance(x, int)
xb = bin(x)[2:]
if width == 0:
assert x == 0
return ''
else:
assert len(xb) <= width
pad = width - len(xb)
return '0' * pad + xb | bigcode/self-oss-instruct-sc2-concepts |
def dist(pt1, pt2):
"""Distance between two points"""
return ((pt2[0] - pt1[0])**2 + (pt2[1] - pt1[1])**2 + (pt2[2] - pt1[2])**2)**0.5 | bigcode/self-oss-instruct-sc2-concepts |
def filter_by_bidder_id(bids, bidder_id):
"""
>>> bids = [
... {"bidder_id": "1", "amount": 100},
... {"bidder_id": "1", "amount": 200},
... {"bidder_id": "2", "amount": 101}
... ]
>>> filter_by_bidder_id(bids, "1")
[{'amount': 100, 'bidder_id': '1'}, {'amount': 200, 'bidder... | bigcode/self-oss-instruct-sc2-concepts |
def get_distance(pt1, pt2):
""" Finds the distance between two points. """
x1 = pt1[0]
y1 = pt1[1]
x2 = pt2[0]
y2 = pt2[1]
return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Callable
def docfill(
*args,
template: Optional[str] = None,
**kwargs
):
"""Format the decorated function's docstring using given args and kwargs
This is useful if some functions share many common inputs or if the
range of valid values for a para... | bigcode/self-oss-instruct-sc2-concepts |
def app_request_type_label(app, request_type) -> str:
"""Format a label based on the application name and request type."""
return f"{app}\n({request_type})" | bigcode/self-oss-instruct-sc2-concepts |
import torch
def scalar_mult(x, y):
"""A function that does complex scalar multiplication between two complex scalars, x and y.
:param x: A complex scalar. (x[0], x[1]) = (real part, imaginary part).
:type x: torch.doubleTensor
:param y: A complex scalar. (x[0], x[1]) = (real part, imaginary part).
... | bigcode/self-oss-instruct-sc2-concepts |
def decode_text(value):
"""
Decode a text-like value for display.
Unicode values are returned unchanged. Byte strings will be decoded
with a text-safe replacement for unrecognized characters.
"""
if isinstance(value, bytes):
return value.decode('ascii', 'replace')
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def znes_colors(n=None):
"""Return dict with ZNES colors.
Examples
--------
>>> znes_colors().keys() # doctest: +ELLIPSIS
dict_keys(['darkblue', 'red', 'lightblue', 'orange', 'grey',...
Original author: @ckaldemeyer
"""
colors = {
'darkblue': '#00395B',
'red': '#B54036... | bigcode/self-oss-instruct-sc2-concepts |
def get_tags_string(tags):
"""
Returns a comma-delimited k=v string
Args:
tags (dict): A dictionary of key/value pairs
Returns:
str
"""
return ','.join([f'{k}={v}' for k, v in tags.items()]) | bigcode/self-oss-instruct-sc2-concepts |
def is_dataset(dataset):
"""
Check if input is a hdf dataset
e.g. is_dataset(hdf_group.get(address))
"""
return hasattr(dataset, 'size') | bigcode/self-oss-instruct-sc2-concepts |
def get_last_completed_launch(fw):
"""
Given a Firework object returns the last completed launch
"""
return next((l for l in reversed(fw.archived_launches + fw.launches) if
l.state == 'COMPLETED'), None) | bigcode/self-oss-instruct-sc2-concepts |
def _check_value(item, allowed_values, item_name=None, extra=None):
"""
Check the value of a parameter against a list of valid options.
Parameters
----------
item : object
Item to check.
allowed_values : tuple of objects
Allowed values to be checked against.
item_name : str ... | bigcode/self-oss-instruct-sc2-concepts |
def play_tictactoe_turn(action, board_state, turn):
"""
Input:
action:
0-8
an index into the board array
board_state:
(0,1,0,None,None,None,None,None,None)
a tuple of the board's state
turn:
1/0
the player's who's turn i... | bigcode/self-oss-instruct-sc2-concepts |
def filter_startswith_prefix(dataframe, prefix="TALON"):
"""Filter out rows where 'annot_gene_id' column value starts with prefix.
Args:
dataframe: pandas DataFrame
prefix: string
Returns:
pandas DataFrame
"""
not_starts_with_prefix = dataframe["annot_gene_id"].apply(
... | bigcode/self-oss-instruct-sc2-concepts |
def int_to_varint_hex(int_value):
"""
VARINT
<= 0xfc example: 12
<= 0xffff example: fd1234
Prefix is fd and the next 2 bytes are the VarInt (in little-endian).
<= 0xffffffff example: fe12345678
Prefix is fe and the next 4 bytes are the VarI... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import List
def validate_entry_context(entry_context: Any, keys: List[str], unpack_nested_elements: bool):
""" Validate entry context structure is valid, should be:
- For unpack_nested_elements==False:
1. List[Dict[str, str/bool/int/float]]
2. Lis... | bigcode/self-oss-instruct-sc2-concepts |
def progessbar(new, tot):
"""Builds progressbar
Args:
new: current progress
tot: total length of the download
Returns:
progressbar as a string of length 20
"""
length = 20
progress = int(round(length * new / float(tot)))
percent = round(new/float(tot) * 100.0, 1)
... | bigcode/self-oss-instruct-sc2-concepts |
def p1_for(input_list):
"""Compute some of numbers in list with for loop."""
out = 0
for i in input_list:
out += i
return out | bigcode/self-oss-instruct-sc2-concepts |
def precision(c, tweets):
"""Computes precision for class `c` on the specified test data."""
tp = 0
fp = 0
for tweet in tweets:
if c in tweet['predictions']:
if c in tweet['tags']:
tp+=1
else:
fp+=1
if(tp+fp == 0):
return floa... | bigcode/self-oss-instruct-sc2-concepts |
def getBondedNeighborLists(atoms, bondProxies):
"""
Helper function to produce a dictionary of lists that contain all bonded
neighbors for each atom in a set of atoms.
:param atoms: Flex array of atoms (could be obtained using model.get_atoms() if there
are no chains with multiple conformations, must ... | bigcode/self-oss-instruct-sc2-concepts |
def format_fasta(title, sequence):
"""
This formats a fasta sequence
Input:
title - String - Title of the sequence
sequence - String - Actual sequence
Output:
String - Fully formatted fasta sequence
"""
fasta_width = 70 # Number of characters in one line
n_lines = 1 + le... | bigcode/self-oss-instruct-sc2-concepts |
def vecBetweenBoxes(obj1, obj2):
"""A distance function between two TextBoxes.
Consider the bounding rectangle for obj1 and obj2.
Return vector between 2 boxes boundaries if they don't overlap, otherwise returns vector betweeen boxes centers
+------+..........+ (x1, y1)
| obj1 | ... | bigcode/self-oss-instruct-sc2-concepts |
def clip(string: str, length: int, suffix = "...") -> str:
"""Clip string to max length
If input `string` has less than `length` characters, then return the original string.
If `length` is less than the number of charecters in `suffix`, then return `string`
truncated to `length`.
Oth... | bigcode/self-oss-instruct-sc2-concepts |
def normalize(string):
"""Returns a string without outer quotes or whitespace."""
return string.strip("'\" ") | bigcode/self-oss-instruct-sc2-concepts |
import ast
def is_ast_equal(node_a: ast.AST, node_b: ast.AST) -> bool:
"""
Compare two ast tree using ast dump
"""
return ast.dump(node_a) == ast.dump(node_b) | bigcode/self-oss-instruct-sc2-concepts |
def decode_text_field(buf):
"""
Convert char[] string in buffer to python str object
:param buf: bytearray with array of chars
:return: string
"""
return buf.decode().strip(b'\x00'.decode()) | bigcode/self-oss-instruct-sc2-concepts |
def is_prime(number):
"""Check if a number is prime."""
if number < 2:
return False
if number == 2:
return True
if number % 2 == 0:
return False
for _ in range(3, int(number ** 0.5) + 1, 2):
if number % _ == 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import torch
def subtract_pose(pose_a, pose_b):
"""
Compute pose of pose_b in the egocentric coordinate frame of pose_a.
Inputs:
pose_a - (bs, 3) --- (x, y, theta)
pose_b - (bs, 3) --- (x, y, theta)
Conventions:
The origin is at the center of the map.
X is upward with ... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def setup(opts):
"""Set up directory for this GenomeHubs instance and handle reset."""
Path(opts["hub-path"]).mkdir(parents=True, exist_ok=True)
return True | bigcode/self-oss-instruct-sc2-concepts |
def accuracy(true_positives, true_negatives, false_positives, false_negatives, description=None):
"""Returns the accuracy, calculated as:
(true_positives+true_negatives)/(true_positives+false_positives+true_negatives+false_negatives)
"""
true_positives = float(true_positives)
true_... | bigcode/self-oss-instruct-sc2-concepts |
def rate_color(rate: int, units: str = '') -> str:
"""
Get color schema for percentage value.
Color schema looks like red-yellow-green scale for values 0-50-100.
"""
color = '[red]'
if 30 > rate > 20:
color = '[orange_red1]'
if 50 > rate > 30:
color = '[dark_orange]'
if 7... | bigcode/self-oss-instruct-sc2-concepts |
import time
def get_duration_timestamp(day=7):
"""
获取当前时间和7天前的时间戳
:param day:
:return:
"""
# 当前时间对应的时间戳
end = int(round(time.time() * 1000))
# 7天前的时间戳
start = end - day * 24 * 60 * 60 * 1000
return start, end | bigcode/self-oss-instruct-sc2-concepts |
def pass_through_filter(cloud, filter_axis='z', axis_limit=(0.6, 1.1)):
"""
Cut off filter
Params:
cloud: pcl.PCLPointCloud2
filter_axis: 'z'|'y'|'x' axis
axis_limit: range
Returns:
filtered cloud: pcl.PCLPointCloud2
"""
# Create a PassThrough filter object.
... | bigcode/self-oss-instruct-sc2-concepts |
def clean_text_up(text: str) -> str:
""" Remove duplicate spaces from str and strip it. """
return ' '.join(text.split()).strip() | bigcode/self-oss-instruct-sc2-concepts |
def case_convert(snakecase_string: str) -> str:
"""Converts snake case string to pascal string
Args:
snakecase_string (str): snakecase string
Returns:
str: Pascal string
"""
return snakecase_string.replace("_", " ").title().replace("Cnn", "CNN") | 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.