content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def moving_sum(x, start_idx: int, end_idx: int):
"""
From MONOTONIC CHUNKWISE ATTENTION
https://arxiv.org/pdf/1712.05382.pdf
Equation (18)
x = [x_1, x_2, ..., x_N]
MovingSum(x, start_idx, end_idx)_n = Sigma_{m=n−(start_idx−1)}^{n+end_idx-1} x_m
for n in {1, 2, 3, ..., N}
... | fa3cb672e23fccad75965da2ca10955134167c7e | 3,742 |
def make_sequence_output(detections, classes):
"""
Create the output object for an entire sequence
:param detections: A list of lists of detections. Must contain an entry for each image in the sequence
:param classes: The list of classes in the order they appear in the label probabilities
:return:
... | 019d3b74699af20a9f3cbc43b575e8bae5e15946 | 3,743 |
def encode(value):
"""
Encode strings in UTF-8.
:param value: value to be encoded in UTF-8
:return: encoded value
"""
return str(u''.join(value).encode('utf-8')) | 697f99f028d4b978b591d006273b9d5f688711f3 | 3,747 |
def get_season(months, str_='{}'):
"""
Creates a season string.
Parameters:
- months (list of int)
- str_ (str, optional): Formatter string, should contain exactly one {}
at the position where the season substring is included.
Returns:
str
"""
if months is None:
retur... | 73b4e8169f08ef286a0b57779d22c3436538fc30 | 3,748 |
def total_value(metric):
"""Given a time series of values, sum the values"""
total = 0
for i in metric:
total += i
return total | 4454bfaeb0797bc03b14819bde48dc8f5accc4d3 | 3,752 |
def pt_to_tup(pt):
"""
Convenience method to generate a pair of two ints from a tuple or list.
Parameters
----------
pt : list OR tuple
Can be a list or a tuple of >=2 elements as floats or ints.
Returns
-------
pt : tuple of int
A pair of two ints.
"""
return (... | 7013b2477959f528b98d364e4cc44ac8700fb366 | 3,760 |
def flatten(lst):
"""Shallow flatten *lst*"""
return [a for b in lst for a in b] | 203e971e43aea4d94bfa0ffa7057b416ef0bf545 | 3,763 |
def sep_num(number, space=True):
"""
Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for
the separator otherwise it will use commas
Note
----
Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separ... | ee7dfbb60fb01bb7b6bb84cbe56ec50dfab4b339 | 3,764 |
def LowercaseMutator(current, value):
"""Lower the value."""
return current.lower() | 7fed0dc4533948c54b64f649e2c85dca27ee9bc5 | 3,767 |
import pathlib
def testdata(request):
"""
If expected data is required for a test this fixture returns the path
to a folder with name '.testdata' located in the same director as the
calling test module
"""
testdata_dir = '.testdata'
module_dir = pathlib.Path(request.fspath).parent
retu... | 5d9a440b178aca00635f567420aaa9c406a1d7d2 | 3,770 |
def drop_useless_columns(data):
"""Drop the columns containing duplicate or useless columns."""
data = data.drop(
labels=[
# we stay in a given city
"agency_id",
"agency_name",
"agency_short_name",
# we stay on a given transportation network
... | 7a47625a5df7e9fa66cefe2f326af3f0b9f59b79 | 3,773 |
import re
def normalize(string: str) -> str:
"""
Normalize a text string.
:param string: input string
:return: normalized string
"""
string = string.replace("\xef\xbb\xbf", "") # remove UTF-8 BOM
string = string.replace("\ufeff", "") # remov... | 2adaeffb60af598dad40bd6f5cd7e61e6b238123 | 3,775 |
def extract_data(mask, dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None):
"""Get a clean sample based on mask
Parameters
----------
mask : array of boolean
mask for extract data
dra/ddc : array of float
R.A.(*cos(Dec.))/Dec. differences
dra_err/ddc_err : array of float... | 70286c6134fb19833f6033c827bb2ab2cd26afb1 | 3,776 |
def update_instance(instance, validated_data):
"""Update all the instance's fields specified in the validated_data"""
for key, value in validated_data.items():
setattr(instance, key, value)
return instance.save() | 2f4d5c4ec9e524cbe348a5efad9ecae27739b339 | 3,779 |
import pipes
def _ShellQuote(command_part):
"""Escape a part of a command to enable copy/pasting it into a shell.
"""
return pipes.quote(command_part) | 31ccd5bd64de657cd3ac5c36c643e9f2f09f2318 | 3,780 |
import math
def circlePoints(x, r, cx, cy):
"""Ther dunction returns the y coordinate of a
circonference's point
:x: x's coordinate value.
:r: length of the radius.
:cx: x coordinate of the center.
:cy: y coordinate of the center."""
return math.sqrt(math.pow(r,2) - math.pow(x-c... | c2cc14a845dccbcf62a38be3af69808024289adc | 3,781 |
import torch
def get_gram_matrix(tensor):
"""
Returns a Gram matrix of dimension (distinct_filer_count, distinct_filter_count) where G[i,j] is the
inner product between the vectorised feature map i and j in layer l
"""
G = torch.mm(tensor, tensor.t())
return G | ad86f06768c07d6fe1ff509d996991f786ea1ffa | 3,782 |
def get_all_contained_items(item, stoptest=None):
"""
Recursively retrieve all items contained in another item
:param text_game_maker.game_objects.items.Item item: item to retrieve items\
from
:param stoptest: callback to call on each sub-item to test whether\
recursion should continue.... | d04e5c297dddb70db83637e748281f04b08b6a25 | 3,785 |
def conv_seq_to_sent_symbols(seq, excl_symbols=None, end_symbol='.',
remove_end_symbol=True):
"""
Converts sequences of tokens/ids into a list of sentences (tokens/ids).
:param seq: list of tokens/ids.
:param excl_symbols: tokens/ids which should be excluded from the final
... | a87da4bb5c34882d882832380f3831929ad41415 | 3,786 |
def param_value(memory, position, mode):
"""Get the value of a param according to its mode"""
if mode == 0: # position mode
return memory[memory[position]]
elif mode == 1: # immediate mode
return memory[position]
else:
raise ValueError("Unknown mode : ", mode) | e02ed7e1baea57af4b08c408b6decadee9c72162 | 3,787 |
import math
def longitude_to_utm_epsg(longitude):
"""
Return Proj4 EPSG for a given longitude in degrees
"""
zone = int(math.floor((longitude + 180) / 6) + 1)
epsg = '+init=EPSG:326%02d' % (zone)
return epsg | f17a03514cc9caf99e1307c0382d7b9fa0289330 | 3,791 |
def compute_node_depths(tree):
"""Returns a dictionary of node depths for each node with a label."""
res = {}
for leaf in tree.leaf_node_iter():
cnt = 0
for anc in leaf.ancestor_iter():
if anc.label:
cnt += 1
res[leaf.taxon.label] = cnt
return res | a633f77d0fff1f29fe95108f96ccc59817179ddd | 3,792 |
import hashlib
def calc_sign(string):
"""str/any->str
return MD5.
From: Biligrab, https://github.com/cnbeining/Biligrab
MIT License"""
return str(hashlib.md5(str(string).encode('utf-8')).hexdigest()) | 3052e18991b084b3a220b0f3096d9c065cf4661c | 3,794 |
def remove_prefix(utt, prefix):
"""
Check that utt begins with prefix+" ", and then remove.
Inputs:
utt: string
prefix: string
Returns:
new utt: utt with the prefix+" " removed.
"""
try:
assert utt[: len(prefix) + 1] == prefix + " "
except AssertionError as e:
... | fa6717e34c6d72944636f6b319b98574f2b41a69 | 3,795 |
def format_ucx(name, idx):
"""
Formats a name and index as a collider
"""
# one digit of zero padding
idxstr = str(idx).zfill(2)
return "UCX_%s_%s" % (name, idxstr) | c3365bf66bca5fe7ab22bd642ae59dfb618be251 | 3,796 |
def eval_add(lst):
"""Evaluate an addition expression. For addition rules, the parser will return
[number, [[op, number], [op, number], ...]]
To evaluate that, we start with the first element of the list as result value,
and then we iterate over the pairs that make up the rest of the list, adding
or subtracti... | 5d6972ccc7a0857da224e30d579b159e89fb8dce | 3,799 |
def validate_target_types(target_type):
"""
Target types validation rule.
Property: SecretTargetAttachment.TargetType
"""
VALID_TARGET_TYPES = (
"AWS::RDS::DBInstance",
"AWS::RDS::DBCluster",
"AWS::Redshift::Cluster",
"AWS::DocDB::DBInstance",
"AWS::DocDB::DB... | db33903e36849fb8f97efecb95f1bbfa8150ed6f | 3,800 |
def cprint(*objects, **kwargs):
"""Apply Color formatting to output in terminal.
Same as builtin print function with added 'color' keyword argument.
eg: cprint("data to print", color="red", sep="|")
available colors:
black
red
green
yellow
blue
pink
cyan
white
no-colo... | 42d0f2357da7f84404a888cf717a737d86609aa4 | 3,801 |
def HHMMSS_to_seconds(string):
"""Converts a colon-separated time string (HH:MM:SS) to seconds since
midnight"""
(hhs,mms,sss) = string.split(':')
return (int(hhs)*60 + int(mms))*60 + int(sss) | f7a49ad5d14eb1e26acba34946830710384780f7 | 3,812 |
def _replace_token_range(tokens, start, end, replacement):
"""For a range indicated from start to end, replace with replacement."""
tokens = tokens[:start] + replacement + tokens[end:]
return tokens | 2848a3ad2d448e062facf78264fb1d15a1c3985c | 3,813 |
def center_crop(im, size, is_color=True):
"""
Crop the center of image with size.
Example usage:
.. code-block:: python
im = center_crop(im, 224)
:param im: the input image with HWC layout.
:type im: ndarray
:param size: the cropping size.
:type size: int
:param is... | ac280efd4773613f08632fe836eecc16be23adf8 | 3,815 |
def num(value):
"""Parse number as float or int."""
value_float = float(value)
try:
value_int = int(value)
except ValueError:
return value_float
return value_int if value_int == value_float else value_float | a2ea65c2afa0005dbe4450cb383731b029cb68df | 3,816 |
def __format_event_start_date_and_time(t):
"""Formats datetime into e.g. Tue Jul 30 at 5PM"""
strftime_format = "%a %b %-d at %-I:%M %p"
return t.strftime(strftime_format) | 4db0b37351308dfe1e7771be9a9ad8b98f2defa6 | 3,817 |
from typing import List
from typing import MutableMapping
def parse_template_mapping(
template_mapping: List[str]
) -> MutableMapping[str, str]:
"""Parses a string template map from <key>=<value> strings."""
result = {}
for mapping in template_mapping:
key, value = mapping.split("=", 1)
result[key] ... | 49eb029a842be7c31d33444235452ecad4701476 | 3,818 |
def shorten_str(string, length=30, end=10):
"""Shorten a string to the given length."""
if string is None:
return ""
if len(string) <= length:
return string
else:
return "{}...{}".format(string[:length - end], string[- end:]) | d52daec3058ddced26805f259be3fc6139b5ef1f | 3,824 |
def parse_healing_and_target(line):
"""Helper method that finds the amount of healing and who it was provided to"""
split_line = line.split()
target = ' '.join(split_line[3:split_line.index('for')])
target = target.replace('the ', '')
amount = int(split_line[split_line.index('for')+1])
return... | 3f11c0807ab87d689e47a79fc7e12b32c00dbd95 | 3,828 |
import torch
def as_mask(indexes, length):
"""
Convert indexes into a binary mask.
Parameters:
indexes (LongTensor): positive indexes
length (int): maximal possible value of indexes
"""
mask = torch.zeros(length, dtype=torch.bool, device=indexes.device)
mask[indexes] = 1
r... | 0235d66f9ee5bdc7447819122b285d29efd238c9 | 3,830 |
def check_pass(value):
"""
This test always passes (it is used for 'checking' things like the
workshop address, for which no sensible validation is feasible).
"""
return True | aa3a5f536b5bc729dc37b7f09c3b997c664b7481 | 3,831 |
def get_trader_fcas_availability_agc_status_condition(params) -> bool:
"""Get FCAS availability AGC status condition. AGC must be enabled for regulation FCAS."""
# Check AGC status if presented with a regulating FCAS offer
if params['trade_type'] in ['L5RE', 'R5RE']:
# AGC is active='1', AGC is ina... | fa73ae12a0934c76f12c223a05161280a6dc01f1 | 3,833 |
def normalize_field_names(fields):
"""
Map field names to a normalized form to check for collisions like 'coveredText' vs 'covered_text'
"""
return set(s.replace('_','').lower() for s in fields) | 55bdac50fd1fcf23cfec454408fbcbbae96e507e | 3,836 |
def remove_comments(s):
"""
Examples
--------
>>> code = '''
... # comment 1
... # comment 2
... echo foo
... '''
>>> remove_comments(code)
'echo foo'
"""
return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#")) | 1d3e1468c06263d01dd204c5ac89235a17f50972 | 3,840 |
import pathlib
def is_dicom(path: pathlib.Path) -> bool:
"""Check if the input is a DICOM file.
Args:
path (pathlib.Path): Path to the file to check.
Returns:
bool: True if the file is a DICOM file.
"""
path = pathlib.Path(path)
is_dcm = path.suffix.lower() == ".dcm"
is_... | 1e20ace9c645a41817bf23a667bd4e1ac815f63f | 3,842 |
def axLabel(value, unit):
"""
Return axis label for given strings.
:param value: Value for axis label
:type value: int
:param unit: Unit for axis label
:type unit: str
:return: Axis label as \"<value> (<unit>)\"
:rtype: str
"""
return str(value) + " (" + str(unit) + ")" | cc553cf4334222a06ae4a2bcec5ec5acb9668a8f | 3,844 |
def extract_tag(inventory, url):
"""
extract data from sphinx inventory.
The extracted datas come from a C++ project
documented using Breathe. The structure of the inventory
is a dictionary with the following keys
- cpp:class (class names)
- cpp:function (functions or class methods)... | dcda1869fb6a44bea3b17f1d427fe279ebdc3a11 | 3,847 |
from collections import Counter
from typing import Iterable
def sock_merchant(arr: Iterable[int]) -> int:
"""
>>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20])
3
>>> sock_merchant([6, 5, 2, 3, 5, 2, 2, 1, 1, 5, 1, 3, 3, 3, 5])
6
"""
count = Counter(arr).values()
ret = sum(n // 2 ... | 1b3b8d37ccb3494ed774e26a41ebba32c87a632c | 3,857 |
def int_from_bin_list(lst):
"""Convert a list of 0s and 1s into an integer
Args:
lst (list or numpy.array): list of 0s and 1s
Returns:
int: resulting integer
"""
return int("".join(str(x) for x in lst), 2) | a41b2578780019ed1266442d76462fb89ba2a0fb | 3,858 |
def sort_ipv4_addresses_with_mask(ip_address_iterable):
"""
Sort IPv4 addresses in CIDR notation
| :param iter ip_address_iterable: An iterable container of IPv4 CIDR notated addresses
| :return list : A sorted list of IPv4 CIDR notated addresses
"""
return sorted(
ip_address_iterable,
... | 97517b2518b81cb8ce4cfca19c5512dae6bae686 | 3,864 |
def script_with_queue_path(tmpdir):
"""
Pytest fixture to return a path to a script with main() which takes
a queue and procedure as arguments and adds procedure process ID to queue.
"""
path = tmpdir.join("script_with_queue.py")
path.write(
"""
def main(queue, procedure):
queue.put... | 7c2c2b4c308f91d951496c53c9bdda214f64c776 | 3,866 |
import re
def parseCsv(file_content):
"""
parseCsv
========
parser a string file from Shimadzu analysis, returning a
dictonary with current, livetime and sample ID
Parameters
----------
file_content : str
shimadzu output csv content
Returns
-------
dic
... | cc20a906c23093994ce53358d92453cd4a9ab459 | 3,869 |
import re
def matchatleastone(text, regexes):
"""Returns a list of strings that match at least one of the regexes."""
finalregex = "|".join(regexes)
result = re.findall(finalregex, text)
return result | 1e0775413189931fc48a3dc82c23f0ffe28b333e | 3,874 |
def get_keys(mapping, *keys):
"""Return the values corresponding to the given keys, in order."""
return (mapping[k] for k in keys) | e3b8bdbdff47c428e4618bd4ca03c7179b9f4a2b | 3,876 |
def total_examples(X):
"""Counts the total number of examples of a sharded and sliced data object X."""
count = 0
for i in range(len(X)):
for j in range(len(X[i])):
count += len(X[i][j])
return count | faf42a940e4413405d97610858e13496eb848eae | 3,877 |
def make_linear_colorscale(colors):
"""
Makes a list of colors into a colorscale-acceptable form
For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
"""
scale = 1.0 / (len(colors) - 1)
return [[i * scale, color] for i, color in enum... | dabd2a2a9d6bbf3acfcabcac52246048332fae73 | 3,884 |
def odd_occurrence_parity_set(arr):
"""
A similar implementation to the XOR idea above, but more naive.
As we iterate over the passed list, a working set keeps track of
the numbers that have occurred an odd number of times.
At the end, the set will only contain one number.
Though the worst... | 57f9362e05786724a1061bef07e49635b1b2b142 | 3,886 |
import copy
def _merge_meta(base, child):
"""Merge the base and the child meta attributes.
List entries, such as ``indexes`` are concatenated.
``abstract`` value is set to ``True`` only if defined as such
in the child class.
Args:
base (dict):
``meta`` attribute from the base... | ba219b8091244a60658bee826fbef5003d3f7883 | 3,887 |
def trunc(x, y, w, h):
"""Truncates x and y coordinates to live in the (0, 0) to (w, h)
Args:
x: the x-coordinate of a point
y: the y-coordinate of a point
w: the width of the truncation box
h: the height of the truncation box.
"""
return min(max(x, 0), w - 1), min... | 3edecdfbd9baf24f8b4f3f71b9e35a222c6be1ea | 3,889 |
def param_to_secopt(param):
"""Convert a parameter name to INI section and option.
Split on the first dot. If not dot exists, return name
as option, and None for section."""
sep = '.'
sep_loc = param.find(sep)
if sep_loc == -1:
# no dot in name, skip it
section = None
opt... | 7d7e2b03cb67ed26d184f85f0328236674fa6497 | 3,894 |
def rotate_char(c, n):
"""Rotate a single character n places in the alphabet
n is an integer
"""
# alpha_number and new_alpha_number will represent the
# place in the alphabet (as distinct from the ASCII code)
# So alpha_number('a')==0
# alpha_base is the ASCII code for the first letter of ... | b1259722c7fb2a60bd943e86d87163866432539f | 3,896 |
import itertools
def _get_indices(A):
"""Gets the index for each element in the array."""
dim_ranges = [range(size) for size in A.shape]
if len(dim_ranges) == 1:
return dim_ranges[0]
return itertools.product(*dim_ranges) | dc2e77c010a6cfd7dbc7b7169f4bd0d8da62b891 | 3,899 |
def slices(series, length):
"""
Given a string of digits, output all the contiguous substrings
of length n in that string in the order that they appear.
:param series string - string of digits.
:param length int - the length of the series to find.
:return list - List of substrings of specif... | ea2d1caf26a3fc2e2a57858a7364b4ebe67297d6 | 3,902 |
from typing import Tuple
def get_subpixel_indices(col_num: int) -> Tuple[int, int, int]:
"""Return a 3-tuple of 1-indexed column indices representing subpixels of a single pixel."""
offset = (col_num - 1) * 2
red_index = col_num + offset
green_index = col_num + offset + 1
blue_index = col_num + of... | cb4a1b9a4d27c3a1dad0760267e6732fe2d0a0da | 3,905 |
def compute_t(i, automata_list, target_events):
"""
Compute alphabet needed for processing L{automata_list}[i-1] in the
sequential abstraction procedure.
@param i: Number of the automaton in the L{automata_list}
@type i: C{int} in range(1, len(automata_list)+1)
@param automata_list: List of a... | 88fc64aaf917d23a29e9400cf29705e6b20665c3 | 3,914 |
def strip_new_line(str_json):
"""
Strip \n new line
:param str_json: string
:return: string
"""
str_json = str_json.replace('\n', '') # kill new line breaks caused by triple quoted raw strings
return str_json | f2faaa80dca000586a32a37cdf3dff793c0a2d9b | 3,915 |
def getObjectInfo(fluiddb, about):
"""
Gets object info for an object with the given about tag.
"""
return fluiddb.about[about].get() | 8614edaf44944fcc11882ac2fcaa31ba31d48d30 | 3,924 |
def is_iterable(obj):
"""
Return true if object has iterator but is not a string
:param object obj: Any object
:return: True if object is iterable but not a string.
:rtype: bool
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) | c7a1353f7f62a567a65d0c4752976fefde6e1904 | 3,932 |
def f_all(predicate, iterable):
"""Return whether predicate(i) is True for all i in iterable
>>> is_odd = lambda num: (num % 2 == 1)
>>> f_all(is_odd, [])
True
>>> f_all(is_odd, [1, 3, 5, 7, 9])
True
>>> f_all(is_odd, [2, 1, 3, 5, 7, 9])
False
"""
return all(predicate(i) for i i... | c0a0e52587a7afc9da143ac936aab87ad531b455 | 3,938 |
from typing import List
from typing import Tuple
from typing import Set
from typing import Dict
def _recursive_replace(data):
"""Searches data structure and replaces 'nan' and 'inf' with respective float values"""
if isinstance(data, str):
if data == "nan":
return float("nan")
if d... | b5c21d806b462070b2d1eec7d91a5dc700f6b0ed | 3,939 |
def audio_sort_key(ex):
"""Sort using duration time of the sound spectrogram."""
return ex.src.size(1) | ec940df6bf2b74962f221b84717f51beba5c4f5f | 3,942 |
def is_versioned(obj):
"""
Check if a given object is versioned by inspecting some of its attributes.
"""
# before any heuristic, newer versions of RGW will tell if an obj is
# versioned so try that first
if hasattr(obj, 'versioned'):
return obj.versioned
if not hasattr(obj, 'Versio... | 7f5ad90ffce6a8efde50dba47cdc63673ec79f60 | 3,944 |
import ast
def maybe_get_docstring(node: ast.AST):
"""Get docstring from a constant expression, or return None."""
if (
isinstance(node, ast.Expr)
and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str)
):
return node.value.value
elif (
is... | 23171c739f3c9ae6d62ecf3307ac7c3409852d6b | 3,947 |
def _find(xs, predicate):
"""Locate an item in a list based on a predicate function.
Args:
xs (list) : List of data
predicate (function) : Function taking a data item and returning bool
Returns:
(object|None) : The first list item that predicate returns True for or None
"""
... | 94d8dd47e54e1887f67c5f5354d05dc0c294ae52 | 3,949 |
def _extract_action_num_and_node_id(m):
"""Helper method: Extract *action_num* and *node_id* from the given regex
match. Convert *action_num* to a 0-indexed integer."""
return dict(
action_num=(int(m.group('action_num')) - 1),
node_id=m.group('node_id'),
) | f1e5f0b81d6d82856b7c00d67270048e0e4caf38 | 3,953 |
def sse_pack(d):
"""For sending sse to client. Formats a dictionary into correct form for SSE"""
buf = ''
for k in ['retry','id','event','data']:
if k in d.keys():
buf += '{}: {}\n'.format(k, d[k])
return buf + '\n' | a497c7ab919115d59d49f25abfdb9d88b0963af3 | 3,961 |
def filter_dictionary(dictionary, filter_func):
"""
returns the first element of `dictionary` where the element's key pass the filter_func.
filter_func can be either a callable or a value.
- if callable filtering is checked with `test(element_value)`
- if value filtering is checked ... | f5fa77a51241323845eb9a59adc9df7f662f287b | 3,964 |
from typing import List
def two_loops(N: List[int]) -> List[int]:
"""Semi-dynamic programming approach using O(2n):
- Calculate the product of all items before item i
- Calculate the product of all items after item i
- For each item i, multiply the products for before and after i
L[i] = N[i-1] *... | 3620aa19833b2e967b2c295fa53ba39bf3b6b70d | 3,968 |
def rgb_to_hex(r, g, b):
"""Turn an RGB float tuple into a hex code.
Args:
r (float): R value
g (float): G value
b (float): B value
Returns:
str: A hex code (no #)
"""
r_int = round((r + 1.0) / 2 * 255)
g_int = round((g + 1.0) / 2 * 255)
b_int = round((b + 1... | a5181c475c798bbd03020d81da10d8fbf86cc396 | 3,969 |
def odd(x):
"""True if x is odd."""
return (x & 1) | 9cd383ea01e0fed56f6df42648306cf2415f89e9 | 3,971 |
import re
def remove_conjunction(conjunction: str, utterance: str) -> str:
"""Remove the specified conjunction from the utterance.
For example, remove the " and" left behind from extracting "1 hour" and "30 minutes"
from "for 1 hour and 30 minutes". Leaving it behind can confuse other intent
parsing... | 67313565c7da2eadc4411854d6ee6cb467ee7159 | 3,973 |
def othertitles(hit):
"""Split a hit.Hit_def that contains multiple titles up, splitting out the hit ids from the titles."""
id_titles = hit.Hit_def.text.split('>')
titles = []
for t in id_titles[1:]:
fullid, title = t.split(' ', 1)
hitid, id = fullid.split('|', 2)[1:3]
titles.a... | fa5bbb47d26adbc61817e78e950e81cc05eca4a6 | 3,974 |
from typing import List
def read_plaintext_inputs(path: str) -> List[str]:
"""Read input texts from a plain text file where each line corresponds to one input"""
with open(path, 'r', encoding='utf8') as fh:
inputs = fh.read().splitlines()
print(f"Done loading {len(inputs)} inputs from file '{path}... | 27b00f4dfcdf4d76e04f08b6e74c062f2f7374d0 | 3,975 |
def _file_path(ctx, val):
"""Return the path of the given file object.
Args:
ctx: The context.
val: The file object.
"""
return val.path | 7c930f2511a0950e29ffc327e85cf9b2b3077c02 | 3,977 |
def total_angular_momentum(particles):
"""
Returns the total angular momentum of the particles set.
>>> from amuse.datamodel import Particles
>>> particles = Particles(2)
>>> particles.x = [-1.0, 1.0] | units.m
>>> particles.y = [0.0, 0.0] | units.m
>>> particles.z = [0.0, 0.0] | units.m
... | 8eca23b7b1a8fc8a7722543f9193f0e4a3397f24 | 3,979 |
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]:
"""Returns set of at least 2 contiguous values that add to target sum."""
i = 0
set_ = []
sum_ = 0
while sum_ <= target_sum:
sum_ += values[i]
set_.append(values[i])
if sum_ == target_sum and len(set... | 64b6c1f99946856a33a79fed3d43395a5a9c1000 | 3,981 |
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple:
"""
Change character's coordinates.
:param character: a dictionary
:param direction_index: a non-negative integer, optional
:param available_directions: a list of strings, optional
:precondition: char... | cc5cc3115437d0dc4e9b7ba7845565ee8147be30 | 3,982 |
def scrap_insta_description(inst) -> str:
"""
Scrap description from instagram account HTML.
"""
description = inst.body.div.section.main.div.header.section.find_all(
'div')[4].span.get_text()
return description | 898fa0d1cb44606374b131b8b471178a22ab74ed | 3,983 |
def __get_from_imports(import_tuples):
""" Returns import names and fromlist
import_tuples are specified as
(name, fromlist, ispackage)
"""
from_imports = [(tup[0], tup[1]) for tup in import_tuples
if tup[1] is not None and len(tup[1]) > 0]
return from_imports | 28df8225ad9440386342c38657944cfe7ac3d3ca | 3,985 |
import random
import hmac
def hash_password(password, salthex=None, reps=1000):
"""Compute secure (hash, salthex, reps) triplet for password.
The password string is required. The returned salthex and reps
must be saved and reused to hash any comparison password in
order for it to match the ... | cac468818560ed52b415157dde71d5416c34478c | 3,988 |
def mixed_social_welfare(game, mix):
"""Returns the social welfare of a mixed strategy profile"""
return game.expected_payoffs(mix).dot(game.num_role_players) | 72c465211bdc79c9fcf2b1b9d8c7dd5abae5d8df | 3,993 |
def _rec_filter_to_info(line):
"""Move a DKFZBias filter to the INFO field, for a record.
"""
parts = line.rstrip().split("\t")
move_filters = {"bSeq": "strand", "bPcr": "damage"}
new_filters = []
bias_info = []
for f in parts[6].split(";"):
if f in move_filters:
bias_inf... | 496056126bdf390a6213dfad5c40c4a14ec35caa | 3,996 |
def get(isamAppliance, cert_dbase_id, check_mode=False, force=False):
"""
Get details of a certificate database
"""
return isamAppliance.invoke_get("Retrieving all current certificate database names",
"/isam/ssl_certificates/{0}/details".format(cert_dbase_id)) | 34ade7c42fcc1b1409b315f8748105ee99157986 | 4,000 |
import random
def t06_ManyGetPuts(C, pks, crypto, server):
"""Many clients upload many files and their contents are checked."""
clients = [C("c" + str(n)) for n in range(10)]
kvs = [{} for _ in range(10)]
for _ in range(200):
i = random.randint(0, 9)
uuid1 = "%08x" % random.randint(... | 384aa2b03169da613b25d2da60cdd1ec007aeed5 | 4,002 |
import xxhash
def hash_array(kmer):
"""Return a hash of a numpy array."""
return xxhash.xxh32_intdigest(kmer.tobytes()) | 9761316333fdd9f28e74c4f1975adfca1909f54a | 4,004 |
def idxs_of_duplicates(lst):
""" Returns the indices of duplicate values.
"""
idxs_of = dict({})
dup_idxs = []
for idx, value in enumerate(lst):
idxs_of.setdefault(value, []).append(idx)
for idxs in idxs_of.values():
if len(idxs) > 1:
dup_idxs.extend(idxs)
return ... | adc8a0b0223ac78f0c8a6edd3d60acfaf7ca4c04 | 4,007 |
def aslist(l):
"""Convenience function to wrap single items and lists, and return lists unchanged."""
if isinstance(l, list):
return l
else:
return [l] | 99ccef940229d806d27cb8e429da9c85c44fed07 | 4,008 |
def enough_data(train_data, test_data, verbose=False):
"""Check if train and test sets have any elements."""
if train_data.empty:
if verbose:
print('Empty training data\n')
return False
if test_data.empty:
if verbose:
print('Empty testing data\n')
retu... | f11014d83379a5df84a67ee3b8f1e85b23c058f7 | 4,011 |
def inc(x):
""" Add one to the current value """
return x + 1 | c8f9a68fee2e8c1a1d66502ae99e42d6034b6b5c | 4,015 |
from datetime import datetime
def parse_iso8601(dtstring: str) -> datetime:
"""naive parser for ISO8061 datetime strings,
Parameters
----------
dtstring
the datetime as string in one of two formats:
* ``2017-11-20T07:16:29+0000``
* ``2017-11-20T07:16:29Z``
"""
return... | 415a4f3a9006109e31ea344cf99e885a3fd2738d | 4,026 |
import re
def is_youtube_url(url: str) -> bool:
"""Checks if a string is a youtube url
Args:
url (str): youtube url
Returns:
bool: true of false
"""
match = re.match(r"^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$", url)
return bool(match) | 97536b8e7267fb5a72c68f242b3f5d6cbd1b9492 | 4,031 |
def item_len(item):
"""return length of the string format of item"""
return len(str(item)) | 7d68629a5c2ae664d267844fc90006a7f23df1ba | 4,033 |
def is_numeric(array):
"""Return False if any value in the array or list is not numeric
Note boolean values are taken as numeric"""
for i in array:
try:
float(i)
except ValueError:
return False
else:
return True | 2ab0bb3e6c35e859e54e435671b5525c6392f66c | 4,034 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.