content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def imagesrc(url, html):
"""Finds the rel="image_src" in the html for the preview"""
image_src = html.find_all(rel="image_src")
for image in image_src:
return image.get('href') | 34f8163ed81f31487f1bb245a6bb70553afca51b | 591,718 |
def scale(val: float, factor: int) -> int:
"""
Multiply val with factor and convert result to an integer with proper
rounding.
Arguments:
val: Float value to rounded
factor: Value with which val is multiplied.
Returns:
Rounded integer value of the product of val and factor.
"... | c643dc65b1525a62f42277424f20fd7beda0e768 | 591,721 |
import json
def jsonParse(strArg):
"""
A utility to handle a string argument by either parsing it
directly as JSON or, if that fails, loading a JSON file at that
filepath.
:param strArg: Either a JSON string or filepath to a JSON file
:type strArg: str
:returns: The parsed JSON object
... | a533cdbd94b8aab46bf75eec30685cd0aa1f6ff1 | 591,722 |
def _getSwiBaselinePeriods() -> list:
"""Returns swi baseline periods"""
# every 5th DOY
return [i for i in range(1,366,5)] | dd6d6895fc8cdffaf85e228ef3c6673d2f7504f6 | 591,724 |
def is_color(image):
""" Takes an image as parameter and decides whether the image is color or not """
return len(image.shape) != 2 | 3b782f4b36a3540001c023e6b06fa9a582e04fe5 | 591,727 |
def make_track_key(fields):
""" Makes a unique key for each track """
# For Efficient Lookups
return (
fields['title'],
fields['artist'],
fields['album'],
fields.get('trackNumber', 0)) | 55435077faee547660c693e9cfd339f4888851af | 591,728 |
def get_year_filter(year):
"""Creates a filter for a year"""
def year_filter(occurrence):
"""Filter for years
Using the year captured the closure, returns false if the occurrence
is before the year, true when is in the year and stops when is past
"""
if year == "*":
... | 39551d7ee0b5ecd89e562b01af3bb9354c4359c5 | 591,733 |
import pickle
def load_rollout(filename):
"""
Extract data related to rollout generated by expert policy.
:param filename - str, name of file.
:return data - A tuple of lists of observations and actions.
"""
with open(filename, 'rb') as f:
data = pickle.loads(f.read())
return ... | b161819b5e249fb43dd859f566ddc8f630141716 | 591,735 |
def sphere_func(x):
"""Sphere objective function.
Has a global minimum at :code:`0` and with a search domain of
:code:`[-inf, inf]`
Parameters
----------
x : numpy.ndarray
set of inputs of shape :code:`(n_particles, dimensions)`
Returns
-------
numpy.ndarray
co... | 3514e9372688a409551243524444ea7388ce7e78 | 591,746 |
from bs4 import BeautifulSoup
def local_urls(soup: BeautifulSoup):
"""
Get a list with all local URLs in a BeautifulSoup object.
:param soup: BeautifulSoup object.
:return: List with all local URLs.
"""
url_result_set = soup.findAll('a')
local = []
for result_set in url_result_set:
... | c56a7ca29eda0aae4e8d32047984bb6abd3cd4cf | 591,749 |
import re
def regexp_word_tokenize(s):
"""Simple word tokenizer using Regular Expression
"""
return re.compile(r"\b\w\w+\b", re.U).findall(s) | e4c61504e4004213166172b0692d24f5adc56692 | 591,754 |
def compute_hirsch_index(citation_counts):
"""Computes the h-index given a sequence containing the number of
citations for each document."""
i = 0
for count in sorted(citation_counts, reverse=True):
if i + 1 > count:
break
i += 1
return i | b3ccea1c6342cfc2f31412f9d14bc0293eb42ba4 | 591,757 |
def format_bytes(n: int) -> str:
"""Format bytes as text
>>> from dask.utils import format_bytes
>>> format_bytes(1)
'1 B'
>>> format_bytes(1234)
'1.21 kiB'
>>> format_bytes(12345678)
'11.77 MiB'
>>> format_bytes(1234567890)
'1.15 GiB'
>>> format_bytes(1234567890000)
'1.... | 3ccc3d3dfb6535456fa03180be56f563bf1aa7c4 | 591,760 |
def remove_widgets(dashboard_widgets, widget_data):
"""
Removes current widgets belonging to dashboard not in widget_data.
Returns remaining widgets.
"""
widget_ids = [wd['id'] for wd in widget_data]
dashboard_widgets.exclude(
id__in=widget_ids
).delete()
return dashboard_widgets... | 1b039d8a02457875592967fdd50c0687b9cc5aeb | 591,761 |
def lookup_property(lookup):
"""Factory function for simple lookup properties."""
def fget(self):
return type(self)("%s__%s" % (self._name, lookup))
return property(fget) | 277ed786a42165638a02d06ede8757de1dd7bf2d | 591,762 |
import torch
def ccwh_to_xyxy(t: torch.Tensor) -> torch.Tensor:
"""
converts bbox coordinates from `(x_center, y_center, width, height)` to `(xmin, ymin, xmax, ymax)`
"""
assert t.size(-1) == 4, "input tensor must be of size `(N, 4)` with format `(x_center, y_center, width, height)`"
cc = t[..., :... | 0e31ac7829ef8033de323a007b792ff9cb52932b | 591,764 |
def items_sum(items, field):
"""Take a list of items, and return the sum of a given field."""
if items:
sum = 0
for item in items:
value = getattr(item, field)
if type(value) in (int, float):
sum += value
return sum
else:
return None | 04553a7a0fa5a2e21781dfeb0b8365e4d79b05e3 | 591,765 |
def query_slice(query, skip, first):
"""Return a list of a slice of `query` starting at `skip` with len `first`."""
return query.slice(skip, skip+first).all() | b5ee443a1fafbe692a2b777a6f2a60ce314beaef | 591,770 |
def required_for_output(inputs, outputs, connections):
"""
Collect the nodes whose state is required to compute the final network output(s).
:param inputs: list of the input identifiers
:param outputs: list of the output node identifiers
:param connections: list of (input, output) connections in the... | 0f4fe75843077948508bdb766e0ebd31a7444129 | 591,771 |
def load_credentials(filepath: str) -> dict:
"""
Load a file containing key and secret credentials, separated by a line break (\n)
Returns a dict with the corresponding credentials
"""
with open(filepath, 'r') as file_resource:
data = file_resource.read().strip().split('\n')
return {
... | 69e3d19ea222d1595b5e88e272f7cbc2ca8691b2 | 591,772 |
from typing import List
def knapsack(amount: int, weights: List[int]) -> int:
"""
Return the closet sum to ``amount`` given ``weights``.
:time: O(m * n) where m is the amount of weights and n is the amount
:space: O(n) where n i the amount
"""
sums = [0] * (amount + 1)
for weight in weig... | 98ba257b9b957d126efe28e46d6fbd63c7b1d70d | 591,773 |
import operator
def polonesa_reversa(expressao: list) -> int:
"""
>>> polonesa_reversa(['2', '1', '+', '3', '*'])
9
>>> polonesa_reversa(['4', '13', '5', '/', '+'])
6
>>> polonesa_reversa(['3', '+'])
Traceback (most recent call last):
...
SyntaxError: Faltando operandos na expressã... | cf90813058171dab60b8927a608ff9dc1b38c1c4 | 591,774 |
import re
def make_escaped(string):
"""Make escaped pattern from string
:string: string to be escaped
:returns: pattern
"""
return re.escape(string.replace('\n', 'NSLPH')).replace('NSLPH', '\n') + r'\n\Z' | c28e90bd59f37ee8af5b25eba5604cec5f680181 | 591,777 |
import codecs
import json
def import_jsondata(selected_file):
"""
Returns dictionary loaded from specified json file
Argument:
selected_file: String such as "assessments/data.json"
"""
f = codecs.open(selected_file, mode='r', encoding='utf-8')
data = json.load(f)
f.close()
retu... | 3d96ed87258a52d5add38424ed74621457950950 | 591,779 |
def int2str(val, max_dec=1024):
"""Make string from int. Hexademical representaion will be used if input value greater that 'max_dec'."""
if val > max_dec:
return "0x%x" % val
else:
return "%d" % val | 47be0d51f5127f3f8a25e4f893b07bbda4ccfffe | 591,782 |
def compose_remove_description(document: dict) -> str:
"""
Compose a change description for removing an OTU.
:param document: the OTU document that is being removed
:return: a change description
"""
name = document["name"]
abbreviation = document.get("abbreviation")
description = f"Re... | a4d02bae15d2e117d49719e7b9c7e4850fb9f027 | 591,788 |
import math
def safediv(a, b):
"""Divide a by b, but return NaN or infinity on division by zero
The behavior is equivalent to Numpy with the 'ignore' setting.
"""
try:
return a / b
except ZeroDivisionError:
sign = a * b
if a and not math.isnan(a):
return math.c... | d17cd7f11d9109622da5e4c67c41c7da8acab1eb | 591,790 |
def count_fixxations(fixxations):
"""
A Function that counts the number of distinct fixxations
:param fixxations: a list with values which indicate if the move from the previos is a fixxations.
:return: a number of indicating the amount of different fixxations
"""
fixxations_count =... | 5a83152be454b05a1744276dc9a8654fbf2eb32c | 591,791 |
def square(x: int) -> int:
""" This function squares numbers. You can use it like that:
:code:`square(5)`.
Args:
`x` (int): number to square
Returns:
int: squared number
:Example:
>>> square(3)
9
>>> square(10)
100
"""
return x**2 | f32d838ef011c97bd17eee16a6d731ad044ede12 | 591,793 |
def unquote(txt):
"""Giving string without quotes if enclosed in those."""
if len(txt) >= 2 and (txt[0] in "\"'") and txt[-1] == txt[0]:
return txt[1:-1]
return txt | dd341bdcb1832a1782361a12922218bd3ab40ab9 | 591,799 |
def keys_and_vals_to_strs(dictionary):
"""Recursively convert a dictionary's keys and values to strings.
:param dictionary: dictionary whose keys/vals are to be converted to strs
"""
def to_str(k_or_v):
if isinstance(k_or_v, dict):
return keys_and_vals_to_strs(k_or_v)
elif i... | 8a41c4bf5888ef1c1b778b0c571df1707532b69e | 591,800 |
import mmap
import hashlib
def hash_file(filename):
"""
Return the hexadecimal MD5 hash of the given file
"""
# Memory mapping appears to be the easiest and most efficient way to hash
# large files in Python
with open(filename, "rb") as f:
mmapped_file = mmap.mmap(f.fileno(), 0, access... | 1b460d4de7562941e8e09c38521d4ec95c6f44f0 | 591,804 |
import re
def cond_add_quotes(s):
"""If there are spaces in the input string s, put quotes around the
string and return it... if there are not already quotes in the
string.
@type s: string
@param s: path name
@rtype: string
@return: string with quotes, if necessary
"""
if re.search(r'[... | a476e27fea96ef5c26600ccf2a73b43dbfafb21d | 591,805 |
def join_words(words, language="en"):
"""
Joins a list of words with a language specific separator. Because not all
languages use the standard English white-space between words.
:param words: List of words
:type words: List[str]
:param language: Language code
:type language: str
:retu... | a74653f7a4cbb2b8b02486c308891841b6f4faf3 | 591,809 |
def index_of(val, listOfVals):
"""
Useful method for lists
(returns -1 instead of ValueError when value not in list)
"""
try:
index = listOfVals.index(val)
except ValueError:
index = -1
return index | 74720cf76dc250c53b573175ef51588b4a2e4aae | 591,810 |
def SplitXmlHeaderFromData(xml_input):
"""Split the XML header from the rest of the document
Args:
xml_input: xml with or without xml header
Returns:
(xml_header, xml_data): if a header was found
(None, xml_input): if no header
"""
if xml_input[:5] == '<?xml':
end_of_xml_header = xml_input.fin... | 631b3a00cf0536ad527a0321252ba40fa9a79320 | 591,823 |
def format_number(number):
"""
Formats a number from float (with or without units) to a latex-like number.
"""
try:
units = f"\\; {number.units.latex_repr}"
except:
units = ""
try:
mantissa, exponent = ("%.3g" % number).split("e+")
exponent = f" \\times 10^{{{in... | a2ef9d56b527b588cd2dcb5b2be3b2becb953b54 | 591,825 |
import importlib
def get_module_attr(attr):
"""
Gets an attribute from a module referred to with dot notation.
Ex: get_class_module('email.message.Message') would return the class
Message from the module email.message.
Positional arguments:
attr -- the dot-separated module and attribute to re... | 0ee9a98f5c705d536af7f4288aa14f97c896a482 | 591,827 |
def docker_compose_file(mock_dir):
"""
Path to docker-compose configuration files used for testing
- fixture defined in pytest-docker
"""
fpath = mock_dir / 'docker-compose.yml'
assert fpath.exists()
return str(fpath) | e32eb5ede50b47c562d48dee5dfb6958f2a49817 | 591,830 |
def get_xp(lvl):
"""
Returns total XP according to gain level
"""
total_xp = int((lvl * 10) ** 1.1)
return total_xp * lvl | 5e20dd0183b3103c7f0ca7aef741426a18c71a4a | 591,831 |
def _ComputeCost(cost_func, specs, flag_set):
"""Compute the mock cost of the flag_set using the input cost function.
All the boolean flags in the specs will be enabled and all the numeric flag
with have the largest legal value.
Args:
cost_func: The cost function which is used to compute the mock cost of ... | dc33e16348eb371698caed96cb9b27cf572c2be4 | 591,834 |
def _split_gain(gradient_left, hessian_left, gradient_right, hessian_right,
sum_gradients, sum_hessians, l2_regularization):
"""Loss reduction
Compute the reduction in loss after taking a split compared to keeping
the node a leaf of the tree.
See Equation 7 of:
XGBoost: A Scalable ... | 81407be6665b0e7fb44bca5398e99a6d1c928835 | 591,836 |
def _fwd6(y, dt):
"""Compute the first derivative of a uniformly-spaced-in-time array with a
sixth-order forward difference scheme.
Parameters
----------
y : (7,...) ndarray
Data to differentiate. The derivative is taken along the first axis.
dt : float
Time step (the uniform s... | 25f7c0902966de16a1eb09cecc2fc2870982ad97 | 591,839 |
from collections import namedtuple
def load_config(filename):
"""
Reads a text file with variable assignments.
Arguments:
filename (str | pathlib.Path): path to the file to be read.
Returns:
(collections.namedtuple): a tuple containing the variables and values defined in the text file... | eb5c042f0bc80ab974a49c2646c6401c409c3e51 | 591,843 |
def is_minimum_version(version, min_version):
"""Return True if version is equal or greater to min_version"""
return list(map(int, version.split('.'))) >= list(map(int, min_version.split('.'))) | e8c99db1808c1e9881a5e3f38fd105a9f3225a05 | 591,844 |
def build_index_from_parts(*parts):
"""Build an index name from parts.
:param parts: String values that will be joined by dashes ("-").
"""
return '-'.join([part for part in parts if part]) | 04d3dfbcc53ccf163c962a302daa2e3e85cce8d8 | 591,845 |
def get_text_filename(book_id, chapter_num=-1):
""" Get the filename for a text document with the book identifier and chapter number. """
if chapter_num != -1:
filename = book_id + '-' + str(chapter_num) + '.txt'
else:
filename = book_id + ".txt"
return filename | 5cc05cd184f8f37263fc1afce4dd1a2f76e29cfb | 591,852 |
import gzip
def open_as_text(path, mode):
"""Open a textfile or gzip file in text mode.
:param path: path to textfile or gzip
:type path: str
:param mode: mode to open the file, either `w` for write or `r` for read
:type mode: str
:return: file object
:rtype: file object
"""
retu... | 165d7c04405f6580068113008cd763a85dec67a1 | 591,853 |
def trim_to_usable_fstart_fstop(bins, usable_bins, fstart, fstop):
"""
Returns (trimmed bins, trimmed usable_bins,
adjusted fstart, adjusted fstop)
"""
left_bin = usable_bins[0][0]
right_bin = usable_bins[-1][0] + usable_bins[-1][1]
span = fstop - fstart
adj_fstart = float(span) * left_... | 1b3349132095086bbf33b0d6f00551588f952c67 | 591,856 |
def _intersection(la: list, lb: list):
"""
Calculates an intersection between two lists of relations.
"""
tmp = lb[:]
cnt_tp, cnt_fn = 0, 0
for a in la:
if a in tmp:
cnt_tp += 1
tmp.remove(a)
else:
cnt_fn += 1
return cnt_tp, cnt_fn | 6bdba2a6c449e812841d60060f2a3f84c35e4077 | 591,861 |
def is_comment(line: str) -> bool:
"""checks for '#' as first char in str:line, returns a bool"""
return line.strip().startswith('#') | ef2e4eb246d4d3d42a95e8a426b7794b25fe2ce1 | 591,862 |
def iterative_search(linkedlist, data):
"""Find the node containing 'data' using an iterative approach.
If there is no such node in the list, or if the list is empty,
raise a ValueError with error message "<data> is not in the list."
Inputs:
linkedlist (LinkedList): a linked list object
... | 3fccacd1450ffed886cdd478ed3c1b328842b143 | 591,866 |
def readu32(fd, loc=None):
"""
Read an unsigned 32-bit number
:param fd: file handle
:param loc: seek location
:return: a 4-byte number
"""
if loc is not None:
fd.seek(loc)
data = fd.read(4)
return data[0] + 256 *(data[1] + 256 *(data[2] + 256 * data[3])) | 989d6ee17a57cbcc50e732cdd5a68ce8d638c048 | 591,868 |
import inspect
def get_all_functions_in_module(module):
"""
Get all the functions in a module.
Will only get functions defined _in that module_! If they are imported
from elsewhere they will not be fetched!
Args:
module (python module): The module.
Returns:
functions ({str: ... | 7aeada260f2878e318375f980b486e6d1058b8a8 | 591,869 |
def columns_to_mapping(columns):
"""
Creates a dictionary whose keys are the column names:
stop_id,stop_code,stop_name,stop_desc,stop_lat,stop_lon,location_type,parent_station,zone_id
And the values are the indexes where their appropriate entry lies in each csv row.
:param columns:
:return:
... | 8bfb02874d778546453f7ce1aa1248a352c12e62 | 591,870 |
def number_to_value(number):
"""Given the numeric value of a card, returns its "value" name"""
values = [None, 'A', '2', '3', '4', '5', '6',
'7', '8', '9', '10', 'J', 'Q', 'K']
return values[number] | 66396374e97bb792321574f094fd897d911c60a6 | 591,880 |
def _canonicalize_output_name(name):
# type: (str) -> str
"""
Args:
name: Name for an op output as it would appear in the protocol buffer
representation of a an node graph
Returns:
A name in the form "<op name>:<output index>"
"""
if ":" in name:
return name
else:
return name + ":0" | c9067614ae0b496cada44c36fde53db3ae9e50db | 591,881 |
def is_square(X):
""" Check if matrices are square.
Parameters
----------
X : ndarray, shape (..., n, n)
The set of square matrices, at least 2D ndarray.
Returns
-------
ret : boolean
True if matrices are square.
"""
return X.ndim >= 2 and X.shape[-2] == X.shape[-1] | 559d4e801d6b59329c86d7d9e3aef4499de8b7e8 | 591,884 |
def _get_element(base, index):
"""Safe element getter from a list, tuple, or Array - returns None if the element doesn't exist"""
if index in base:
return base[index]
return None | dc31ed86425e682c9979b588aed0a85e3d3118cf | 591,891 |
def _has_file(mod):
"""
:param mod: Module object. Can be any of the multiple types used to
represent a module, we just check for a __file__ attribute.
:type mod: ``Any``
:return: If given module has a not None __file__ attribute.
:rtype: ``bool``
"""
return hasattr(mod, "__file__") ... | a817eb84b90ec125f8668ec1865d7449a3b64319 | 591,892 |
def hamming_distance(seq1, seq2, normalize=False):
"""Compute the Hamming distance between the two sequences `seq1` and `seq2`.
The Hamming distance is the number of differing items in two ordered
sequences of the same length. If the sequences submitted do not have the
same length, an error will be rais... | bb9936bc16e342e0a17acb2c3dd4eef0f5d9a34c | 591,893 |
def __get_page_component_filename_from_page_data(page_data):
"""Return a generated page component filename from json page data."""
return "{}_{}.js".format(page_data["style"], str(page_data["id"]).zfill(2)) | 3b2d4cfca40f689409f520cd9d1fa3c7e524872b | 591,896 |
def format_primer3_params(params):
"""Format parameter dictionary for primer3 input"""
# Must terminate input with empty assignment
return '\n'.join(['='.join(map(str, (k,v)))
for k, v in params.iteritems()] + ['=']) | 66f8d38f54fd3e4dc6f59fa16cbf4acb083899dd | 591,899 |
from io import StringIO
import csv
def encode_csv(dataset):
"""Takes a list of rows and returns it as a CSV string.
Parameters:
dataset (list[row]): A list of rows. Each row is a list of primitive
values.
Returns:
str: A CSV representation of the dataset.
>>> encode_csv(... | 284c3316c6987f5cc315e3b5b4806d5f274898ba | 591,900 |
def append_name(name, postfix):
""" append name with postfix """
if name is None:
ret = None
elif name == '':
ret = postfix
else:
ret = '%s_%s' % (name, postfix)
return ret | 60f63ac4ae60444b5456c31a8df9e55679118652 | 591,907 |
def prestats(threshold):
"""Wrapper for the ``tbss_4_prestats`` command.
The normal recommendation for <threshold> is 0.2
"""
return ["tbss_4_prestats", f'{threshold}'] | 356eba046f62daa3d7cf6e8960ff1210f4a5707a | 591,908 |
def _allow_all(root, path, pool):
"""Generic authz_read_func that permits access to all paths"""
return 1 | 5fe75af7fbc971153b23f5543ae2fb02df8ce296 | 591,915 |
def _calculate_humid_adjustment(temp: float, rh: float) -> float:
"""
Calculates and adjustment to the head index applicable when humidity is greater than
85% and temperature is between 80 and 87
"""
return ((rh - 85) / 10.0) * ((87 - temp) / 5.0) | b50aad9398c416c97c4ee3e7d438a7ec1d848777 | 591,916 |
from typing import List
from typing import Tuple
def group(lst: List, n: int) -> List[Tuple]:
"""
Splits a list into tuples of length n
https://stackoverflow.com/a/15480610/36061
eg
a = 'Moscow|city|London|city|Royston Vasey|vilage'
list(group(a.split('|'), 2))
gives
[('Moscow', 'city... | 61de96a908434e63423529a55194f7a7fa027d54 | 591,917 |
def suma(a, b):
"""Suma dos números
Args:
a (Numero): Numero a la izquierda del operador
b (Numero): Numero a la derecha del operador
Returns:
Numero: El resultado de la suma
"""
return a + b | 67a05bc1479b507cb713c39ea98a262a2e9e2c0d | 591,920 |
def attsiz(att: str) -> int:
"""
Helper function to return attribute size in bytes.
:param str: attribute type e.g. 'U002'
:return: size of attribute in bytes
:rtype: int
"""
return int(att[1:4]) | ab856fbaac4b59396c86b013ac9225e1150e8569 | 591,922 |
def find_with_pred(items, pred):
"""
Given a source iterable and a predicate defining how to identify an
element, find and return the element if it is present, or None if the
element is not found.
:param items: a keyless iterable (list or dictionary values or similar)
:param pred:
:return: ... | decb36994eff9edc5a22f4ca0d05b8e73c4e4ec7 | 591,924 |
def collide_1_1(spr1, spr2):
"""
Check if two sprite widgets have collided with each other.
"""
return spr1.collide_widget(spr2) | c48086cbffd6fb9709c6ae76a12ef5b505e23a8d | 591,925 |
def output_dir(tmpdir):
"""Fixture to prepare test output directory."""
return str(tmpdir.mkdir('output')) | 3385d339083897bd59914a5019cca452e81f4e9f | 591,926 |
def get_non_link_props(props):
"""Return subset of iterable props that are not links."""
return [val for val in props if '.' not in val] | f2790eb1301c426da0115e543d01a1a454221fdd | 591,932 |
def get_package_display_name(package):
"""Returns a human-readable name of package with optional version"""
if package.version:
return package.name + " - " + package.version
else:
return package.name | fedc55210e68b96d027d6fbc589351f79b823af3 | 591,939 |
from pathlib import Path
def test_path() -> Path:
"""Define test path.
Returns:
Parent directory of this file.
"""
return Path(__file__).resolve().parent | bfa87d3f33a97445ffeff8f31343a1d8ac0ba708 | 591,941 |
import io
import csv
def _load_csv_file(csv_file):
""" load csv file and check file content format
@param
csv_file: csv file path
e.g. csv file content:
username,password
test1,111111
test2,222222
test3,333333
@return
list of paramete... | 623af41507ea119440189647684f030af8bd5807 | 591,944 |
def _utc_datetime_to_iso(datetime_object):
"""
Takes a UTC datetime object and returns an ISO formatted string
:param datetime_object: datetime.datetime
:return: string with datetime in ISO format
"""
if datetime_object:
# Converts the datetime to ISO 8601
return datetime_object.... | 78813d28c141f846910367e2f1bd77e47f2291bf | 591,948 |
def missing_import(name, fail_msg=''):
"""
Generates a class which raises an import error when initialised.
e.g. SomeClass = missing_import('SomeClass') will make SomeClass() raise ImportError
"""
def init(self, *args, **kwargs):
raise ImportError(
f'The class {name} you tried to... | 301242d818bbc7df684d22f2bc0c1356b67e882b | 591,949 |
import click
def validate_new_relay_name(context, param, value):
"""
Validates uniqueness of new relay name.
"""
relays = context.obj.api.relays()
exists = any(r for r in relays
if r["name"] == value)
if exists:
error = "Relay \"%s\" already exists" % value
rai... | c4e892174036da476f47494c3ff9a8a29ce78d75 | 591,951 |
def check_required_args(required_args, args):
"""
Checks if all required_args have a value.
:param required_args: list of required args
:param args: kwargs
:return: True (if an exception isn't raised)
"""
for arg in required_args:
if arg not in args:
raise KeyError('Requi... | 87d510f0b45f861e6c558240c941bad03b6db33e | 591,954 |
def is_number(x):
""" Return true if x is an integer or float """
# Yes, I know that true pythonistas aren't supposed to do this, but ...
return isinstance(x, int) or isinstance(x, float) | 8211c2cae18478babde1bb8079f57c0590da471e | 591,955 |
def ellipsize(o):
"""
Ellipsize the representation of the given object.
"""
r = repr(o)
if len(r) < 800:
return r
r = r[:60] + ' ... ' + r[-15:]
return r | 2dc58a0aaa1c53dd97562d75a7d4b2660b32100b | 591,956 |
import string
import keyword
def translateName(s, dot=0):
"""Convert CL parameter or variable name to Python-acceptable name
Translate embedded dollar signs to 'DOLLAR'
Add 'PY' prefix to components that are Python reserved words
Add 'PY' prefix to components start with a number
If dot != 0, als... | da240b4e780cdce451e7d910a381f890e073c5c7 | 591,957 |
def get_dev_raw_data_source_stage_text_input(pipeline_builder):
"""Create Dev Raw Data Source stage with TEXT as input."""
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.set_attributes(data_format='TEXT',
raw_data='Hello Wor... | 57c29bdc7415a3df86b283dfc8e3c167ccf4a38d | 591,958 |
import torch
def reverse_padded_sequence(inputs, lengths, batch_first=False):
"""Reverses sequences according to their lengths.
Inputs should have size ``T x B x *`` if ``batch_first`` is False, or
``B x T x *`` if True. T is the length of the longest sequence (or larger),
B is the batch size, and * i... | bd097b86857f1e27dd5ef794bda48bc7b1a8400a | 591,960 |
def sublist(l):
"""
Breaks a long list into small sublists
"""
return [l[i:i+25] for i in range(0,len(l), 25)] | 2b3a66abcf4972941b4b0811a6233a7aec13489f | 591,965 |
from typing import Counter
def count_chars_in_file(input_filename: str, line_by_line: bool = True) -> Counter:
"""
Iterates line-by-line through specified file and counts the characters present in
each line. Returns resulting Counter. All letters (uppercase and lowercase) are
counted as lowercase lett... | ae2e43c52eae149e2c97680dc2c69a924f5138da | 591,969 |
def make_smiles_dict(filename):
"""Takes in a csv file with two columns. The first column
would be a compound identifier name while the second is a smiles
string for the molecule
This function returns a dictionary where the keys are compound
names and values are the smiles stings."""
smiles_ra... | 8498442ae3cb76ad86c437888a0507804bccbad7 | 591,971 |
def _remove_special(col_name):
"""Remove special characters from column name."""
return "".join(item for item in col_name if item.isalnum() or "_" in item) | e7ecdc0751e5ec13d314daa657608c44c89fda61 | 591,972 |
def get_attr_multi_level(obj, name: str):
"""
Returns the attribute 'name' from obj. Support attributes of attributes
separated by '.' So if you have a top level class MyClass which has a
subclass Sub1 and that one has a subclass Sub2 and that has an attribute
address you could access it with
ge... | 398f22c443ea4cb8ace00ab24b8aec2ca9ace314 | 591,975 |
def all_equal(array):
"""
Checks if all elements in the array are equal.
Parameters
----------
array : list, tuple
Raises
------
ValueError
If input array is empty
Returns
-------
bool
`True` in case if all elements are equal and
`False` otherwise.
... | 55965dbd16b2f6f0ac87ee2f05ea90747ee9b5be | 591,981 |
from datetime import datetime
def datetime_to_unix_ms(dt: datetime) -> int:
"""Convert a Python ``datetime`` object to a Unix millisecond timestamp.
This is necessary as the timestamps Cook returns in its API are in
milliseconds, while the Python ``datetime`` API uses seconds for Unix
timestamps.
... | 63b0ed18c800616bfeba2503a26b52d51f452411 | 591,984 |
def bootstrap_http_defaults(options):
"""Bootstraps http default options."""
options.setdefault("ENCODING", "UTF-8")
options.setdefault("MAX_CONTENT_LENGTH", 4 * 1024 * 1024)
options.setdefault("HTTP_COOKIE_DOMAIN", None)
options.setdefault("HTTP_COOKIE_SAMESITE", None)
options.setdefault("HTTP_... | 8f90664f54bb00c088cb82238da0ba024e9eb2f4 | 591,990 |
def run(
*, # Force kwargs.
head_branch="master",
event="push",
status="completed",
conclusion="success",
is_fork=False
) -> dict:
"""Generate Github run like dict."""
return {
"head_branch": head_branch,
"event": event,
"status": status,
"conclusion": co... | f253365451c4f5847ad2f344540fec0512c2125f | 591,993 |
def less_than_100(a:int, b: int) -> bool:
"""Determin if the sum of two numbers is less than 100."""
return sum((a,b,)) < 100 | 8f0eabc61abb29e645bbe761230389ba64105d19 | 591,994 |
def getPositions(mask):
"""
Get a list of positions where the specified
mask has the bit set
"""
# XXX I don't exactly love this implementation,
# but it works.
binaryString = bin(mask)[2:]
result = []
for index, c in enumerate(binaryString[::-1]):
if int(c):
resu... | f4976a7c900e82e62c7d067d337c6f5db7d269a9 | 591,997 |
def connected_children_names(obj, bone_name):
""" Returns a list of bone names (in order) of the bones that form a single
connected chain starting with the given bone as a parent.
If there is a connected branch, the list stops there.
"""
bone = obj.data.bones[bone_name]
names = []
w... | 373a8edbd976f5f4606071701d348f0b2a100551 | 592,002 |
def parts_11852cab(centre):
"""Return lists containing corners, sides, middle points for the task
11852cab"""
x, y = centre
corners = [(x-2, y-2), (x+2, y-2), (x-2, y+2), (x+2, y+2)]
sides = [(x, y-2), (x-2, y), (x+2, y), (x, y+2)]
middle = [(x-1, y-1), (x+1, y-1), (x-1, y+1), (x+1, y+1)]
re... | ec3b98a8a4efe171823e6ada1d0fe66f90425f8f | 592,004 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.