content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
import json
def setHassSensor(value, token, url):
"""Set the value of the Homeassistant Sensor"""
headers = {"Authorization": "Bearer {}".format(token), "Content-Type": "application/json"}
data = {"state": value}
response = requests.post(url, data=json.dumps(data), headers=headers)
... | 989c8c281be670eddf442aa505745ecc6ad48a21 | 593,026 |
from csv import reader
def open_dataset(file_name, header=True):
"""
Open a dataset contained in a csv file.
:param str file_name: The csv file that contains the dataset
:param bool header: If the dataset has a header (default=True)
:return: A list with dataset content
"""
# open the file
... | 1846aac5564ed047bd0082ea212f40949f3cf5cb | 593,030 |
def _cast_bool(value):
"""Return True if value is a non-zero int."""
try:
return int(value) != 0
except ValueError:
return False | 010ad2302b3a4272ef11c75ffdf9d73c5ab43fe2 | 593,032 |
def bold(text: str) -> str:
"""Formats text for discord message as bold"""
return f"**{text}**" | f5cf9645b9d637ff5b79c8a37abe01857cb3cec5 | 593,033 |
import ctypes
def get_memoryview_from_address(address, nbytes, format="B"):
"""Get a memoryview from an int memory address and a byte count,"""
# The default format is "<B", which seems to confuse some memoryview
# operations, so we always cast it.
c_array = (ctypes.c_uint8 * nbytes).from_address(addr... | b7ed665ed4033928a7d04ed9df2885fdc5daf57a | 593,035 |
import errno
def write_if_updated(path, s):
"""
Writes 's' as the contents of <out_dir>/<filename>, but only if it
differs from the current contents of the file. This avoids unnecessary
timestamp updates, which trigger documentation rebuilds.
Returns True if the file was updated, False otherwise.... | f4b39263d21b534b6b75f0ead7e8f45a76a5cbf4 | 593,039 |
import random
def _select_random_seed(min_seed_value: int = 1, max_seed_value: int = 2**32) -> int:
"""Selects random seed.
Parameters
----------
min_seed_value: int
Minimum seed value. Default: 1.
max_seed_value: int
Maximum seed value. Default: 2**32.
Returns
-------
... | fdc7fde449e5e66137ac3d1bd2677392729b3632 | 593,040 |
def get_values_per_node(params_per_age, graph):
"""
Returns a list of parameters according to each node, where list[i] is the value of a given parameter for node i
Sample input:
- params_per_age = {'0-9': 0.0000,
'10-19': 0.3627,
'20-29'... | 4a1d1265c19973308ff0693c0184261960be5944 | 593,043 |
def parallel_bubble_sort_single_step(array, key, odd=False,
system_side_length=None):
"""Give a layer of swaps as part of a sorting network for an array of
positions.
Args:
array: An array of multi-dimensional positions to sort.
key: The key function by ... | 893da68943f8e5fef0de4c3431497dbd9a0e83f6 | 593,044 |
def latex_float(number: float, precision=4) -> str:
"""
Turns a float into a latex formatted nice number.
:param number: the number to format.
:param precision: the precision you want in the number.
:return: the number formatted for latex.
"""
float_str = f"{number:.{precision}g}"
if "e"... | 2a2441d4bc16d754bd8aeae491601f2a590189f4 | 593,048 |
def _check_param_device(param, old_param_device):
"""This helper function is to check if the parameters are located
in the same device. Currently, the conversion between model parameters
and single vector form is not supported for multiple allocations,
e.g. parameters in different GPUs, or mixture of CP... | 52800fd950bcc9db044eb27a313bad797a6246e6 | 593,050 |
import pickle
def load_data(log_dir):
"""
Returns the average rewards along training, along with the number of arms.
Parameters
----------
log_dir : str
The directory where agentData.pk is stored.
Returns
-------
The data in the agentData.pk file.
"""
with open(f"{lo... | 02ea853fdf4fed7a3216f0567b440801f386201c | 593,052 |
def get_stack_output(stack, name: str) -> str:
"""Get a named output directly from a CF stack"""
for output in stack.outputs:
if output["OutputKey"] == name:
return output["OutputValue"]
raise ValueError(f"No stack output with name {name} found in stack {stack}!") | 223e50bd44b383dd1203b28a016f53d699a80711 | 593,054 |
def format_project_id(project_id):
"""
adds dashes to a bluebeam project id
"""
if len(project_id) == 9 and project_id.isdigit():
return "{}-{}-{}".format(
project_id[:3],
project_id[3:6],
project_id[6:]
)
return project_id | 0a4e5dedb3e49324d9b5fd56919cc20d5a4f55ee | 593,058 |
def length(tour, D):
"""Calculate the length of a tour according to distance matrix 'D'."""
#z = D[tour[-1], tour[0]] # edge from last to first city of the tour
z = 0
for i in range(1,len(tour)):
z += D[tour[i], tour[i-1]] # add length of edge from city i-1 to i
return z | 6c4b4d38bc5725a7be3c9ecd1af60da9c1ebac47 | 593,060 |
import re
def _interval_string_to_seconds(interval_string):
"""Convert internal string like 1M, 1Y3M, 3W to seconds.
:type interval_string: str
:param interval_string: Interval string like 1M, 1W, 1M3W4h2s...
(s => seconds, m => minutes, h => hours, D => days, W => weeks, M => months, Y => Years)... | 8cbb803cc323a234152b1e34c132e1e1a5e943ba | 593,070 |
import warnings
def resample_nanmean(data, dim='time', resample='M', nmin=15, **kwargs):
""" Resample Dataset and apply a minimum for resampling mean
Args:
data (DataArray, Dataset): Input fields
dim (str): datetime dimension
resample (str): upsampling frequency
nmin (int): mi... | c6ace88d87664af4d5b313c866a4b25334e489fc | 593,071 |
def clean_path_id(db_name: str, path_id: str) -> str:
"""
Take a DB name and pathway identifier string and returns a clean id
formatted as DB_name:path_id
:param db_name:
:param path_id:
:return:
"""
if db_name == "humancyc" or db_name == "reactome" or db_name == "pid":
return db... | fb8afdee743be63a01da25340e9add8b12c860e4 | 593,072 |
import string
import random
def generate_string( length=10, letters=string.ascii_letters ):
"""
Generate a random string
Arguments
---------
length: int (optional, default 10)
letters: string (optional, default is all ascii letters)
Returns
-------
string
random string
... | ddef5a729ab6e129b46c92f44815a91540942837 | 593,073 |
def get_modality(cfg):
"""
Helper function to intialize list of modalities
Args
----------
cfg: dict
Dictionary of config parameters
"""
modality = []
if cfg.data.rgb.enable:
modality.append("RGB")
if cfg.data.flow.enable:
modality.append("Flow")
if cfg... | a5531465199ad540fe67a5a20240ffaa8223f640 | 593,082 |
def find_tables(lines):
"""
For a list of lines, splits lines into blocks (stored in lists
of lines within two lists) representing tables or non tables. Also
return if a file starts with a table or a non-table (mostly
non-tables, but functionality is included for robustness).
"""
in_table = ... | 8d1e2b658e1b830081e23076e653c87aadbb5976 | 593,085 |
def is_stanza(sentences: str):
"""
Check if input is a stanza or not
param sentences: sentences to check
return: is stanza or not
"""
return len(sentences.split("\n\n")) == 1 | 281f862a3638fc81d470ded70dc23211b5bf16ef | 593,086 |
def get_openssl_url_version(version):
"""
Get the OpenSSL URL version part from the openssl version string.
"""
if version[:3] == "3.0":
return "3.0"
tokens = version.split(".")
if len(tokens) > 2:
return ".".join(tokens[:2] + [tokens[2][0],])
return version | 24ef49860a1e658a748b8a5c6dc39f0d38959bb0 | 593,087 |
def make_path(wname, wdate, sname, sdate):
"""Create the api path base string to append on livetiming.formula1.com for api
requests.
The api path base string changes for every session only.
Args:
wname: Weekend name (e.g. 'Italian Grand Prix')
wdate: Weekend date (e.g. '2019-09-08')
... | 0a408576550fa909ba5e2083f0c9110cc1de26c7 | 593,089 |
def append_key_value(content, key, value):
"""
Safely append the key/value as a separate line to the content
:param content:
:param key:
:param value:
:return: new content
"""
if key and value:
if content:
return '%s\n%s: %s' % (content, key, value)
return '%s... | 757e60b4692610f5dac170885fbb9476d929946a | 593,093 |
def _test_jpeg(h):
"""JPEG data with JFIF or Exif markers; and raw JPEG"""
if h[6:10] in (b'JFIF', b'Exif'):
return 'jpeg'
elif h[:4] == b'\xff\xd8\xff\xdb':
return 'jpeg' | 9f141edc23bf399c748d53a66d9d4257700616c5 | 593,094 |
def dummy_func(page, parent):
"""Dummy rule function, used for testing"""
return True | e3c34e6393c5847437669f3233cd52e1c2d3d3ff | 593,098 |
import math
def slope_angle(slope):
"""
Returns the angle(in degrees) of a line given its slope
"""
if slope is None:
return 90
return math.degrees(math.atan(slope)) | f2b8f14eed671c00371ed4be4f9e9c7fb3204fbb | 593,102 |
def reverse_complement(sequence):
"""
Reverse complement of a sequence represented as unicode string.
"""
complement = dict(zip([ord(b) for b in u'ACGTacgt'], u'TGCAtgca'))
return ''.join(reversed(sequence.translate(complement))) | d13fb366a26d3bc9bfa823cac1249ed095a28de7 | 593,103 |
def geometry_from_file(file_name):
"""Function to create molecular geometry from text file.
Args:
file_name: a string giving the location of the geometry file.
It is assumed that geometry is given for each atom on line, e.g.:
H 0. 0. 0.
H 0. 0. 0.7414
Returns:
... | c95ffc8d55a7e971eb1f9ab070dab6538d540c34 | 593,115 |
def hasNumber(passW):
"""
Checks if password has Numbers
"""
count=0
for i in ["0","1","2","3","4","5","6","7","8","9"]:
if(i in passW):
count+=1
return count | 93a28149ea88e06c5db714ba98feadf035fdb645 | 593,117 |
def int_to_32bit_array(val):
"""
Converts an integer to 32 bit bytearray
:param val: the value to convert to bytes
:return: bytearray
"""
value = val
bytes = bytearray()
for i in range(4):
bytes.insert(0, (value & 0xff))
value >>= 8
return str(bytes) | b37475f6e7223df1352d8fd84463c31230444b15 | 593,118 |
def getShapes(node):
"""Returns the shape of the dagNode
Arguments:
node (dagNode): The input node to search the shape
Returns:
list: The shapes of the node
"""
return node.listRelatives(shapes=True) | 290710ebfbc43830e847a441cb59beedf4aa7989 | 593,119 |
import torch
def get_prewitt_kernel_3x3() -> torch.Tensor:
"""
Utility function that returns a prewitt kernel of 3x3
in x direction (transpose for y direction).
Prewitt in x direction: This mask is called the
(vertical) Prewitt Edge Detector
prewitt_x=... | 56878a5fab88620e41083be45bd83c0b04b290df | 593,121 |
def is_symbol_included_for_completeness(symbol: str) -> bool:
""" Determine whether a symbol is listed for sake of type completeness. """
return symbol.endswith(':completeness') | 73167fd0da6da59e43bdfb17a651610790181708 | 593,122 |
import struct
def read_int64(file_obj):
"""
Reads an 8 byte binary integer from a file. From David Palzer.
:param file_obj: The open file object from which to read.
:return: The eight bytes read from the file object interpreted as a long int.
"""
return struct.unpack('q', file_obj.read(8))[0] | 833f9b0926956e0b93e18e45ea8093a8e0610a16 | 593,124 |
def get_tf_opname_for_layer(model, layer_name, output_op = False):
"""Return tf i/o node name for a layer of keras model"""
try:
layer = model.get_layer(layer_name)
except ValueError:
return None
if output_op:
return layer.output.op.name
else:
return layer.input.op.n... | 3b5788ffcb96f072dea967cd09b41772e0fc96e1 | 593,127 |
def popular_articles(count=3):
"""
Gets the list of the most popular articles
:param count: The number of articles to return. Default 3.
:return: The query string
"""
return """
SELECT COUNT(log.status) as views, articles.title
FROM articles, log
WHERE log.path = ... | 3421059b43846d2bd6bf6d817d3986b2212e43de | 593,129 |
def unique_list(l):
"""Return unique list form list."""
r = []
for i in l:
if i not in r:
r.append(i)
return r | 7b0590535165ced3ca979074e43288f69929ae02 | 593,130 |
def get_info_dict(info_string):
"""Convert a info string to a dictionary
Args:
info_string(str): A string that contains the INFO field from a vcf variant
Returns:
info_dict(dict): The input converted to a dictionary
"""
info_dict = {}
if not info_string:
return info_dic... | 3afd529bb4eed653f538cbc266f7533a2e4aa5ba | 593,131 |
import random
def generate_odd_one_out_array(n, seed=None):
""" Generate an array of n sets of integers that occur an even number of
times and a single integer that occurs an odd number of times"""
arr = []
for i in range(n):
# Optionally Make data NOT random for use in static tests
i... | 2d6fd6c2c32baf90827d020ff5046ea448f6508e | 593,133 |
def dot(a, b):
"""Compute the dot product between the two vectors a and b."""
return sum(i * j for i, j in zip(a, b)) | 93c727467a62ec3ce93a0b612624cb0eab57b120 | 593,135 |
def compute_tally(vec):
"""
Here vec is an iterable of elements.
Return dict giving tally of elements.
"""
tally = dict()
for x in vec:
tally[x] = tally.get(x, 0) + 1
return tally | 0c39226f6a7710e597d7f6b82abaea18df6edd7d | 593,139 |
def _locations_tolist(x):
"""Transforms recursively a list of iterables into a list of list."""
if hasattr(x, '__iter__'):
return list(map(_locations_tolist, x))
else:
return x | a836d8ee13b2578960509a55551d3acf32a87569 | 593,140 |
import json
def from_json_string(my_str):
""" decodes a JSON str """
x = json.loads(my_str)
return x | a063686b664decfe295d426dd72ed4c9e09c798e | 593,142 |
def _find_start_end_time(stream):
"""
find the start and end time of a specific stream.
:param stream:
:return starttime, endtime:
"""
starttime = []
endtime = []
for tr in stream:
starttime.append(tr.stats.starttime)
endtime.append(tr.stats.endtime)
return max(st... | 07267d0fdb114048e5862db916edc666a1509155 | 593,143 |
import torch
def deque_to_tensor(last_num_frames):
""" Convert deque of n frames to tensor """
return torch.cat(list(last_num_frames), dim=0) | c5887b2f814f66ef9677d658c72004d6f32af7c0 | 593,146 |
def do_query(documents, config_file=None, logger=None, context=None):
"""
Gets metadata about an XML document.
Returns result of form:
[
<FILENAME>:
{
doctype: <DOCTYPE>,
namespaces: {<TAG>: <URL>, <TAG>: <URL>, ...},
no_ns_sc... | 174b18db1450ceb2b5107b9bb9820feece75b88a | 593,149 |
def _compute_energy_fb_feat_names(data, freq_bands, deriv_filt):
"""Utility function to create feature names compatible with the output of
:func:`mne_features.univariate.compute_energy_freq_bands`."""
n_channels = data.shape[0]
if isinstance(freq_bands, dict):
n_freq_bands = len(freq_bands)
... | 3658dbaed0dd7dddcb51c650079467669433e478 | 593,159 |
import torch
def cal_negative_logistic_loss(preds, targets, reduction="mean", **kwargs):
"""
preds: (batch_size, vector_size)
targets: (batch_size, vector_size)
"""
# (batch_size, )
scalar_product = torch.matmul(preds, targets.transpose(0, 1)).diagonal()
loss = torch.log(1 + torch.exp(scal... | 800040e1a403c3be115524b4b5ede56b4c835041 | 593,160 |
def get_keys(dic, key_path=""):
"""get_keys of nested dictionary
>>> a = {"a": 1, "b": {"c": 2}}
>>> get_keys(a)
['/a', '/b/c']
"""
keys_list = []
def get_keys(dic, key_path):
if isinstance(dic, dict):
for i in dic:
get_keys(dic[i], key_path + "/" + str... | 1dc0bbca91d51dc5074aaaa56466e267a28e1816 | 593,165 |
def filter_samples_by_nan(data_df, sample_frac_cutoff):
""" Filter out samples whose fraction of probes measured is less than sample_frac_cutoff.
Args:
data_df (pandas df)
sample_frac_cutoff (float b/w 0 and 1)
Returns:
out_df (pandas df): potentially smaller than input
"""
... | 4043d05a72212e5700a09663e5cd9aec40912a0c | 593,168 |
import re
def split_text(text, **kwargs):
"""
Splits text by either spaces and \n, or by kwargs['pattern'].
"""
pattern = kwargs.get("pattern", None)
if pattern is None:
pattern = r'\s+|\n+'
return [x.strip() for x in re.split(pattern, text) if x != ''] | 4ff0380fcc969b943e3b14665c0b9cb2fba0c1b7 | 593,171 |
def humanize_list(l):
"""Return a human-readable list."""
if len(l) == 1:
return l[0]
elif len(l) == 2:
return "{0} and {1}".format(l[0], l[1])
else:
return ", ".join(l[:-1]) + ", and " + l[-1] | 3e5d33af1e1e05e6f09003036f0e9e176f47fb7d | 593,175 |
import requests
def fetch_website(date):
"""
Fetch the website containing the data from ENTSOE.EU
Parameters
----------
date: something datetime-like
Returns
-------
str
"""
# the date needs to look like 24.02.2016 for the url
formatted_date = date.strftime("%d.%m.%Y")
... | 1cdf36612e2305abbcd6135c6e0145e609c48504 | 593,176 |
def get_traceback(db, job_id):
"""
Return the traceback of the given calculation as a list of lines.
The list is empty if the calculation was successful.
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
"""
# strange: understand why the filter... | 2af94b950c4492580140c5f349bb55fbd2ed30f6 | 593,179 |
import socket
def verify_ip(ip_, address_family):
"""Verify that a string is an IP in a given family (IPv4 or IPv6).
Args:
ip_ (bytes): The IP address as a bytestring.
address_family (socket.AddressFamily): The expected address family of
the IP address,
Returns:
str: T... | e3bff5cc4e207320b75bfeb1398f267340d82d8e | 593,180 |
def spin_stat_factor(J,I):
"""
The spin statistical factor
The spin statistical factor is the probability that
a particular compound state will form for a given J
and I when neutrons interact with the nucleus.
Parameters
----------
J : float or array-like
J is the compound... | ba66551f2accc0ba87b7fe6f78312ee7df802a9f | 593,181 |
import functools
def ambiguous(decorator):
""" Decorator to allow the decorated function to be called with or without
parenthesis. Should only be used to decorate other decorator defintions"""
@functools.wraps(decorator)
def wrapper(*args, **kwargs):
if len(args) > 0:
f = args... | aca338ba1b63cc17d9c32da018eb719d2eee1cf4 | 593,182 |
import re
def pipe_cleaner(spec):
"""Guess the actual URL from a "pipe:" specification."""
if spec.startswith("pipe:"):
spec = spec[5:]
words = spec.split(" ")
for word in words:
if re.match(r"^(https?|gs|ais|s3)", word):
return word
return spec | 3c5237d3f20391c9bc40bfd3dd16f1e7df422b0a | 593,187 |
def _wall_pos_xyaxes(size):
"""Infers position and size of bounding walls given pitch size.
Walls are placed around `ground_geom` that represents the pitch. Note that
the ball cannot travel beyond `field` but walkers can walk outside of the
`field` but not the surrounding walls.
Args:
size: a tuple of (... | f1e4b9e5cddaa87328b6c210e66a490d3d1eef30 | 593,188 |
def post_or_get(request, key, fallback=None):
"""
Returns request param from GET and POST if available, fallback otherwise.
Precedence is POST, GET, then fallback if not found.
"""
return request.POST.get(key, request.GET.get(key, fallback)) | 25024fc8d8211c15f869958bd57b83d0e6801af8 | 593,191 |
def unitarity_decay(A, B, u, m):
"""Eq. (8) of Wallman et al. New J. Phys. 2015."""
return A + B * u ** m | 0d3e5f8f1648bf8e8aff9fc5f17766c737b7a228 | 593,192 |
from datetime import datetime
def create_report_footer(journal_text):
""" Create report's footer. """
today = datetime.now()
journal_text = journal_text + "<hr>"
journal_text = journal_text + "Report generated on: " + today.strftime(
'%d %b %Y, %H:%M:%S %z') + " by <a href='https://github.com/... | 8c11bc95735e666f7766b103de5aed89f6970fcb | 593,194 |
def subset_with_values(target, lst):
"""Determines whether or not it is possible to create the target sum using
values in the list. Values in the list can be positive, negative, or zero.
The function returns a tuple of exactly two items. The first is a boolean,
that indicates true if the sum is possible... | 512325fa7380bdbb140dc36488b42fe95436db3a | 593,196 |
def available_screen_size(session):
"""
Returns the effective available screen width/height size,
excluding any fixed window manager elements.
"""
return tuple(session.execute_script("""
return [
screen.availWidth - screen.availLeft,
screen.availHeight - screen.availT... | 2f9fed4fb0fdbcc3a1792ed800010518095fec1e | 593,200 |
def create_node_coverage(graph, reference_coverage):
"""
Create node coverage for a terminal graph given a reference coverage consisting of node_ids.
"""
coverage = ['0'] * len(reference_coverage)
graph_node_ids = set(node.node_id for node in graph.nodes)
for index, node_id in enumerate(refere... | e43ddd851139738b2ab7dea09c5f2833fc34416f | 593,201 |
def dynamic_filename(inputs, wildcards, pattern):
"""
Generate a filename dynamically by
formatting a pattern with
input values and wildcards
:param inputs:
:param wildcards:
:param pattern:
:return:
"""
return pattern.format(inputs=inputs, wildcards=wildcards) | 0844e7d3fdfcd81c5c615c5a72a5d1558e4b86e0 | 593,202 |
def gens_by_bus(buses, gens):
"""
Return a dictionary of the generators attached to each bus
"""
gens_by_bus = {k: list() for k in buses.keys()}
for gen_name, gen in gens.items():
gens_by_bus[gen['bus']].append(gen_name)
return gens_by_bus | 3339177bf38689e3e2c5130e09725cb6de394a6c | 593,203 |
from pathlib import Path
import json
def getVocabulary(path):
"""
Retrieves the vocabulary from the vocabulary file of an ezxperiment
:param path: path of the vocabulary
:type path: String
:return: a dictionary with id as a key and word as value,
returns False if the vocabulary ... | 0053267bc553bd9d4e2337a169ed7b53a32ab911 | 593,204 |
def labels_to_onehot(labels, classes):
""" Convert a list of labels (integers) into one-hot format.
Parameters
----------
labels : list
A list of integer labels, counting from 0.
classes : int
Number of class integers.
Returns
-------
list
List of one-hot lists... | 886f7ccc954ffb86cc97db131b5108484ec40fa3 | 593,208 |
def get_nth_bit(block, n, blocksize=4) -> int:
"""Returns n-th bit in a `blocksize` bit block counting from left,
bit indexes start at 1.
"""
return block >> (blocksize-n) & 0b1 | 1aa0da95b5e55cc76fb76beefbb5df30395b08e5 | 593,211 |
import csv
def create_vlans_data(csv_path) -> dict:
"""
Args:
csv_path: path to the corresponding CSV file
Returns:
a dict with vlan_id:vlan_name mapping
Examples:
{'2': 'Printers',
'3': 'CCTV_&_TVs',
'4': 'Time_clocks',
'5': 'Voice_IP'}
"""
... | d455145c7f759fe21317b7f1f2b95cda2969f755 | 593,214 |
def truncate_list(ts, n=9):
"""Truncate the elements of a list, keeping elements at each end, and
replacing the omitted middle with a single character, an ellipsis ('…').
Note that this is not '...', but the unicode character for an ellipsis
proper. After all, we *are* making a typesetting program."""
... | 79fc90b2e2be8336f88931e970ae32ddd4cf0ec5 | 593,215 |
def get_entities(filepath):
"""Load saved list of phrases or named entities. These are used to
"""
with open(filepath) as f:
return f.read().splitlines() | 7ae2dcf2187bb6cab9bea028f86fcfa16ad0dc28 | 593,216 |
from textwrap import dedent
def formatHelp(help, sep=' '):
"""
Dedent help text and strip blank lines.
@returns: A "short help" and the complete help
@rtype: C{(shortHelp, help)}
"""
lines = [line.strip()
for line in dedent(help).splitlines()
if line.strip()]
ret... | 927005d4dbe14100f051b1a6aff83abbdf3a50d5 | 593,223 |
import base64
def decode(s):
"""
Base64 decode.
:param s:
:return: str
"""
if isinstance(s, str):
if len(s) % 4 > 0:
s = s + '=' * (4 - len(s) % 4)
s = s.encode('utf-8')
# URL Safe
s = s.translate(bytes.maketrans(b'-_', b'+/'))
try:
return bas... | c6fbd15e391a329253445a911d54e9fbdf1d522c | 593,229 |
def encode_html(unicode_data: str, encoding: str = 'ascii') -> bytes:
"""
Encode unicode_data for use as XML or HTML, with characters outside
of the encoding converted to XML numeric character references.
"""
return unicode_data.encode(encoding, 'xmlcharrefreplace') | 8ea448bc0a8a7a1883128dd26bb5fdc1df23ffde | 593,230 |
def course_reverse_func_from_name_func(reverse_name_func):
"""
Returns a function that will determine a course URL for the provided
reverse_name_func.
Use this when the calculation of the reverse_name is dependent on the
course. Otherwise, use the simpler course_reverse_func.
This can be used ... | e865856ea6cb6d0122fe501e44c59e473d03e372 | 593,232 |
import random
def word_selection(file_name):
"""
file_name: string, the file which contains the words
returns: a random word from words.txt file
"""
with open(file_name, 'r') as f:
words_list = f.read().splitlines()
random_word = random.choice(words_list)
return random_word | 2a590b19e5f58846aeb12080846ad591b9082e00 | 593,234 |
def HasOnlyOneRootBone(obj):
"""
Returns True if @obj only has a single root bone without siblings.
@obj (bpy.types.Object). Object.type is assumed to be 'ARMATURE'
"""
bones = obj.data.bones
rootBoneCount = 0
for bone in bones:
if bone.parent == None:
rootBoneCount += 1
... | 7162b5207ad63168b623515635d522010537b316 | 593,239 |
from typing import Callable
def deduplicate_by(elements: list, fcn: Callable):
"""De-duplicate list via a function of each element."""
return list(dict((fcn(element), element) for element in elements).values()) | cb252d8e9c7af05286ad5be85ba33306d46ad563 | 593,248 |
def is_in_bounds(grid, x, y):
"""Get whether an (x, y) coordinate is within bounds of the grid."""
return (0 <= x < len(grid)) and (0 <= y < len(grid[0])) | 6db32384bed01c99aa4347d8c6919a91adc3adf2 | 593,249 |
def split_num(num, n):
"""
Divide num into m=min(n, num) elements x_1, ...., x_n, where x_1, ..., x_n >= 1 and max_{i,j} |x_i - x_j| <= 1
"""
n = min(num, n)
min_steps = num // n
splits = []
for i in range(n):
if i < num - min_steps * n:
splits.append(min_steps + 1)
... | bbe69833b829dea8ca62f1b7646ad53eb8cebc80 | 593,252 |
def get_description(model_class):
"""
Returns the model's description from the docstring.
"""
return model_class.__doc__.split("# Parameters")[0].strip() | 1ff23a7a2775d24bc0f0facb5392149a3f90c95f | 593,254 |
def ibwt(r: str) -> str:
"""Apply inverse Burrows-Wheeler transform."""
table = [""] * len(r) # Make empty table
for i in range(len(r)):
table = sorted(r[i] + table[i] for i in range(len(r))) # Add a column of r
s = [row for row in table if row.endswith("\003")][0] # Find the correct row (end... | d59570de8fbb94de5685126b372556801a5f7f33 | 593,256 |
def absolute(input):
"""Valor absoluto
Devuelve el valor absoluto de la entrada input.
Args:
input(Number): valor real
Returns:
Number
"""
return abs(input) | 6742157a5dda867c084ec4ece9289223521a6898 | 593,257 |
def form_to_data_cube_parameters(form_instance):
"""Converts some of the all caps/other form data parameters to the required Data Cube parameters"""
individual_dates = form_instance.cleaned_data['times']
date_ranges = form_instance.cleaned_data['time_ranges']
return {
'product': form_instance.c... | ac1221cd922b01e3a31b219b6ebf4e1522343da8 | 593,261 |
def mongo_logical_and(document_filters):
""" Combine document filters with logical and operation.
"""
if not any(document_filters):
return None
return {"$and": [_ for _ in document_filters if _]} | b5a07ce7d07b9e1662c7a2d82f96282cda29f1ca | 593,271 |
def pegtop_blending(rgba, norm_intensities):
""" Calculates image colors with the Pegtop Light shading of ImageMagick
See:
http://www.imagemagick.org/Usage/compose/#pegtoplight
Forked from Ran Novitsky's blog (no license found)
http://rnovitsky.blogspot.nl/2010/04/u... | 878d1c09d9746b20d47284d931a5da0f4aa0cf29 | 593,272 |
def positive_response_id(service_id: int) -> int:
"""Given a service ID of a request, return the corresponding SID for a positive response"""
assert service_id != 0x7f - 0x40
return service_id + 0x40 | 3906aff13c397a116c722c414d3afccd65ca91e9 | 593,273 |
import requests
def check_uri(uri, timeout=5):
"""
Checks if a uri returns response of 200 if it is requested
Will return True if the response is 200, false otherwise
:param uri: URI to request
:param timeout: how long to return False, if we do not get a response
:return: True/False
:rtype... | fdb5f34facef287d47900508e124e81b88c57fc7 | 593,274 |
import six
def MaxSizeInDistribution(dist):
"""Find the maximum object size in a distribution."""
return max(six.iterkeys(dist)) | 415b6bb54fe5722fed92cdb6ce96d606719f46b1 | 593,277 |
def temp_or_none(t):
"""Return the supplied temperature as a string in the format
"%5.1f" or a hyphen, if unavailable (None).
"""
if t is None:
return " -"
return "%5.1f" % t | b8fcb83796cc508ee9112e2680b5c1c6815aa59b | 593,278 |
def ressymbol(name):
"""
Dictionary containing conversion from residue 3-letter symbol to 1-letter symbol
Parameters
----------
name : str
Residue symbol (3-letter convention)
Returns
-------
oneletter : str
Residue symbol (1-letter convention)
"""
reslist = {... | 75c0e9aa275c4c43cea74552a424d0ebb263b7f0 | 593,280 |
def db_user() -> str:
"""Database user"""
return 'root' | 45abb1fae264fa96232daf5f38b253b5b957be38 | 593,284 |
def get_lr_master_url(resource):
"""
Returns the full URL of the master copy of the given resource object.
This URL points to the single resource view of the resource on the resource'
master node.
"""
return "{0}/{1}".format(resource.storage_object.source_url,
re... | cd89ef78df9cb08653aefc28fb261df62cd7b5e4 | 593,286 |
def extract_episode_details(season, episode_response):
"""Clean and extract episode details response.
Take an episode details response and cleans the data.
Extract the relevant fields needed to construct an
Episode object.
Args:
season: The season number
episode_response: An episod... | dc236736d69a1521961adf09ad871a4b1c0a49d4 | 593,288 |
def add(a, b):
"""
Example add function with docstring and doctest
Parameters
----------
a : int
Number
b : int
Number
Returns
-------
result : sum of ``a`` and ``b``
>>> add(3, 2)
5
"""
return a + b | e31c3b411aa68c75eb6cdf3c490d0986ea8a593f | 593,293 |
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None | ffadd9e06a20acdcda4b2d085e086e31ad53c694 | 593,296 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.