seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def generate_artifact_link(owner: str, name: str) -> str:
"""Generate link for downloading artifacts
:param owner: Github repo owner name
:type owner: str
:param name: Github repo name
:type name: str
:returns: Link to api to download artifacts
:rtype: str
"""
return f"https://api.... | bigcode/self-oss-instruct-sc2-concepts |
def get_route_edge_attributes(
G, route, attribute=None, minimize_key="length", retrieve_default=None
):
"""
Get a list of attribute values for each edge in a path.
Parameters
----------
G : networkx.MultiDiGraph
input graph
route : list
list of nodes IDs constituting the pa... | bigcode/self-oss-instruct-sc2-concepts |
def compute_acc(pred, truth):
""" Compute accuracy """
return pred.max(dim=1)[1].eq(truth).sum() / len(pred) | bigcode/self-oss-instruct-sc2-concepts |
def is_sorted(lst, le_cmp=None):
""" Check if a list is sorted
Args:
lst (:obj:`list`): list to check
le_cmp (:obj:`function`, optional): less than equals comparison function
Returns
:obj:`bool`: true if the list is sorted
"""
if le_cmp:
return all(le_cmp(a, b) for ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_column_width(max_value, decimals=5):
"""Get width of column to pass to :func:`numpy.savetxt`, accounting
for the decimal point and a sign +/-.
"""
return len(str(int(max_value // 1))) + decimals + 2 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cosine_similarity(v1, v2):
"""Cosine similarity [-1, 1].
Parameters
----------
v1, v2 : Tensor
Tensor with the same shape [batch_size, n_feature].
References
----------
- `Wiki <https://en.wikipedia.org/wiki/Cosine_similarity>`__.
"""
return torch.sum(t... | bigcode/self-oss-instruct-sc2-concepts |
def list2string(ls):
"""Print a list as a string"""
s = " ".join(ls)
return s | bigcode/self-oss-instruct-sc2-concepts |
import random
def shred(d, prefix=None, existing=False, contigs=10000, minsize=500,
maxsize=10000):
"""
Generate random shreds of input fasta file
:param d: Dictionary of sequences
:param prefix: Prefix string to append to random contigs
:param existing: Use existing prefix string ('|' ... | bigcode/self-oss-instruct-sc2-concepts |
def str2int(val):
"""
Converts a decimal or hex string into an int.
Also accepts an int and returns it unchanged.
"""
if type(val) is int:
return int(val)
if len(val) < 3:
return int(val, 10)
if val[:2] == '0x':
return int(val, 16)
return int(val, 10) | bigcode/self-oss-instruct-sc2-concepts |
def check_file_extension(filename, extension_list):
""" Check if the extension file match with the authorized extension list
:param string filename: Filename to check
:param list extension_list: The list of extension the file have to match to
:return: True if the extension is correct, False... | bigcode/self-oss-instruct-sc2-concepts |
def human_bytes(n):
"""
Return the number of bytes n in more human readable form.
"""
if n < 1024:
return '%d B' % n
k = n/1024
if k < 1024:
return '%d KB' % round(k)
m = k/1024
if m < 1024:
return '%.1f MB' % m
g = m/1024
return '%.2f GB' % g | bigcode/self-oss-instruct-sc2-concepts |
def format_integer(number, group_size=3):
"""Formats integers into groups of digits."""
assert group_size > 0
number = str(number)
parts = []
while number:
number, part = number[:-group_size], number[-group_size:]
parts.append(part)
number = ' '.join(reversed(parts))
return number | bigcode/self-oss-instruct-sc2-concepts |
def surrogate_pairs(code_point):
"""Return the UTF-16 high and low surrogates for a unicode code point.
Arguments:
code_point -- A string representation of the form 'U+xxxxx' or '\Uxxxxxxxx'
Returns:
A tuple containing the surrogate pairs as hexadecimal strings:
(high, low), or (code_point,) i... | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def get_spaced_colors(n):
"""Create n evenly spaced RGB colors
:param n: number of colors needed
source: https://stackoverflow.com/questions/876853/generating-color-ranges-in-python
"""
hsv_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)]
rgb_tuples = map(lambda x: colorsy... | bigcode/self-oss-instruct-sc2-concepts |
def get_all_moves(coord):
""" Return a list of all coordinates reachable from this one """
return [{'x': coord['x'], 'y': coord['y'] + 1}, {'x': coord['x'], 'y': coord['y'] - 1}, {'x': coord['x'] + 1, 'y': coord['y']}, {'x': coord['x'] - 1, 'y': coord['y']}] | bigcode/self-oss-instruct-sc2-concepts |
def below(prec, other_prec):
"""Whether `prec` is entirely below `other_prec`."""
return prec[1] < other_prec[0] | bigcode/self-oss-instruct-sc2-concepts |
def _find_lines_from_point(d={}, ptag=-1):
"""Find lines that have the given point tag
Parameters
----------
d : Dictionary
GMSH dictionary
ptag : int
point tag
Returns
-------
ltag : int
List of line tags
"""
lines = list()
for s_data in d.values():... | bigcode/self-oss-instruct-sc2-concepts |
def _crc_update(crc, data, mask, const):
"""
CRC8/16 update function taken from _crc_ibutton_update() function
found in "Atmel Toolchain/AVR8 GCC/Native/3.4.1061/
avr8-gnu-toolchain/avr/include/util/crc16.h" documentation.
@param[in] crc current CRC value
@param[in] data next byte of data
@p... | bigcode/self-oss-instruct-sc2-concepts |
def xor(bytes_1, bytes_2):
"""XOR two bytearrays of the same length."""
l1 = len(bytes_1)
l2 = len(bytes_2)
assert l1 == l2
result = bytearray(l1)
for i in range(l1):
result[i] = bytes_1[i] ^ bytes_2[i]
return result | bigcode/self-oss-instruct-sc2-concepts |
def cgi2dict(form, linelist):
"""Convert the form from cgi.FieldStorage to a python dictionary"""
params = {'linelist': linelist.value}
for key in form.keys():
if key != 'linelist':
params[key] = form[key].value
return params | bigcode/self-oss-instruct-sc2-concepts |
def _2d_distance_squared(position1, position2):
"""calculate the square of the distance bwtween two 2D coordinate tuples"""
return (position1[0] - position2[0]) ** 2 + (position1[1] - position2[1]) ** 2 | bigcode/self-oss-instruct-sc2-concepts |
def read_target_positions(file_path, filter_chromosomes):
"""
reads a bed file and returns a list of tuples containing genomic coordinates
"""
if filter_chromosomes==None:
filter_chromosomes = []
else:
print('filtering out: ' + ' '.join(filter_chromosomes))
with open(file_path) a... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
from typing import Dict
from typing import Union
def tags_to_filter(
tags: List[Tuple[str, str]]
) -> List[Dict[str, Union[str, List[str]]]]:
"""Turn list of tuples with tag name and value in to AWS format."""
return [{"Name": f"tag:{tag[0]}", "Values": [ta... | bigcode/self-oss-instruct-sc2-concepts |
def get_unbound_arg_names(arg_names, arg_binding_keys):
"""Determines which args have no arg binding keys.
Args:
arg_names: a sequence of the names of possibly bound args
arg_binding_keys: a sequence of ArgBindingKey each of whose arg names is
in arg_names
Returns:
a sequence of... | bigcode/self-oss-instruct-sc2-concepts |
def apply_type_recognizers(recognizers, type_obj):
"""Apply the given list of type recognizers to the type TYPE_OBJ.
If any recognizer in the list recognizes TYPE_OBJ, returns the name
given by the recognizer. Otherwise, this returns None."""
for r in recognizers:
result = r.recognize(type_obj)... | bigcode/self-oss-instruct-sc2-concepts |
def rgb_color(color: str) -> tuple:
"""Convert an RGB color string to an RGB tuple.
>>> rgb_color('#fff')
(15, 15, 15)
>>> rgb_color('#500100')
(80, 1, 0)
"""
color = color.lstrip('#')
if len(color) == 3:
return (int(color[0], 16),
int(color[1], 16),
... | bigcode/self-oss-instruct-sc2-concepts |
def huffman_encoding_recursion(node, code=''):
"""
Encoding characters using recursion
Args:
node(HuffManTreeNode): leaf to save data and non-leaf node assign 0 and 1 to edges
code(str): Assign 0 to the left edge and 1 to the right edge
Returns:
encode_map(dict) : huffman coding map... | bigcode/self-oss-instruct-sc2-concepts |
def label2nodename(label):
"""
convert label e.g. '(1,2)' to nodename e.g. 'n1c2'
"""
lsplit = label.split(',')
return 'n' + lsplit[0][1:] + 'c' + lsplit[1][:-1] | bigcode/self-oss-instruct-sc2-concepts |
import socket
def is_ipv6(ip: str) -> bool:
"""
A helper function that checks if a given IP address is a valid IPv6 one.
Parameters
----------
ip: :class:`str`
A string representing an IP address.
"""
try:
socket.inet_pton(socket.AF_INET6, ip)
return True
e... | bigcode/self-oss-instruct-sc2-concepts |
def read_form_field_string(model, form, field_name, transformation=None):
"""
:param model: Model containing string field
:param form: Form data from front-end
:param field_name: Name of field shared by model and form
:param transformation: Transformation of form data to perform before inserting int... | bigcode/self-oss-instruct-sc2-concepts |
def MAV(data):
"""
Mean absolute value: the average of the absolute value of the signal.
Parameters
----------
data: array-like
2D matrix of shape (time, data)
Returns
-------
MAVData: 1D numpy array containing average absolute value
Reference
---------
Hudgins, B., Parker, P., & Scott, R. N. ... | bigcode/self-oss-instruct-sc2-concepts |
def linear_interpolation(pos):
"""
Easing function for animations: Linear Interpolation.
"""
return pos | bigcode/self-oss-instruct-sc2-concepts |
def get_github_path(owner: str, repo: str) -> str:
"""Get github path from owner and repo name"""
return "%s/%s" % (owner, repo) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def natoms(self):
"""
Sequence of number of sites of each type associated with the Poscar.
Similar to 7th line in vasp 5+ POSCAR or the 6th line in vasp 4 POSCAR.
"""
return [len(tuple(a[1])) for a in itertools.groupby(self.syms)] | bigcode/self-oss-instruct-sc2-concepts |
def recookie(wrapped):
"""
Decorator to mark a session as needing to recookie.
This is necessary when setting a new max-age/etc
:param wrapped: a function to wrap with this decorator.
:returns wrapped_recookie: a wrapped function.
"""
def wrapped_recookie(session, *arg, **kw):
resu... | bigcode/self-oss-instruct-sc2-concepts |
def convertDate(time):
"""
Returns the converted time, accept only this format DD/MM/YYYY
Parameters:
time (string)
Returns:
time (int): return converted time as this format YYYYMM, so year and month
"""
tmp = time.split("/")
retu... | bigcode/self-oss-instruct-sc2-concepts |
def mutindex2pos(x, start, end, mut_pos):
"""
Convert mutation indices back to genome positions
"""
if x == -.5:
return start
elif x == len(mut_pos) - .5:
return end
else:
i = int(x - .5)
j = int(x + .5)
return (mut_pos[i] + mut_pos[j]) / 2.0 | bigcode/self-oss-instruct-sc2-concepts |
def peel(event):
"""
Remove an event's top-level skin (where its flavor is determined), and return
the core content.
"""
return list(event.values())[0] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
import json
def cors_web_response(status_code: int, body: Dict[str, str]):
"""Create a response when dealing with CORS."""
return {
'statusCode': status_code,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,X-Amz-Security-Token,Authoriz... | bigcode/self-oss-instruct-sc2-concepts |
def parse_env_var_args(env_var_args):
"""
:param List[str] env_var_args:
List of arguments in the form "VAR_NAME" or "VAR_NAME=VALUE"
:return: Dict[str,str]
Mapping from "VAR_NAME" to "VALUE" or empty str.
"""
env_vars = {}
if env_var_args is not None:
for arg in env_var_... | bigcode/self-oss-instruct-sc2-concepts |
def get_active_sessions_orchestrator(
self,
) -> list:
"""Get all current active sessions on Orchestrator
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - activeSessions
- GET
- /session/activeSessions
:return:... | bigcode/self-oss-instruct-sc2-concepts |
def file_parser_old(line, config):
"""
Parse Markdown page for compomics.github.io pages:
- Replace wiki URLs to pages URLs
"""
line = line.replace(
"https://github.com/{}/{}/wiki/".format(config['user'], config['project_name']),
"https://compomics.github.io/projects/{}/wiki/".forma... | bigcode/self-oss-instruct-sc2-concepts |
import re
def preprocess_sentences(sentences, SOS, EOS):
"""
Preprocess the input text by
lowercasing
adding space around punctuation
removing strange characters
tokenizing on whitespace
(optional) reversing the words as suggested by the Seq2Seq paper
adding <SOS> and <EOS>... | bigcode/self-oss-instruct-sc2-concepts |
def moving_avg(xyw, avg_len):
"""
Calculate a moving average for a given averaging length
:param xyw: output from collapse_into_single_dates
:type xyw: dict
:param avg_len: average of these number of points, i.e., look-back window
:type avg_len: int
:return: list of x values, list of y value... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def _filter_change_sets(change_sets: list, artifact_filter) -> list:
"""Filter the change sets with given artifact filter
"""
result = []
for commit in change_sets:
mod_commit = copy.deepcopy(commit)
# grab only source files
mod_commit["file_path"] = list(
... | bigcode/self-oss-instruct-sc2-concepts |
def _tls_version_check(version, min):
"""Returns if version >= min, or False if version == None"""
if version is None:
return False
return version >= min | bigcode/self-oss-instruct-sc2-concepts |
def get_serializer_error_response(error):
"""
Returns error response from serializer
:param str error: message
:return: error_response
:rtype: object
"""
error_response = {"status": 422, "data": [], "message": error}
return error_response | bigcode/self-oss-instruct-sc2-concepts |
def standardize(X):
"""Z-transform an array
param X: An N x D array where N is the number of examples and D is the number of features
returns: An N x D array where every column has been rescaled to 0 mean and unit variance
"""
return (X - X.mean())/X.std(ddof=1) | bigcode/self-oss-instruct-sc2-concepts |
def default_prompt(category: str) -> str:
"""Create the user prompt for selecting categories of options.
Args:
category (str): The type of thing being selected (assignment, section, etc)
Returns:
str: The user prompt
"""
return f"Which {category} would you like to grade? >>> " | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
import torch
def create_grid(
grid_sizes: List[int],
grid_bounds: List[Tuple[float, float]],
extend: bool = True,
device="cpu",
dtype=torch.float,
) -> List[torch.Tensor]:
"""
Creates a grid represented by a list of 1D Tensors representing t... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_slug(model) -> str:
"""Generate a unique slug
Args:
model (cls): Django Model
Returns:
slug (string)
"""
query_manager = model.objects
slug = uuid.uuid4().hex[:6]
while query_manager.filter(slug=slug).exists():
slug = uuid.uu... | bigcode/self-oss-instruct-sc2-concepts |
def extract_indices_python( original_indices, selected_indices,
pid, selected_pid, preserve_particle_index ):
"""
Go through the sorted arrays `pid` and `selected_pid`, and record
the indices (of the array `pid`) where they match, by storing them
in the array `selected_indices` (... | bigcode/self-oss-instruct-sc2-concepts |
def get_biggest_face(array_of_faces):
"""
:param array_of_faces: array of faces returned from detector.detectMultiScale()
:return: a 1x4 array containing the face with the biggest area (width*height)
"""
largest_area = 0
largest_face = None
for face in array_of_faces:
area = face[2] ... | bigcode/self-oss-instruct-sc2-concepts |
def escapeAttr(sText):
"""
Escapes special character to HTML-safe sequences.
"""
sText = sText.replace('&', '&')
sText = sText.replace('<', '<')
sText = sText.replace('>', '>')
return sText.replace('"', '"') | bigcode/self-oss-instruct-sc2-concepts |
def area(r, shape_constant):
"""Return the area of a shape from length measurement R."""
assert r > 0, 'A length must be positive'
return r * r * shape_constant | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def generate_hash(value, hash='sha1'):
"""
Generate a hash for a given value.
By default generate a `sha1` hash.
Other hash can be specified. If so all supported hash
algorithms are listed in `hashlib.algorithms`.
Returns a String.
"""
sha_obj = getattr(hashlib, hash... | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_words(sentstr, stops):
"""
simple utility to word tokenize a text string and remove stop words
:param sentstr: input string of text
:param stops: list of stop words to remove
:return:
"""
words = re.sub(r"[^\w]", " ", sentstr).split()
cleaned_text = [w.lower() for... | bigcode/self-oss-instruct-sc2-concepts |
def TTD_TT_UB_rule(M, i, j, w, t):
"""
Every day of every week for each (window, ttype), there can
be no more people scheduled (TourTypeDay) than
number of people assigned to TourType[window, ttype].
:param M: Model
:param i: window
:param j: day
:param w: week
:param t: tour type
... | bigcode/self-oss-instruct-sc2-concepts |
def word_count(data):
"""
输入一个字符串列表,统计列表中字符串出现的次数
参数
----
data: list[str],需要统计的字符串列表
返回
----
re: dict,结果hash表,key为字符串,value为对应的出现次数
"""
re = {}
for i in data:
re[i] = re.get(i, 0) + 1
return re | bigcode/self-oss-instruct-sc2-concepts |
import random
def gen_next_match_pick_randomly(population):
""" Decides next two player indexes who will play against each other by randomly selecting two players
from the list of players available"""
available_players = [player for player in population if player.available]
p1 = random.choice(availab... | bigcode/self-oss-instruct-sc2-concepts |
def list_or_none(lst):
"""Returns a stringified list or 'None'."""
return ",".join(map(str, lst)) if lst else "None" | bigcode/self-oss-instruct-sc2-concepts |
def GetDimensions(line):
"""
Parse and extract X, Y and Z dimensions from string
Parameters
----------
line: string
Line containing x, y, z dimensions
Returns
-------
(nx,ny,nz): (int,int,int)
The dimensions on x, y, and z coordinate respectively
... | bigcode/self-oss-instruct-sc2-concepts |
def get_serial_number_key(serial_num: str) -> str:
"""Get the compressed search serial number key for the MH serial number."""
key: str = ''
if not serial_num:
return key
key = serial_num.strip().upper()
if len(key) > 20:
return key[0:20]
return key | bigcode/self-oss-instruct-sc2-concepts |
def isValidId(id_, v=0x0110000100000000, y=1):
"""Reverse Steam ID formula taking full community ID and decoding the account ID.
Args:
id_ (int) : steam community id
v (int, optional) : account type, defaults to user: 0x0110000100000000
y (int, optional) : account universe, defaults to p... | bigcode/self-oss-instruct-sc2-concepts |
import re
def cut_iframes(value):
"""
Filter which cut <iframe> tags.
"""
pattern = re.compile(r'<p><iframe .*</iframe></p>')
return re.sub(pattern, '', value) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def timestamp_from_dt(dt, epoch=datetime(1970, 1, 1)):
"""
Convert a datetime to a timestamp.
https://stackoverflow.com/a/8778548/141395
"""
delta = dt - epoch
# return delta.total_seconds()
return delta.seconds + delta.days * 86400 | bigcode/self-oss-instruct-sc2-concepts |
def _get_specie_str(specie, include_phase):
"""Gets the specie string
Parameters
----------
specie : :class:`~pmutt.empirical.nasa.Nasa` object
Specie to use
include_phase : bool, optional
If True, includes the reaction phase. Default is True
Returns
-------
... | bigcode/self-oss-instruct-sc2-concepts |
def critical_events_in_outputs(healthcheck_outputs):
"""Given a list of healthcheck pairs (output, healthy), return
those which are unhealthy.
"""
return [healthcheck for healthcheck in healthcheck_outputs if healthcheck[-1] is False] | bigcode/self-oss-instruct-sc2-concepts |
def align_origin(origin, w, h, align=('left','top')):
"""Calculates size of text box and returns an origin as if aligned
from the given origin.
Accepted alignments are:
left, center, right
top, center, bottom"""
if align==('left','top'):
return origin
aligns = {'left': 0, 'center':... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _build_transform_name(lag, tfm, *args) -> str:
"""Creates a name for a transformation based on `lag`, the name of the function and its arguments."""
tfm_name = f'{tfm.__name__}_lag-{lag}'
func_params = inspect.signature(tfm).parameters
func_args = list(func_params.items())[1:] # re... | bigcode/self-oss-instruct-sc2-concepts |
def _GetFailedRevisionFromCompileResult(compile_result):
"""Determines the failed revision given compile_result.
Args:
compile_result: A dict containing the results from a compile. Please refer
to try_job_result_format.md for format check.
Returns:
The failed revision from compile_results, or None i... | bigcode/self-oss-instruct-sc2-concepts |
import urllib.request
def read_url(url):
"""Send a GET request to a given URL and read the response.
References
----------
- https://docs.python.org/3/howto/urllib2.html
- https://docs.python.org/3/library/http.client.html#httpresponse-objects
"""
with urllib.request.urlopen(url) as res... | bigcode/self-oss-instruct-sc2-concepts |
def k_func(h,s_H,s_K,g,n,alpha,phi,delta,k):
"""args:
h (float): Human capital
s_h (float): Investments in human capital
s_k (float): Investments in physical capital
g (float): Growth in technology
n (float): Growth rate of population/labour force
delta (float): Depreciation ... | bigcode/self-oss-instruct-sc2-concepts |
def agenda_format_day(
number_of_days_before,
date_start,
cfg_today,
cfg_tomorrow,
cfg_in_days,
):
"""
Formats the string who indicates if the event is today, tomorrow, or else
in an arbitrary number of day.
Args:
number_of_days_before (int): The number of days before th... | bigcode/self-oss-instruct-sc2-concepts |
def minmax(x):
"""
Returns a tuple containing the min and max value of the iterable `x`.
.. note:: this also works if `x` is a generator.
>>> minmax([1, -2, 3, 4, 1, 0, -2, 5, 1, 0])
(-2, 5)
"""
(minItem, maxItem) = (None, None)
for item in x:
if (minItem is None) or (item < m... | bigcode/self-oss-instruct-sc2-concepts |
def daily_return(t_df):
""" add daily return column to the data frame """
dlyr = t_df['Close'].shift(1) / t_df['Close'] - 1
t_df['Daily Return'] = dlyr * 100
return t_df | bigcode/self-oss-instruct-sc2-concepts |
def count_entities(entities, project=None, locale=None):
"""Count the number of entities (i.e. source strings) with the given project and/or locale."""
count = 0
for ent in entities:
if (project is None or project == ent["project"]) and (
locale is None or locale == ent["locale"]
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def read_spectrum(filestream, n):
"""Reads n mz and intensity pairs from existing .sbd filestream. Assumes double
precision for mass and single for intensity.
Returns:
Tuple:tuple of mz and intensity vectors
"""
mzs = struct.unpack("<%dd" % n, filestream.read(8 * n))... | bigcode/self-oss-instruct-sc2-concepts |
def crop_image(new_width, new_height, image):
"""
Method to crop a given input image to new width and height specifications given.
Args:
new_width: Width of the cropped image
new_height: Height of the cropped image
image: Image object to be processed
Returns:
The croppe... | bigcode/self-oss-instruct-sc2-concepts |
import pytz
def local_time_obj(time, course):
""" Get a Datetime object in a course's locale from a TZ Aware DT object."""
if not time.tzinfo:
time = pytz.utc.localize(time)
return time.astimezone(course.timezone) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
def moving_average(source: Sequence[float], window_size: int):
"""
Compute a simple moving average from a source list.
Arguments:
source: The source list of data from which to compute the moving average.
window_size: The size of the moving average to com... | bigcode/self-oss-instruct-sc2-concepts |
def minimum_grade(parsed_list, passing_grade, overall_min=True):
"""
This function calculates the minimum grade from the given grades.
:param parsed_list: the parsed list of the grades
:param passing_grade: the grade passing threshold
:param overall_min: True, when calculating the minimum of all th... | bigcode/self-oss-instruct-sc2-concepts |
def detect_faces(image, cascade, scale_factor, min_neighbours):
"""
Detect faces visible on the image.
:param cascade: cascade object used for detection
:param image: analyzed image
:param scale_factor: subsequent detections scaling coefficient
:param min_neighbours: minimum detection neighbours... | bigcode/self-oss-instruct-sc2-concepts |
def cuberoot(x):
"""Finds the cube root of x"""
return x**(1./3.) | bigcode/self-oss-instruct-sc2-concepts |
def strip_tags(body):
"""Delete the first and last line if they full of hashtags.
Also strip every line of unnecessary whitespaces."""
lines = body.split('\n')
# remove last line if full of hashtags
for word in lines[-1].split():
if word[0] != '#':
break
else:
del li... | bigcode/self-oss-instruct-sc2-concepts |
def createProtein(element):
"""
Create dictionary representation of Protein element from Percolator XML output
"""
defns = element.nsmap[None] #default namespace
protein = {}
protein["ID"] = element.get("{{{}}}protein_id".format(defns))
protein["q-value"] = float(element.find("{{{}}}q_v... | bigcode/self-oss-instruct-sc2-concepts |
def get_params_fit(data_pt, params_fix):
"""Returns the fitted parameters a specific data point depends on."""
data_pt_params = (
(
data_pt.get_fitting_parameter_names() |
data_pt.get_fixed_parameter_names()
) - params_fix
)
return data_pt_params | bigcode/self-oss-instruct-sc2-concepts |
def _re_word_boundary(r):
"""
Adds word boundary characters to the start and end of an
expression to require that the match occur as a whole word,
but do so respecting the fact that strings starting or ending
with non-word characters will change word boundaries.
"""
# we can't use \b as it c... | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_documents_by_feature_value(input_dict):
"""
Split Annotated Document Corpus by conditions with features and values.
:param adc: Annotated Document Corpus
:param feature_condition: split condition.
:param discard_filtered_out default-false: discard documents that do not fulfil... | bigcode/self-oss-instruct-sc2-concepts |
def get_properties(schema):
""" Return the three properties we have to enforce for this schema.
Returns tuple of (enforce, default, and required), where
enforce is a custom function, default is the default value for this attribute, and
required is a boolean.
"""
if isinstance(schema, dict):
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def _get_reasonable_file_label(uri: str) -> Optional[str]:
"""
Get a label for the dataset from a URI.... if we can.
>>> uri = '/tmp/some/ls7_wofs_1234.nc'
>>> _get_reasonable_file_label(uri)
'ls7_wofs_1234.nc'
>>> uri = 'file:///g/data/rs0/datacube/002/LS7_ETM_NBA... | bigcode/self-oss-instruct-sc2-concepts |
def merge(nums1, nums2):
"""
Merge two given sorted arrays by merge sort
:param nums1: first array
:type nums1: list[int]
:param nums2: second array
:type nums2: list[int]
:return: merged array
:rtype: list[int]
"""
result = []
i = j = 0
while i < len(nums1) and j < len(... | bigcode/self-oss-instruct-sc2-concepts |
def is_audit_type(*args):
"""This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict]
"""
def _is_audit_type(audit_options):
if audit_options.get('audit_type') in args:
... | bigcode/self-oss-instruct-sc2-concepts |
def count_blocks(documents):
"""
Counts the total number of blocks in a list of documents
Args:
documents(metadata.MetaDocument): The list of documents
Returns:
int: Size of the list
"""
return sum([len(doc.blocks) for doc in documents]) | bigcode/self-oss-instruct-sc2-concepts |
def get_day_offset(day, number):
"""
Returns an integer representing the day number shifted
by the given amount
"""
day -= number
if day < 0:
day += 7
return day | bigcode/self-oss-instruct-sc2-concepts |
def is_logged_in(soup):
""" checks from code snippet whether user is logged in
phpbb signatures
Not Logged in
<a href="./ucp.php?mode=login" title="Anmelden" accesskey="x" role="menuitem">
<i class="icon fa-power-off fa-fw" aria-hidden="true"></i><span>_log on message_</span>
... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_uuid(length):
"""Generates hex uuid with customized length.
Example: d9f3a7e8
Args:
length (int): number of digits of uuid
"""
return str(uuid.uuid4().hex)[:length] | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize_whitespace(string):
"""Normalize whitespace in string
Deletes consecutive spaces and newlines
"""
return re.sub("\n+", "\n", re.sub(" +", " ", string)) | bigcode/self-oss-instruct-sc2-concepts |
def get_api_key(filepath):
"""Read a local file with your API key."""
api = []
with open(filepath) as f:
for line in f:
api.append(line.strip())
assert len(api) == 1, "API key should be only one line long."
return api[0] | bigcode/self-oss-instruct-sc2-concepts |
def count_non_ascii_chars(file_path: str) -> int:
"""Counts non ascii characters and returns their amount.
Args:
file_path: the pathname (absolute or relative to the current working directory)
of the file to be opened.
Returns:
amount of non ascii characters.
"""
amount = ... | 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.