seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def _translate(pat):
"""Given a pattern, returns a regexp string for it."""
out = '^'
for c in pat:
if c == '*':
out += '.*'
else:
out += re.escape(c)
out += '$'
return out | bigcode/self-oss-instruct-sc2-concepts |
def _downsample_simple(arr, n):
"""
Skip n elements of a 1D array.
:param arr: 1D array.
:param n: integer which defines the skips.
:return: Downsampled 1D array.
"""
return arr[::n] | bigcode/self-oss-instruct-sc2-concepts |
def substitution_costs(c1, c2):
"""defines the costs of substitutions for the alignment"""
if c1[-1] == c2[-1]:
return 2
else:
return -3 | bigcode/self-oss-instruct-sc2-concepts |
def get_extrapolated_flux(flux_ref, freq_ref, spectral_index):
"""
Computes the flux density at 843 MHz extrapolated from a higher/lower flux
density measurement & some assumed spectral index.
input:
------
flux_ref: float
Reference flux density, usually S400 or S1400 [mJy].
freq_re... | bigcode/self-oss-instruct-sc2-concepts |
def flag(argument):
"""
Check for a valid flag option (no argument) and return ``None``.
(Directive option conversion function.)
Raise ``ValueError`` if an argument is found.
"""
if argument and argument.strip():
raise ValueError('no argument is allowed; "%s" supplied' % argument)
e... | bigcode/self-oss-instruct-sc2-concepts |
def remove_double_blanks(lines):
""" Takes a list of lines and condenses multiple blank lines into a single
blank line.
"""
new_lines = []
prev_line = "" # empty line here will remove leading blank space
for line in lines:
if len(line.strip()) or len(prev_line.strip()):
new_... | bigcode/self-oss-instruct-sc2-concepts |
def interpolation(x0, y0, x1, y1, x):
"""
Performs interpolation.
Parameters
----------
x0 : float.
The coordinate of the first point on the x axis.
y0 : float.
The coordinate of the first point on the y axis.
x1 : float.
The coordinate of the second point on the x a... | bigcode/self-oss-instruct-sc2-concepts |
def make_component_header(component, header):
"""
Function that extracts information from components
and adds it to the data header. The input header is
expected to come from Data.coords.header by default.
Parameters
----------
component: glue Component
Glue component to extract info... | bigcode/self-oss-instruct-sc2-concepts |
def _get_screenshot_data(driver) -> None:
"""
Returns the screenshot as base64 encoded data.
"""
return driver.get_screenshot_as_png() | bigcode/self-oss-instruct-sc2-concepts |
def to_secs(delta):
"""Convert a :py:class:`datetime.timedelta` to a number of seconds.
(This is basically a backport of
:py:meth:`datetime.timedelta.total_seconds`.)
"""
return (delta.days * 86400.0 +
delta.seconds +
delta.microseconds / 1000000.0) | bigcode/self-oss-instruct-sc2-concepts |
def fst(l):
"""Returns the first item in any list
Parameters
---------
l : list
the list we want to extract the first item from
Returns
-------
first item in list
"""
if isinstance(l, list):
return fst(l[0])
else:
return l | bigcode/self-oss-instruct-sc2-concepts |
def get_max_profit(stock_prices):
"""
Time Complexity: O(n)
Space Complexity: O(1)
n: number of stocks (length of the list)
"""
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
min_price = stock_prices[0]
max_profit = stock_prices[1] - s... | bigcode/self-oss-instruct-sc2-concepts |
def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | bigcode/self-oss-instruct-sc2-concepts |
def _prepare_hunk(hunk):
"""Drop all information but the username and patch"""
cleanhunk = []
for line in hunk.splitlines():
if line.startswith(b'# User') or not line.startswith(b'#'):
if line.startswith(b'@@'):
line = b'@@\n'
cleanhunk.append(line)
return... | bigcode/self-oss-instruct-sc2-concepts |
def odorant_distances(results, subject_id=None):
"""
Given the test results, returns a dictionary whose keys are odorant pairs
and whose values are psychometric distances between those pairs,
defined as the fraction of discriminations that were incorrect.
This can be limited to one subject indicated... | bigcode/self-oss-instruct-sc2-concepts |
def get_fps_number(avg_fps_msg: str) -> float:
"""Decodes FPS number from given "Avg FPS" string output by Peeking Duck
in the format: "... Avg FPS over last n frames: x.xx ..."
Args:
avg_fps_msg (str): Peeking Duck's average FPS message string
Returns:
float: Frames per second number
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_info_float(lines, rege):
"""Get the infromation form contents based on the regular expression."""
cp = re.compile(rege)
energy = 1000
for line in lines:
match = cp.search(line)
if match:
energy = float(match.group(1))
return energy | bigcode/self-oss-instruct-sc2-concepts |
def bbox_transform(bbox):
"""
[analog of SqueezeDet src/utils/util.py:bbox_transform()]
convert a bbox of form [cx, cy, w, h] to [xmin, ymin, xmax, ymax].
Works for numpy array or list of tensors.
"""
cx, cy, w, h = bbox
out_box = [[]]*4
out_box[0] = cx-w/2
out_box[1] = cy-h/2
out_box[2] = cx+w/... | bigcode/self-oss-instruct-sc2-concepts |
def boost_node(n, label, next_label):
"""Returns code snippet for a leaf/boost node."""
return "%s: return %s;" % (label, n['score']) | bigcode/self-oss-instruct-sc2-concepts |
def _Dij(A, i, j):
"""Sum of lower-left and upper-right blocks of contingency table."""
# See [2] bottom of page 309
return A[i+1:, :j].sum() + A[:i, j+1:].sum() | bigcode/self-oss-instruct-sc2-concepts |
def is_active(drone):
"""Check if the drone is in active state."""
return drone["State"]["Status"] == "Active" | bigcode/self-oss-instruct-sc2-concepts |
def get_title(soup):
"""
Get a topic title.
Examples
--------
>>> title_tag = '<title>title</title>'
>>> soup = make_soup(title_tag)
>>> get_title(soup)
'title'
"""
return soup.find('title').text.split('|')[0].strip() | bigcode/self-oss-instruct-sc2-concepts |
def create_indicator_entry(
indicator_type,
value,
pkg_id,
ind_id,
timestamp,
source=None,
score=None,
):
"""Creating a JSON object of given args
Args:
indicator_type: (str) indicator type
value: (str) indicator value
pkg_id: (str)... | bigcode/self-oss-instruct-sc2-concepts |
def create_document1(args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<h1 style="font-family: 'Trebuchet MS', Helvetica, sans-ser... | bigcode/self-oss-instruct-sc2-concepts |
def train_test_split(features, target, split_ts):
"""
Splits all provided TimeSeries instances into train and test sets according to the provided timestamp.
:param features: Feature TimeSeries instances to be split.
:param target: Target TimeSeries instance to be split.
:return: 4-tuple of the form... | bigcode/self-oss-instruct-sc2-concepts |
def get_item(config, section, key, *args):
"""
Return property value.
:param config: Configuration parser instance.
:param section: Section name in configuration with property to look for.
:param key: Name of the key to look for in section.
:param args: Can contains the default value (consi... | bigcode/self-oss-instruct-sc2-concepts |
def ndim(array, dims):
"""Return True IFF CRDS `array` object has number of dimensions `dims`.
>>> array = utils.Struct({"KIND":"IMAGE", "SHAPE" : (2048,2048), "TYPE": "float32"})
>>> ndim(array, 2)
True
>>> ndim(array, 3)
False
"""
return len(array.SHAPE) == dims | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_sb_ticket_id(ticket_url):
"""Extracts the supportbee ticket id from url"""
match = re.search(r'\/(\d+)', ticket_url)
return match.group(1) if match else None | bigcode/self-oss-instruct-sc2-concepts |
import base64
def b64d(s):
"""b64d(s) -> str
Base64 decodes a string
Example:
>>> b64d('dGVzdA==')
'test'
"""
return base64.b64decode(s) | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_whitespaces_and_hyphens(value):
"""
Returns value without whitespaces or -
"""
if not value:
return value
return re.sub(r'[\s-]+', '', value) | bigcode/self-oss-instruct-sc2-concepts |
def double(x: int) -> int:
"""
Doubles a number.
"""
return 2 * x | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_state(filename):
"""Load the annotation state stored in filename.
"""
with open(filename, 'rb') as input_state_file:
loaded_state = pickle.load(input_state_file)
return loaded_state | bigcode/self-oss-instruct-sc2-concepts |
def property_from_topic(mqtt_topic):
"""Extract the RuuviTag's property from the MQTT topic."""
return mqtt_topic.split("/")[3] | bigcode/self-oss-instruct-sc2-concepts |
def get_image_class_name(self, image_id):
""" Retrieves the image class name given an image id """
return self.image_infos[image_id]['class_name'] | bigcode/self-oss-instruct-sc2-concepts |
import re
def shorten_module(mod):
"""
Return a module name that is shorter but still useful, for
being displayed in logs
>>> shorten_module("civicboom/lib/helpers.py")
'lib.helpers'
"""
return re.sub("civicboom/(.*).py", "\\1", mod).replace("/", ".") | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def build_sorted_text_output(headline: str, content: List[Tuple[str, str, int]]) -> str:
"""
Takes a headline and a list of items and their respective descriptions,
sorts it and returns a nicely readable output
"""
content.sort()
output: str =... | bigcode/self-oss-instruct-sc2-concepts |
def get_rad_weekday(date):
"""
Returns numeric representation of a weekday according to RAD's data load
schedule.
:param date: date to return weekday for
:type value: datetime.date
"""
isoday = date.isoweekday()
if isoday == 7:
# Sunday
return 0
else:
return ... | bigcode/self-oss-instruct-sc2-concepts |
def chunk_to_parameter(chunk):
"""
:param chunk: List of numbers.
:return: String of numbers, comma delimited, no spaces.
"""
numbers = ''
for number in chunk:
numbers += '%s,' % number
# Remove last comma.
numbers = numbers[:-1]
return numbers | bigcode/self-oss-instruct-sc2-concepts |
import click
def _validate_repo_name(ctx, param, value):
"""Callback used to check if repository argument was given."""
if "/" not in value:
raise click.BadParameter('Expected format for REPOSITORY is '
'"<org_name>/<project_name>" (e.g "jcfr/sandbox")')
return val... | bigcode/self-oss-instruct-sc2-concepts |
from typing import TextIO
def skip_header(reader: TextIO) -> str:
"""Skip the header in reader and return the first real piece of data.
>>> infile = StringIO('Example\\n# Comment\\n# Comment\\nData line\\n')
>>> skip_header(infile)
'Data line\\n'
"""
# Read the descript... | bigcode/self-oss-instruct-sc2-concepts |
import random
def tr_get_asset_ip(params):
"""
return a random host IP, If params is defined as a network address returns an IP from that subnet
:param str params: Network address of the subnet from which to return a host IP
:return: Host IP
:rtype: str
"""
try:
if params ... | bigcode/self-oss-instruct-sc2-concepts |
def clean_corpus(df):
"""
Clean corpus of text for all documents.
"""
df.Text = df.Text.replace('\s+', ' ', regex=True) # Remove duplicate spaces
df.Text = df.Text.str.encode('ascii', 'ignore').str.decode('utf-8') # Encode in ascii to remove weird characters such as \uf0a7
#df.Text = df.Text.... | bigcode/self-oss-instruct-sc2-concepts |
def list_member(i_list1: list, i_list2: list):
"""
Compute the element common among i_list1 and i_list2;
not common among i_list1 and i_list2
:param i_list1: The source list
:param i_list2: The reference list
:return: (Common list, Not Common list)
"""
if len(i_list1) == 0:
... | bigcode/self-oss-instruct-sc2-concepts |
def get_4x4_translation(x,y,z):
"""return a matrix 4x4 for translation"""
a= [1,0,0,0]
b= [0,1,0,0]
c= [0,0,1,0]
d= [x,y,z,1]
return [a,b,c,d] | bigcode/self-oss-instruct-sc2-concepts |
def decorate_token(t, z_):
"""Make selected text boldface in Markdown format"""
dec = "**" if z_ == 1 else ""
return dec + t + dec | bigcode/self-oss-instruct-sc2-concepts |
import grp
import pwd
def _get_user_groups(user_name):
"""
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def _inverse_dict_lookup(dict: Dict[str, Any], value: Any):
""" Finds the first key in a dictionary with the input value. """
for k, v in dict.items():
if v == value:
return k
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_words(text, dedupe=True):
"""Get the words from a piece of text.
Args:
text: The text from which words should be extracted.
dedupe: Flag indicating if only unique words should be returned. Defaults to true.
Returns:
Iterable over string words found from the input... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def create_year(datum: str) -> Optional[int]:
"""Parse a year from the datum field."""
if datum is None or len(datum) < 4 or not datum[:4].isdigit():
return None
jaar = int(datum[:4])
if 1000 < jaar < 2000:
return jaar
return None | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_pickle(filepath: str) -> object:
"""
Loads a pickle file to memory.
:param filepath: Path pointing to file
"""
with open(filepath, 'rb') as handle:
return pickle.load(handle) | bigcode/self-oss-instruct-sc2-concepts |
def _TailSet(start_point, listing):
"""Returns set of object name tails.
Tails can be compared between source and dest, past the point at which rsync
was done. For example if test ran rsync gs://bucket1/dir gs://bucket2/dir2,
the tails for listings from bucket1 would start after "dir", while the tails
for l... | bigcode/self-oss-instruct-sc2-concepts |
def get_colour_set(n_colours, rng):
"""
Generates a (unique) list of randomly generated RGB colours.
# Arguments:
n_colours: the number of colours to generate.
rng: an instance of numpy.random.Generator.
# Returns:
colours: a list of randomly generated colours.
"""
colo... | bigcode/self-oss-instruct-sc2-concepts |
import warnings
def ignore_warnings(method):
"""Decorator for ignoring warnings"""
def _inner(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = method(*args, **kwargs)
return result
return _inner | bigcode/self-oss-instruct-sc2-concepts |
import torch
def subsequent_mask(size, device):
"""Mask out subsequent positions (adapted from
http://nlp.seas.harvard.edu/2018/04/03/attention.html)"""
attn_shape = (1, size, size)
subsequent_mask = torch.triu(torch.ones(attn_shape, device=device), diagonal=1)
return subsequent_mask == 0 | bigcode/self-oss-instruct-sc2-concepts |
def factorial(n):
"""Returns the factorial of a number n > 0.
This is a recursive function.
"""
if n == 0:
return 1
else:
return n * factorial(n-1) | bigcode/self-oss-instruct-sc2-concepts |
import string
def is_valid_file_name(str_input):
"""Returns if str is valid file name.
May only contain: ascii_lowercase, ascii_uppercase, digits, dot, dash, underscore
"""
allowed = set(string.ascii_lowercase + string.ascii_uppercase + string.digits + '.-_')
if str_input is not '':
return... | bigcode/self-oss-instruct-sc2-concepts |
def bt_analysis_tcm(bta, temp_min=300, temp_max=400, doping_min=1e19, doping_max=1e22):
"""
Performs analysis for transparent conductive materials
Focuses on T=300-400K and Doping=1E19-1E22
:param bta: Boltztrap analyzer object
:return: dict of conductivity and effective mass
"""
d = {}
... | bigcode/self-oss-instruct-sc2-concepts |
def clipping_dist(delta):
"""
Returns the average distance between residues i and j, based on experimental data.
Parameters
----------
delta : int
The delta between residue indexes i and j.
Returns
-------
float
The average distance.
"""
if delta == 1:
r... | bigcode/self-oss-instruct-sc2-concepts |
def _linestring_to_segments(arr):
"""
Translates line strip to segments
:param arr: numpy.array
Array of line strip vertices
:return: numpy.array
Line segments
"""
return [arr[i / 2] for i in range(0, len(arr) * 2)][1:-1] | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def CalcMd5(data):
"""
calculate the md5 of data
Args:
data : the data to calculate
Returns:
return md5 of data, if fail to calculate return None
"""
try:
md5 = hashlib.md5()
md5.update(data)
return md5.hexdigest()
except BaseExcepti... | bigcode/self-oss-instruct-sc2-concepts |
def hztous(hz):
"""
Convert frame rate in hz to microseconds between frames
"""
return (1/hz)*10**6 | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def read_cadence_file(filename):
"""
Parse a cadence file.
Args:
filename (str): Name of cadence file
Returns:
cadence_dict: dictionary containing cadence file contents
"""
with open(filename, 'r') as f:
cadence_dict = yaml.safe_load(f)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_table_position(screen_layout):
""" return first position of table encountered within screen layout
"""
for _, data in screen_layout.items():
if data.get('table'):
return data['position']
return None | bigcode/self-oss-instruct-sc2-concepts |
def same_fringe(tree1, tree2):
""" Detect is the given two trees have the same fringe. A fringe is a list
of leaves sorted from left to right.
"""
def is_leaf(node):
return len(node['children']) == 0
def in_order_traversal(node):
if node == None:
return []
if is... | bigcode/self-oss-instruct-sc2-concepts |
def get_hi_file_at_long(longitude, sgps_hi_file_list, edge_size=0.5):
"""
Identify the best SGPS file to retrieve data from at the supplied Galactic
longitude. Will try to find a file where the longitude is at least edge_size
away from the edge of the cube, but will fall back to any file with data
c... | bigcode/self-oss-instruct-sc2-concepts |
def number_of_ad_performance_threads() -> str:
"""The number of threads used to download ad performance"""
return '10' | bigcode/self-oss-instruct-sc2-concepts |
def formatOneTextRow(fields, values = None, fieldDLM="|@|"):
"""
Parameters in:
fields - a list of fields name
values - a dictionary of values with fields name, Default None
fieldDLM - delimeter of values, default "|@|"
Return:
if values is None, return fields with delimeters... | bigcode/self-oss-instruct-sc2-concepts |
def sub_domain_to_tld(domain):
"""
Turn the input domain to get Top Level Domain
Args:
domain: any domain value
Returns:
TLD of input domain
"""
domain_list = domain.split('.')[-2:]
return '.'.join(domain_list) | bigcode/self-oss-instruct-sc2-concepts |
def is_file_readable(file, strict=False):
"""Check if a file exists and is readable.
Parameters
----------
file : :class:`str`
The file to check.
strict : :class:`bool`, optional
Whether to raise the exception (if one occurs).
Returns
-------
:class:`bool`
Wheth... | bigcode/self-oss-instruct-sc2-concepts |
def assert_quality_condition(options, sds_file):
"""Assert that the SDSFile quality is in a list given in the options.
Parameters
----------
options : `dict`
The rule's options.
- ``qualities``: List of qualities to accept (`list` of `str`)
sds_file : `SDSFile`
The file bein... | bigcode/self-oss-instruct-sc2-concepts |
import six
def pretty_unicode(string):
"""
Make sure string is unicode, try to decode with utf8, or unicode escaped string if failed.
"""
if isinstance(string, six.text_type):
return string
try:
return string.decode("utf8")
except UnicodeDecodeError:
return string.decod... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def get_required(dist):
"""Return a set with all distributions that are required of dist
This also includes subdependencies and the given distribution.
:param dist: the distribution to query. Can also be the name of the distribution
:type dist: :class:`pkg_resources.Distribution... | bigcode/self-oss-instruct-sc2-concepts |
def read_POPI_points(file_name):
"""
Read the Point-validated Pixel-based Breathing Thorax Model (POPI) landmark points file.
The file is an ASCII file with X Y Z coordinates in each line and the first line is a header.
Args:
file_name: full path to the file.
Returns:
(list(tuple)): L... | bigcode/self-oss-instruct-sc2-concepts |
def update_from_dict(obj, update_dict):
"""
A function to update an object instance with values stored in a dictionary.
In some cases preferred over calling filter(pk=pk).update(**dict) because update does not send signals.
:param obj: The object instance to be updated
:param update_dict: A dictiona... | bigcode/self-oss-instruct-sc2-concepts |
import math
def haversine_bearing(lat1, lon1, lat2, lon2):
"""
Calculate the bearing from 1 point to 1 other
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
dlon = lon2 - lon1
... | bigcode/self-oss-instruct-sc2-concepts |
def get_style(line):
""" get plot styles from Line2D object
mostly copied from "Line2D.update_from"
Args:
line (Line2D): source of style
Return:
dict: line styles readily usable for another plot
"""
styles = {
'linestyle': line.get_linestyle(),
'linewidth': line.get_linewidth(),
'color... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Optional
def _process_api_resource(permission_resource: Dict[str, Any], api_operation: str) -> Optional[bool]:
"""Helper method to check if the api action permission is in this API resource
Args:
permission_resource: The dictionary for ... | bigcode/self-oss-instruct-sc2-concepts |
def windows_translator(value):
"""Translates a "windows" target to windows selections."""
return {
"@com_github_renatoutsch_rules_system//system:windows_x64": value,
"@com_github_renatoutsch_rules_system//system:windows_x64_msvc": value,
"@com_github_renatoutsch_rules_system//system:wind... | bigcode/self-oss-instruct-sc2-concepts |
def reshape_to_tf(tensor, dim=3):
"""Reshape the tensor to Tensorflow ordering.
This function assumes that your patch have
the same width for each dimension.
The types of tensors are supported
- Simple 2D patch sample
shape = (n_channels, patch_size, patch_size)
- 2D patch samples corp... | bigcode/self-oss-instruct-sc2-concepts |
def numlookup(x, y):
"""
Try to resolve y as a numberic, then try to
look it up a key in dictionary x.
"""
try:
return int(y)
except ValueError:
return x[y] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import io
def is_file_like(value: Any) -> bool:
"""Check if a value represents a file like object"""
return isinstance(value, io.IOBase) | bigcode/self-oss-instruct-sc2-concepts |
import struct
import socket
def address_in_network(ip, net):
"""
Is an address in a network
ip: 192.168.2.2
net:("192.168.2.0/24",)
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
for cur_net in net:
netaddr, bits = cur_net.split('/')
netmask = struct.unpack('=L',... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def img_tag(movie_id: int, frame: int, box: List[int]):
"""Get a 'standard' image tag as used by the face recognition stack.
"""
# Real example of full file name: 121614:3616:235_183_293_262.jpeg
# Face file names are <tag>.jpeg
return f"{movie_id}:{frame}" + ":{}_{}_{}_{}"... | bigcode/self-oss-instruct-sc2-concepts |
def self_embeds(url):
"""Does this url generate a usable embed on it's own when sent on discord?"""
return (
url.startswith("https://www.youtube.com")
or url.startswith("https://youtu.be")
or url.startswith("https://imgur.com")
or url.startswith("https://www.imgur.com")
o... | bigcode/self-oss-instruct-sc2-concepts |
def get_object_size_on_humans_retina(distance_to_object, object_height, focus_distance):
"""
Calculates an object size on human's retina
based on the object remoteness and its height
============================================================
The original formula is:
object_height / distanc... | bigcode/self-oss-instruct-sc2-concepts |
def w_s_update(u, S):
"""Computes the updates for the proxy of the derivative of u for smoothing
Parameters
----------
u : np.array of shape (None,)
Beamlet radiation distribution u
S : np.array of shape (None, None)
Returns
-------
w_next : list of np.array of shape (None,)
... | bigcode/self-oss-instruct-sc2-concepts |
def format_pdf_search_term(search_term, encoding='utf-8'):
"""Converts a unicode string into the way it might actually
exist in the bytes of a pdf document. so we can check if the text
made its way into the final pdf.
An example:
the text
'So\nmany\nlines'
becomes the bytes
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_mutation_string(instring):
"""Split a string with letters and numbers in it -- the number still stays a string though
Examples:
>>> split_mutation_string('A123F')
['A', '123', 'F']
"""
return re.split('(\d+)', instring) | bigcode/self-oss-instruct-sc2-concepts |
def Username(i, delegates, usernames):
"""
Returns delegates dictionary with username of delegate
from usernames.json file.
"""
name = delegates[i]['Name']
if name in usernames:
delegates[i]['Username'] = usernames[name]
else:
delegates[i]['Username'] = ('NEWBIE')
return... | bigcode/self-oss-instruct-sc2-concepts |
def one_dec_places(x, pos):
"""
Adds 1/10th decimal to plot ticks.
"""
return '%.1f' % x | bigcode/self-oss-instruct-sc2-concepts |
def fac(n):
"""Returns the factorial of n"""
if n < 2:
return 1
else:
return n * fac(n - 1) | bigcode/self-oss-instruct-sc2-concepts |
def remove_blank_spaces(syllables) -> list:
"""Given a list of letters, remove any blank spaces or empty strings.
>>> remove_blank_spaces(['', 'a', ' ', 'b', ' ', 'c', ''])
['a', 'b', 'c']
"""
cleaned = []
for syl in syllables:
if syl == " " or syl == '':
pass
else:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def format_numbers(nums: Tuple) -> str:
"""Format an array of numbers.
Parameters
----------
lst : Tuple
Array with numbers to be formatted
Returns
-------
str
String with number formatted
Example
-------
>>> format_numbers((2, 3, 10,... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_countries_metadata(fname="countries-readable.json"):
"""Read a database file containing information about different countries.
Specifically, we are interested in the capital and population of each country, because
we will use this information to disambiguate records, by giving more we... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_config(input_image, no_data_config):
"""Read config json file for valid pixel value ranges per band and image type.
Args:
input_image (str): Name of the image file - must contain image type e.g. sentinel2, planet_4m.
no_data_config (dict): Config dictionary as found in json ... | bigcode/self-oss-instruct-sc2-concepts |
def clean_text(txt):
"""Remove unnecessary spaces."""
return ' '.join(txt.strip().split()) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Type
from typing import TypeVar
def is_type_var(annotation: Type) -> bool:
"""Returns True if the annotation is a TypeVar."""
return isinstance(annotation, TypeVar) | bigcode/self-oss-instruct-sc2-concepts |
def remove_prefix(text: str) -> str:
"""
Removes prefix of a text based on : sign.
"""
return text.split(":", maxsplit=1)[1] if ":" in text else text | bigcode/self-oss-instruct-sc2-concepts |
def is_experiment_related(title):
"""Check if the title is experiment related."""
name = title.split(":")[1].lower()
long_keywords = [
"method",
"material",
"experimental"
# "materials and method",
# "methods and material",
# "experimental framework",
... | bigcode/self-oss-instruct-sc2-concepts |
def is_magic_5gon_ring(elements):
"""
Return True if elements (10-vector) form a "magic" ring
"""
total = sum(elements[0:3])
return sum(elements[2:5]) == total and sum(elements[4:7]) == total \
and sum(elements[6:9]) == total and elements[1] + sum(elements[8:10]) == total | 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.