content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def double_middle_drop(progress):
"""
Returns a linear value with two drops near the middle to a constant value for the Scheduler
:param progress: (float) Current progress status (in [0, 1])
:return: (float) if 0.75 <= 1 - p: 1 - p, if 0.25 <= 1 - p < 0.75: 0.75, if 1 - p < 0.25: 0.125
"""
eps1... | bfdf14ac75e63b88160f6c511d26c76031f9c663 | 41,453 |
def split_info_from_job_url(BASE_URL, job_rel_url):
"""
Split the job_rel_url to get the separated info and
create a full URL by combining the BASE_URL and the job_rel_url
:params:
job_rel_url str: contain the Relative Job URL
:returns:
job_id str: the unique id contained in the job_... | 276db11041c18a1675ca10b9581a898787b11321 | 41,457 |
def get_long_id(list_session_id):
"""Extract longitudinal ID from a set of session IDs.
This will create a unique identifier for a participant and its corresponding sessions. Sessions labels are sorted
alphabetically before being merged in order to generate the longitudinal ID.
Args:
list_sess... | f5b0ffa6fe75c9059453d0a2d32456dd88da2a16 | 41,460 |
def get_attrname(name):
"""Return the mangled name of the attribute's underlying storage."""
return '_obj_' + name | 02d7983a02f7a112479d6289ab1a4ddcb8a104a7 | 41,468 |
def extract_valid_libs(filepath):
"""Evaluate syslibs_configure.bzl, return the VALID_LIBS set from that file."""
# Stub only
def repository_rule(**kwargs): # pylint: disable=unused-variable
del kwargs
# Populates VALID_LIBS
with open(filepath, 'r') as f:
f_globals = {'repository_rule': repository_... | e8e9b60dcd86e6216b7d3d321a079da09efa19e8 | 41,475 |
import itertools
def normalise_environment(key_values):
"""Converts denormalised dict of (string -> string) pairs, where the first string
is treated as a path into a nested list/dictionary structure
{
"FOO__1__BAR": "setting-1",
"FOO__1__BAZ": "setting-2",
"FOO__2__FOO": "setting-... | b8670458415404d673e530b0a6e15c9a050ea4ca | 41,476 |
def create_commit(mutations):
"""A fake Datastore commit method that writes the mutations to a list.
Args:
mutations: A list to write mutations to.
Returns:
A fake Datastore commit method
"""
def commit(req):
for mutation in req.mutations:
mutations.append(mutation)
return commit | dc7cfa4c3f79076c2b67e3261058ab5d55e1f189 | 41,478 |
def is_paired(input_string:str):
"""
Determine that any and all pairs are matched and nested correctly.
:param input_string str - The input to check
:return bool - If they are matched and nested or not.
"""
stack = []
for char in input_string:
if char in ['[', '{', '(']:
... | 040d79e471831d4444ffded490f39ed90247e39e | 41,480 |
import random
def random_value_lookup(lookup):
"""Returns a object for a random key in the lookup."""
__, value = random.choice(list(lookup.items()))
return value | b1d7b3859cd9232df2a41505ee4f2bdfaa2607a4 | 41,484 |
def symbols(vma):
""" Obtain the atomic symbols for all atoms defined in the V-Matrix.
:param vma: V-Matrix
:type vma: automol V-Matrix data structure
:rtype: tuple(str)
"""
return tuple(zip(*vma))[0] if vma else () | 3f2a547e7ec0eb17e681ec2fe5de93057fdaa22a | 41,491 |
import pickle
def decode_dict(dictionary):
"""Decodes binary dictionary to native dictionary
Args:
dictionary (binary): storage to decode
Returns:
dict: decoded dictionary
"""
decoded_dict = pickle.loads(dictionary)
return decoded_dict | 158d7db725f1856c276f867bfea3482c3fbe283b | 41,494 |
def form_fastqc_cmd_list(fastqc_fp, fastq_fp, outdir):
"""Generate argument list to be given as input to the fastqc function call.
Args:
fastqc_fp(str): the string representing path to fastqc program
fastq_fp(str): the string representing path to the fastq file to be evaluated
outdir(st... | ce0ed8eb7d35bdd2565f910bb982da710daa23c5 | 41,495 |
from datetime import datetime
def get_timestamp_utc() -> str:
"""Return current time as a formatted string."""
return datetime.utcnow().strftime("%Y-%m-%d-%H%M%S") | 05a1cfeeda438a8f5f9857698cb2e97e4bb62e96 | 41,496 |
def rtd10(raw_value):
"""Convert platinum RTD output to degrees C.
The conversion is simply ``0.1 * raw_value``.
"""
return (float(raw_value) / 10.0, "degC") | 5b44908c722ff8298cf2f4985f25e00e18f05d21 | 41,500 |
def reverse_list(l):
"""
return a list with the reverse order of l
"""
return l[::-1] | 21bf60edf75a6016b01186efccdae9a8dd076343 | 41,503 |
import requests
def query_graphql(query, variables, token):
"""Query GitHub's GraphQL API with the given query and variables.
The response JSON always has a "data" key; its value is returned
as a dictionary."""
header = {"Authorization": f"token {token}"}
r = requests.post("https://api.github.com/... | 72da627b5600973303ae4001bf3b07f738212f04 | 41,506 |
def get_passive_el(passive_coord, centroids):
""" Gets index of passive elements .
Args:
passive_coord (:obj:`tuple`): Region that the shape will not be changed.
centroids (:obj:`numpy.array`): Coordinate (x,y) of the centroid of each element.
Returns:
Index of passive elements... | 9983ee9d730ced9f8ce56790c07af22c9dfcdb0d | 41,507 |
def get_exposure_id(exposure):
"""Returns exposure id.
"""
expinf = exposure.getInfo()
visinf = expinf.getVisitInfo()
expid = visinf.getExposureId()
return expid | a269a08cd62b629d65db803d92d6e6356b76feab | 41,508 |
import re
def escapeRegex(text):
"""
Escape string to use it in a regular expression:
prefix special characters « ^.+*?{}[]|()\$ » by an antislash.
"""
return re.sub(r"([][^.+*?{}|()\\$])", r"\\\1", text) | 97f13b05996daf2a7d01ade0e428244bed156af4 | 41,509 |
def none(active):
"""No tapering window.
Parameters
----------
active : array_like, dtype=bool
A boolean array containing ``True`` for active loudspeakers.
Returns
-------
type(active)
The input, unchanged.
Examples
--------
.. plot::
:context: close-fi... | e323f7e153049a4f663688d7bee4b73bd8dd1ca9 | 41,513 |
import re
def get_sandwich(seq, aa="FYW"):
"""
Add sandwich counts based on aromatics.
Parameters:
seq: str, peptide sequence
aa: str,
amino acids to check fo rsandwiches. Def:FYW
"""
# count sandwich patterns between all aromatic aminocds and do not
# distinguish... | d8df68a1873d3912aa64fc91563aae9827da324c | 41,514 |
def is_param_free(expr) -> bool:
"""Returns true if expression is not parametrized."""
return not expr.parameters() | e9dadcaae0c9c0cdcffe1afe5202925d98c6b4fb | 41,519 |
def null_count(df):
"""
Returns the number of null values in the input DataFrame
"""
return df.isna().sum().sum() | d92582292a01412df3433cfaa69ec68a92057301 | 41,522 |
def get_armstrong_value(num):
"""Return Armstrong value of a number, this is the sum of n**k
for each digit, where k is the length of the numeral.
I.e 54 -> 5**2 + 4**2 -> 41.
Related to narcisstic numbers and pluperfect digital invariants.
"""
num = str(num)
length = len(num)
armstrong_... | fd0692566ab0beffb785c1ac4fbd4aa27893cfbf | 41,523 |
import re
def convert_bert_word(word):
"""
Convert bert token to regular word.
"""
return re.sub("##|\[SEP\]|\[CLS\]", "", word) | f7f7d95fd7fd90b55a104ce13e10b08f6ae0c9f0 | 41,526 |
def cleanly_separate_key_values(line):
"""Find the delimiter that separates key from value.
Splitting with .split() often yields inaccurate results
as some values have the same delimiter value ':', splitting
the string too inaccurately.
"""
index = line.find(':')
key = line[:index]
value = line[index + 1:]
r... | d790f6bca2b52ee87bce01467a561901ba08655d | 41,527 |
def batch(tensor, batch_size = 50):
""" It is used to create batch samples, each batch has batch_size samples"""
tensor_list = []
length = tensor.shape[0]
i = 0
while True:
if (i+1) * batch_size >= length:
tensor_list.append(tensor[i * batch_size: length])
return tens... | 2b4b10520fd72b90ebe1239b7f52e61ba442484d | 41,528 |
def mse(predictions, targets):
"""Compute mean squared error"""
return ((predictions - targets) ** 2).mean() | 516c8767731577db36dc4b503c179c034fca1166 | 41,531 |
def _command(register_offset, port_number, register_type):
"""Return the command register value corresponding to the register type for a given port number and register offset."""
return (register_offset * register_type) + port_number | d09815a2451e86448e0da280c8b037b59cfbd87b | 41,532 |
import math
def myceil(x, base=10):
"""
Returns the upper-bound integer of 'x' in base 'base'.
Parameters
----------
x: float
number to be approximated to closest number to 'base'
base: float
base used to calculate the closest 'largest' number
Returns
-------
n_h... | 6e52b99755cdd25b882f707c54c3ff27f8ff279e | 41,537 |
def get_branch_name(ref):
"""
Take a full git ref name and return a more simple branch name.
e.g. `refs/heads/demo/dude` -> `demo/dude`
:param ref: the git head ref sent by GitHub
:return: str the simple branch name
"""
refs_prefix = 'refs/heads/'
if ref.startswith(refs_prefix):
... | bb7e791c6dac430fef9a38f8933879782b943fd1 | 41,542 |
def stdin(sys_stdin):
"""
Imports standard input.
"""
return [int(x.strip()) for x in sys_stdin] | 54964452384ae54961472328e603066f69391957 | 41,546 |
from typing import Tuple
def parse_interval(interval: str) -> Tuple[str, str, str]:
"""
Split the interval in three elements. They are, start time of the working day,
end time of the working day, and the abbreviation of the day.
:param interval: A str that depicts the day, start time and end time
... | f2bac53a1b56e1f6371187743170646c08109a27 | 41,547 |
def surrogate_loss(policy, all_obs, all_actions, all_adv, old_dist):
"""
Compute the loss of policy evaluated at current parameter
given the observation, action, and advantage value
Parameters
----------
policy (nn.Module):
all_obs (Variable):
all_actions (Variable):
all_adv (Variab... | 26e0f53e91a9537a4b9d0bfc3a3122dbe4917fc2 | 41,550 |
def _get_zero_one_knapsack_matrix(total_weight: int, n: int) -> list:
"""Returns a matrix for a dynamic programming solution to the 0/1 knapsack
problem.
The first row of this matrix contains the numbers corresponding to the
weights of the (sub)problems. The first column contains an enumeration of
... | bc96eb43f487b6ad20b143c177474ba04afc2319 | 41,551 |
def read_atom_file(file):
"""Read file with atoms label
Args:
file (str): Name of file with atoms labels
Returns:
list: atoms labeled as <Residue Name> <Atom Name>
"""
atoms = [line.rstrip('\n').split() for line in open(file, "r")]
atoms = [[a[0] + " " + aa for aa in a[1::]] fo... | 3d85dff55f7165d1c9b747eb75d395ec03f5b3ce | 41,554 |
def combine_bolds(graph_text):
"""
Make ID marker bold and remove redundant bold markup between bold elements.
"""
if graph_text.startswith("("):
graph_text = (
graph_text.replace(" ", " ")
.replace("(", "**(", 1)
.replace(")", ")**", 1)
.replace(... | b87afc51de6bb1e83c0f8528773e50f5d797fe2d | 41,555 |
def format_id(kepler_id):
"""Formats the id to be a zero padded integer with a length of 9 characters.
No ID is greater than 9 digits and this function will throw a ValueError
if such an integer is given.
:kepler_id: The Kepler ID as an integer.
:returns: A 0 padded formatted string of length 9.
... | 427726b825f6ee1c4a20c07d098a3a063c18a0c1 | 41,556 |
def rev_comp(s):
"""A simple reverse complement implementation working on strings
Args:
s (string): a DNA sequence (IUPAC, can be ambiguous)
Returns:
list: reverse complement of the input sequence
"""
bases = {
"a": "t", "c": "g", "g": "c", "t": "a", "y": "r", "r": "y", "w"... | 3fd61300016da5e8546f0c00303a8477af79902f | 41,559 |
def sumIO(io_list, pos, end_time):
"""
Given io_list = [(timestamp, byte_count), ...], sorted by timestamp
pos is an index in io_list
end_time is either a timestamp or None
Find end_index, where io_list[end_index] is the index of the first entry in
io_list such that timestamp > end_time.
Sum the byte_cou... | a6b36148e05ac57f599bc6c68ffac242020dc65f | 41,561 |
def is_child_class(target, base):
""" Check if the target type is a subclass of the base type and not base type itself """
return issubclass(target, base) and target is not base | 731c551149f94401a358b510aa124ee0cba6d0bd | 41,567 |
def get_pyramid_single(xyz):
"""Determine to which out of six pyramids in the cube a (x, y, z)
coordinate belongs.
Parameters
----------
xyz : numpy.ndarray
1D array (x, y, z) of 64-bit floats.
Returns
-------
pyramid : int
Which pyramid `xyz` belongs to as a 64-bit int... | 8fe2fbc727f13adf242094c3b0db3805af31a1e9 | 41,569 |
import copy
def get_midpoint_radius(pos):
"""Return the midpoint and radius of the hex maze as a tuple (x,y), radius.
Params
======
pos: PositionArray
nelpy PositionArray containing the trajectory data.
Returns
=======
midpoint: (x0, y0)
radius: float
"""
# make a loc... | 76290309f12e00b6a487f71b2393fabd8f3944ac | 41,570 |
from pathlib import Path
from typing import Tuple
from typing import List
def listdir_grouped(root: Path, ignore_folders=[], include_hidden=False) -> Tuple[List, List]:
"""Dizindeki dosya ve dizinleri sıralı olarak listeler
Arguments:
root {Path} -- Listenelecek dizin
Keyword Arguments:
... | 13d2ea09cafd3b4062714cbf151c0a4b290616e1 | 41,574 |
from typing import Optional
from typing import List
def _with_config_file_cmd(config_file: Optional[str], cmd: List[str]):
""" Prefixes `cmd` with ["--config-file", config_file] if
config_file is not None """
return (["--config-file", config_file] if config_file else []) + cmd | a7a93f2b089e4265a22fb7fd0ccced1e78e1c55c | 41,575 |
def _clip_points(gdf, poly):
"""Clip point geometry to the polygon extent.
Clip an input point GeoDataFrame to the polygon extent of the poly
parameter. Points that intersect the poly geometry are extracted with
associated attributes and returned.
Parameters
----------
gdf : GeoDataFrame, ... | c7f21807d28f37044a4f36f4ededce26defbb837 | 41,578 |
import re
def get_relval_id(file):
"""Returns unique relval ID (dataset name) for a given file."""
dataset_name = re.findall('R\d{9}__([\w\d]*)__CMSSW_', file)
return dataset_name[0] | 5b3369920ae86d7c4e9ce73e1104f6b05779c6d4 | 41,584 |
def splitdrive(path):
"""Split a pathname into drive and path specifiers.
Returns a 2-tuple "(drive,path)"; either part may be empty.
"""
# Algorithm based on CPython's ntpath.splitdrive and ntpath.isabs.
if path[1:2] == ':' and path[0].lower() in 'abcdefghijklmnopqrstuvwxyz' \
and (pa... | ed50877516130669cfe0c31cd8a6d5085a83e7c6 | 41,586 |
import re
def safe_filename(url):
"""
Sanitize input to be safely used as the basename of a local file.
"""
ret = re.sub(r'[^A-Za-z0-9]+', '.', url)
ret = re.sub(r'^\.*', '', ret)
ret = re.sub(r'\.\.*', '.', ret)
# print('safe filename: %s -> %s' % (url, ret))
return ret | 4f43984c35678e9b42e2a9294b5ee5dc8c766ac6 | 41,588 |
async def combine_channel_ids(ctx):
"""Combines all channel IDs.
Called by `channel_setter` and `channel_deleter`.
Args:
ctx (discord.ext.commands.Context): context of the message
Returns:
list of int: of Discord channel IDs
"""
channels = []
if not ctx.message.channel_me... | 1351faa7e49ce026d4da04c2c8886b62a5f294c3 | 41,589 |
def get_role_arn(iam, role_name):
"""Gets the ARN of role"""
response = iam.get_role(RoleName=role_name)
return response['Role']['Arn'] | ab6ed4fa7fd760cd6f5636e77e0d1a55372909a8 | 41,590 |
import logging
def get_logger(name: str, level: int = logging.INFO) -> logging.Logger:
"""
Creates a logger with the given attributes and a standard formatter format.
:param name: Name of the logger.
:param level: Logging level used by the logger.
:return: The newly or previously created Logger ob... | 7348e1775d236e34e25d9810d71db59a7faff88e | 41,594 |
def gera_estados(quantidade_estados: int) -> list:
"""
Recebe uma quantidade e retorna uma lista com nomes de estados
"""
estados: list = []
for i in range(quantidade_estados):
estados.append('q'+str(i))
return estados | 555ff4821626121b4e32d85acfa1f2ef2a7b08bb | 41,596 |
def valid_cards_syntax(cards_str):
""" Confirm that only numeric values separated by periods was given as input """
cards = cards_str.split('.')
for c in cards:
if not c.isnumeric():
return 'Cards must contain only digits 0-9 separated by periods'
return None | 8e3811505075269d2b1a37751c14017e107ce69b | 41,597 |
def db_to_amplitude(amplitude_db: float, reference: float = 1e-6) -> float:
"""
Convert amplitude from decibel (dB) to volts.
Args:
amplitude_db: Amplitude in dB
reference: Reference amplitude. Defaults to 1 µV for dB(AE)
Returns:
Amplitude in volts
"""
return reference... | d1a2a4a1c82ad2d3083b86687670af37dafa8269 | 41,599 |
def simple_expand_spark(x):
""" Expand a semicolon separated strint to a list (ignoring empties)"""
if not x:
return []
return list(filter(None, x.split(";"))) | 1d4a9f8007f879c29770ea0ea8350a909b866788 | 41,602 |
def get_output_parameters_of_execute(taskFile):
"""Get the set of output parameters of an execute method within a program"""
# get the invocation of the execute method to extract the output parameters
invokeExecuteNode = taskFile.find('assign', recursive=True,
value=la... | 56ba0c1f1941a72174befc69646b4bdb6bc9e009 | 41,606 |
def split_addr(ip_port: tuple[str, int]) -> tuple[int, ...]:
"""Split ip address and port for sorting later.
Example
--------
>>> split_addr(('172.217.163.78', 80))
>>> (172, 217, 163, 78, 80)
"""
split = [int(i) for i in ip_port[0].split(".")]
split.append(ip_port[1])
return tupl... | d768e493d9bdfe07923927c7d157683515c52d7d | 41,610 |
def is_set(bb, bit):
""" Is bit a position `bit` set? """
return (bb & 1 << bit) != 0 | 4990ccb7eb796da8141bf2b3aec7741addfe2a0c | 41,611 |
def redirect(status, location, start_response):
"""
Return a redirect code. This function does not set any cookie.
Args:
status (str): code and verbal representation (e.g. `302 Found`)
location (str): the location the client should be redirected to (a URL)
start_response: the start_... | 7fb5569d5872be69285a29c404b04df7ff7eef74 | 41,612 |
def count_att(data, column, value):
"""
:param data: Pandas DataFrame
:param column: specific column in the dataset
:param value: which value in the column should be counted
:return: probability of (value) to show in (column), included Laplacian correction
"""
dataset_len = len(data)
try... | 4dd11d02257ab2a5ac7fcc0f366de0286cdc84f7 | 41,615 |
def null_getter(d, fld, default="-"):
"""
Return value if not falsy else default value
"""
return d.get(fld, default) or default | 7970045e766c60e96bca005f86d214e21762f55c | 41,625 |
def get_list_string(data: list, delim: str = '\t', fmt: str = '{}') -> str:
"""Converts a 1D data array into a [a0, a1, a2,..., an] formatted string."""
result = "["
first = True
for i in data:
if not first:
result += delim + " "
else:
first = False
resul... | 25e9bb0e0220776ff79e121bab3bddf99168602d | 41,631 |
def mbar2kPa(mbar: float) -> float:
"""Utility function to convert from millibars to kPa."""
return mbar/10 | 9dcb74581fb099da0d136aad57de1c8ac3cf7c1d | 41,632 |
import re
def prep_for_search(string):
"""
Expects a string. Encodes strings in a search-friendy format,
lowering and replacing spaces with "+"
"""
string = re.sub('[^A-Za-z0-9 ]+', '', string).lower()
string = string.replace(" ", "+")
return string | 61a6762598fe3538b2d2e2328bc77de53fba4d74 | 41,638 |
def get_default_query_ids(source_id, model):
"""
Returns set of Strings, representing source_id's default queries
Keyword Parameters:
source_id -- String, representing API ID of the selection source
model -- Dict, representing current DWSupport configuration
>>> from copy import deepcopy
... | 766b69d32433d586dc086eec7ee1c27c312b7724 | 41,644 |
import aiohttp
from typing import List
from typing import Tuple
async def get_html_blog(
session: aiohttp.ClientSession,
url: str,
contests: List[int],
) -> Tuple[str, str, List[int]]:
"""Get html from a blog url.
Args:
session (aiohttp.ClientSession) : session
url (str) : blog u... | 1e0a0a573f1733370a1a59f37ca39a5cd0a5bb9c | 41,650 |
def query_string_to_kwargs(query_string: str) -> dict:
"""
Converts URL query string to keyword arguments.
Args:
query_string (str): URL query string
Returns:
dict: Generated keyword arguments
"""
key_value_pairs = query_string[1:].split("&")
output = {}
for key_value_p... | 9382d1c12cc2a534d9edbf183a3fcd3ea7b38968 | 41,651 |
import collections
def group_transcripts_by_name2(tx_iter):
"""Takes a iterable of GenePredTranscript objects and groups them by name2"""
r = collections.defaultdict(list)
for tx in tx_iter:
r[tx.name2].append(tx)
return r | a2fce0dfa8ba5e0b7321e977d1dbc8455ab6dfd1 | 41,653 |
def get_var_mode(prefix):
"""Returns False if { in prefix.
``prefix`` -- Prefix for the completion
Variable completion can be done in two ways and completion
depends on which way variable is written. Possible variable
complations are: $ and ${}. In last cursor is between
curly braces.
"""
... | ab080ae0ea2bce0ce2b267a2e7be839a6a982fb2 | 41,655 |
def lol2str(doc):
"""Transforms a document in the list-of-lists format into
a block of text (str type)."""
return " ".join([word for sent in doc for word in sent]) | 61f58f715f1a923c368fb0643a1cf4d7eddefb73 | 41,657 |
import textwrap
def _pretty_longstring(defstr, prefix='', wrap_at=65):
"""
Helper function for pretty-printing a long string.
:param defstr: The string to be printed.
:type defstr: str
:return: A nicely formated string representation of the long string.
:rtype: str
"""
outstr = ""
... | 19008289620b86b8760a36829cbaa97d117a8139 | 41,659 |
def kronecker(x, y):
"""
Returns 1 if x==y, and 0 otherwise.
Note that this should really only be used for integer expressions.
"""
if x == y:
return 1
return 0 | d28e9c101f61e04445b4d87d91cc7919e1921714 | 41,661 |
def space_join(conllu,sentence_wise=False):
"""Takes conllu input and returns:
All tokens separated by space (if sentence_wise is False), OR
A list of sentences, each a space separated string of tokens
"""
lines = conllu.replace("\r","").strip().split("\n")
lines.append("") # Ensure last blank
just_text = []
... | e3e752906b57090f56c2678031f295c5a8e66f29 | 41,669 |
def cumsum(arr):
""" Cumulative sum. Start at zero. Exclude arr[-1]. """
return [sum(arr[:i]) for i in range(len(arr))] | b629695089e731855b47c8fb3e39be222aeba1db | 41,670 |
def first(it):
"""Get the first element of an iterable."""
return next(iter(it)) | 535f9028d96e0e78bc310b4a8e75e558c9217172 | 41,671 |
from typing import Dict
import hashlib
import base64
def headers_sdc_artifact_upload(base_header: Dict[str, str], data: str):
"""
Create the right headers for sdc artifact upload.
Args:
base_header (Dict[str, str]): the base header to use
data (str): payload data used to create an md5 con... | 6895fff6d1a26cfb8009a3fedd2dcc9357efbe40 | 41,674 |
def content_disposition_value(file_name):
"""Return the value of a Content-Disposition HTTP header."""
return 'attachment;filename="{}"'.format(file_name.replace('"', '_')) | 9d7f50b95ab409013af39a08d02d6e7395abe545 | 41,676 |
def decode_dataset_id(dataset_id):
"""Decode a dataset ID encoded using `encode_dataset_id()`.
"""
dataset_id = list(dataset_id)
i = 0
while i < len(dataset_id):
if dataset_id[i] == '_':
if dataset_id[i + 1] == '_':
del dataset_id[i + 1]
else:
... | 08b31b17f8bda58379e7541eaedb1d1a128e9777 | 41,679 |
def _add_tag(tags, label: str) -> bool:
"""Adds the tag to the repeated field of tags.
Args:
tags: Repeated field of Tags.
label: Label of the tag to add.
Returns:
True if the tag is added.
"""
for tag in tags:
if tag.label == label:
# Episode already has the tag.
return False
... | 932399e97ae823ef0922929dc5123a587c06b211 | 41,680 |
def get_admin_net(neutron_client):
"""Return admin netowrk.
:param neutron_client: Authenticated neutronclient
:type neutron_client: neutronclient.Client object
:returns: Admin network object
:rtype: dict
"""
for net in neutron_client.list_networks()['networks']:
if net['name'].ends... | bbb96a3da0967e74d9229537ca8afbcbfbd786e8 | 41,681 |
def binary_search(target,bounds,fn,eps=1e-2):
""" Perform binary search to find the input corresponding to the target output
of a given monotonic function fn up to the eps precision. Requires initial bounds
(lower,upper) on the values of x."""
lb,ub = bounds
i = 0
while ub-lb>eps:
... | be5416bd6cdd53ff5fd8f58c489d7cf036dcd6a6 | 41,687 |
from typing import List
def format_learning_rates(learning_rates: List[float]) -> str:
"""
Converts a list of learning rates to a human readable string. Multiple entries are separated by semicolon.
:param learning_rates: An iterable of learning rate values.
:return: An empty string if the argument is ... | 06c7395ba609be49ae57db618fe0e739b247de66 | 41,691 |
def add_buffer_to_intervals(ranges, n_channels, pad_channels=5):
"""Extend interval range on both sides by a number of channels.
Parameters
----------
ranges : list
List of intervals [(low, upp), ...].
n_channels : int
Number of spectral channels.
pad_channels : int
Numb... | 44548e70f0cbdc8d1f3df59ba7402ebc6aae0f41 | 41,692 |
def has_required_vowels(text, no_of_vowels=3):
"""Check if there are the required number of vowels"""
# Set up vowels and vowel count
vowels = 'aeiou'
vowel_count = 0
# count vowels in text until it reaches no_of_vowels,
# at which point, return True, or return False otherwise
for characte... | 395958ac12f6015bec2d6122670d485d41b2d1b8 | 41,695 |
def image_prepare(image):
"""Clip negative values to 0 to reduce noise and use 0 to 255 integers."""
image[image < 0] = 0
image *= 255 / image.sum()
return image.astype(int) | c244a9a9e613215796b1a72b4576e0e39885d65e | 41,701 |
def parse_value(value):
"""
Tries to convert `value` to a float/int/str, otherwise returns as is.
"""
for convert in (int, float, str):
try:
value = convert(value)
except ValueError:
continue
else:
break
return value | 7bab352a5bbcfe0eb9de19f7252d9d759950b01e | 41,702 |
def flatten(xs):
"""Flatten a 2D list"""
return [x for y in xs for x in y] | 5b3fc103f699cbb0ef56f0457f482f35d0c3e4af | 41,707 |
def caption_fmt(caption):
""" Format a caption """
if caption:
return "\n== {} ==\n".format(caption)
return "" | e6e94efa5f16f9b0590e912e68ee1e3acfb4d54a | 41,712 |
def rgbi2rgbf(rgbf):
"""Converts a RGB/integer color into a RGB/float.
"""
return (int(rgbf[0]*255.0), int(rgbf[1]*255.0), int(rgbf[2]*255.0)) | eca27cee4f43653f42b96c84c72a5332927e1dc0 | 41,713 |
def node_count(shape):
"""Total number of nodes.
The total number of nodes in a structured grid with dimensions given
by the tuple, *shape*. Where *shape* is the number of node rows and
node columns.
>>> from landlab.utils.structured_grid import node_count
>>> node_count((3, 4))
12
"""... | f3f460967346afbb25098db6ebb7ea8db45e2870 | 41,715 |
def Madd(M1, M2):
"""Matrix addition (elementwise)"""
return [[a+b for a, b in zip(c, d)] for c, d in zip(M1, M2)] | 0e01c5be64f7c7b7c0487080ef08c560bacd6fc1 | 41,717 |
def bubble_sort(li):
""" [list of int] => [list of int]
Bubble sort: starts at the beginning of the data set.
It compares the first two elements, and if the first is
greater than the second, it swaps them. It continues doing
this for each pair of adjacent elements to the end of the
data set. It ... | d2730adae8e2ddec4943d5e9a39e2a5e34eaaaaa | 41,721 |
def get_bgp_attrs(g, node):
"""Return a dict of all BGP related attrs given to a node"""
if 'bgp' not in g.node[node]:
g.node[node]['bgp'] = {'asnum': None, 'neighbors': {}, 'announces': {}}
return g.node[node]['bgp'] | 9345cb12b263a2aec48f000e84b5b115a158c62f | 41,722 |
def GenerateAndroidResourceStringsXml(names_to_utf8_text, namespaces=None):
"""Generate an XML text corresponding to an Android resource strings map.
Args:
names_to_text: A dictionary mapping resource names to localized
text (encoded as UTF-8).
namespaces: A map of namespace prefix to URL.
Returns:... | 3561769bff337d71a3ee02acd39f30746e89baf9 | 41,728 |
def similar_lists(list1, list2, eps=1e-3):
"""Checks elementwise whether difference between two elements is at most some number"""
return all(map(lambda pair: abs(pair[0]-pair[1])<eps, zip(list1, list2))) | 09f8d5eea57eb19e3c64ce6f76603ab13a7e37ac | 41,730 |
def normalized_difference(x, y):
"""
Normalized difference helper function for computing an index such
as NDVI.
Example
-------
>>> import descarteslabs.workflows as wf
>>> col = wf.ImageCollection.from_id("landsat:LC08:01:RT:TOAR",
... start_datetime="2017-01-01",
... end_d... | bfb74cbdae173d31811533f42f88e5165489f5ae | 41,733 |
def _jd2mjd( jd ):
"""
The `_jd2mjd` function converts the Julian date (serial day number)into a
Modified Julian date (serial day number).
Returns a float.
"""
return jd - 2400000.5 | 01f4db238d092ab235374c5ab64517754ef075de | 41,736 |
def tokenTextToDict(text):
"""
Prepares input text for use in latent semantic analysis by shifting it from
a list to a dictionary data structure
Parameters
----------
text : list of strings
A list of strings where each string is a word and the list is a document
Returns
-------
... | c712eaa06d540486792d59d45f0b489ddb12df56 | 41,738 |
def search(array, value, dir="-"):
"""
Searches a sorted (ascending) array for a value, or if value is not found,
will attempt to find closest value.
Specifying dir="-" finds index of greatest value in array less than
or equal to the given value.
Specifying dir="+" means find index of least va... | 9284ed8f826f3a472d9149531b29f12a8875870c | 41,739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.