content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def statistics(*args):
"""
Compute the average, minimum and maximum of a list of numbers.
Input: a variable no of arguments (numbers).
Output: tuple (average, min, max).
"""
# this function takes variable argument lists
avg = 0; n = 0 # avg and n are local variables
for term in args:
... | d737c9265456df32f91d982c8cd92d12bf865442 | 661,962 |
def get_invalid_keys(validation_warnings):
"""Get the invalid keys from a validation warnings list.
Args:
validation_warnings (list): A list of two-tuples where the first
item is an iterable of string args keys affected and the second
item is a string error message.
Returns... | 0eb0db053e505f696471e7166051d9b2e025d439 | 661,963 |
def _islinetype(line, testchar):
"""Checks for various kinds of line types based on line head"""
return line.strip().startswith(testchar) | 6b756278299fbac2955b527d7564f30a0085f9e4 | 661,964 |
from unittest.mock import call
def is_master() -> bool:
"""Return if current branch is master."""
branch_name = call("git rev-parse --abbrev-ref HEAD").replace("\n", "")
return branch_name == "master" | 89dd8ab05bad22f770abd4589304df961dce958e | 661,965 |
import math
def fscy(scale=100):
"""
Escalado del alto del texto.
"""
return '\\fscy{:d}'.format(int(math.ceil(scale))) | 893416caa650f1579a9dc28b3aec4baa5121605e | 661,966 |
def development_extract_parameter_check_for_isobarics(
df, df_isobarics
):
"""
Check for isobarics.
Check mass transitions for isobarics and rank fragments.
Parameters
----------
df : dataframe
Dataframe to check for isobarics.
df_isobarics : dataframe
Dataframe... | 7b690c2b187973c59d14f210b2c0d37c9b627be2 | 661,967 |
import random
import string
def generate_random_string(length=7):
"""Generates random string"""
return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length)) | 35939d445cde1fa0cc3f3194eedd21e6a39b19e2 | 661,968 |
def RPCFunction(func):
"""Decorator used in `Plugin` to expose a function to Goofy server."""
func.__rpc_function__ = True
return func | 3c30f5ee83a0e2b543ce7290851c498f00c35d23 | 661,969 |
def filter_words(words, filters):
""" Filter words from a list of filters """
filters = set(filters)
return [w for w in words if w.lower() not in filters] | b9b9ae78ecf6ed45921e20018de8b0ce0d4bcfaa | 661,970 |
def get_max(arr: list) -> int:
"""Returns the maximum value in an list
Args:
arr (list): the list to find the value in
Returns:
int: the value itself
"""
max_value = arr[0]
for value in arr:
if value > max_value:
max_value = value
return max_value | ddd007e509f79bcdd155906220413dec9d81dd21 | 661,971 |
def hyps2word(hyps):
"""
Converts a list of hyphens to a string.
:param hyps: a list of strings (hyphens)
:return: string of concatenated hyphens
"""
return ''.join(hyps) | 28d007d70a66ac2efa212f4a58811f039e9a5fdf | 661,972 |
def validate_trait_python(trait, obj, name, value):
"""Calls a Python-based trait validator"""
return trait.c_attrs.py_validate(obj, name, value) | 6ec2298b8fb2f19d68d46ba3b853e51eabb98b24 | 661,973 |
import re
def get_shorttext(text):
"""Get the initial 200 characters of text. Remove HTML and line breaks."""
shorttext = re.sub(r"<.*?>|\n|\t", " ", text)
shorttext = shorttext.strip()
shorttext = re.sub(r" ", " ", shorttext)
return shorttext[:200] | 7b2534c463b9cabba8539e96527bbb14f3e4ec56 | 661,974 |
def fullname(obj):
"""Returns full name of object"""
if hasattr(obj, '__module__'):
module = obj.__module__
else:
module = obj.__class__.__module__
if hasattr(obj, '__name__'):
name = obj.__name__
else:
name = obj.__class__.__name__
if module is None or module == ... | c2118763f29abb45494e0837dd946d809f97a7f1 | 661,976 |
def get_factors(n):
"""Return a list of the factors of a number n.
Does not include 1 or the number n in list of factors because they're used for
division questions.
"""
factors = []
for i in range(2, n):
if n % i == 0:
factors.append(i)
return factors | 7fe54e47f17a898164806d8109f1d803451ba9d6 | 661,979 |
from typing import Container
def generate_primes_v2(n: int) -> Container[int]:
"""Computes and returns all the primes up to 'n'.
Args:
n: The integer upto which all primes to be computed.
Returns:
All the primes upto 'n'.
"""
if n < 2:
return []
size = (n - 3) // 2 +... | 66abf28d02a72cc8b7ad5836d99cddd1c7a8c767 | 661,981 |
from typing import List
def sequence (lower:int, upper:int) -> List[int]:
"""
generate an integer sequence between two numbers.
"""
seq = [ ]
current = lower
while current <= upper:
seq.append(current)
current += 1
return seq | 6a54c3b1234f108abd0a95fbbf0ab7fcb3d3f7f4 | 661,982 |
def fitfunc(f):
"""
A decorator that can be used to say if something is a fitfunc.
"""
f.fitfuncwraps = True
return f | 18c549291866166b249855cb31d33dfac6857df1 | 661,983 |
from typing import Protocol
def test_structural_subtyping() -> None:
"""Structural subtyping."""
class SupportsOn(Protocol):
"""A protocol for anything that can be turned on."""
def turn_on(self) -> str:
...
class Engine:
"""Engine that can be turned on - a structura... | beb0b907929761ea5146d04780ee38c48d5790b0 | 661,984 |
import subprocess
def run_service(service, out_port, in_port):
"""
:param service: The name of the service
:param out_port: The exposed (published) port (accessible from host)
:param in_port: The local port where the application is running on
:return:
"""
comm = "docker-compose run -d -e p... | b2640f5694c762bedd94ed8077ab4fa8f39eb2ac | 661,985 |
from redis.client import Redis
def from_url(url, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
return Redis.from_url(url, **kwargs) | c540436213b31fedc653596146667068430aac03 | 661,986 |
import json
def parse_image_json(text):
"""
parses response output of AWS describe commands and returns the first (and only) item in array
:param text: describe output
:return: image json
"""
image_details = json.loads(text)
if image_details.get('Images') is not None:
try:
... | 8e576b0a153be00fc35ae87bec05298c14981a01 | 661,987 |
def build_matrix(similarity_matrix, topic_bias, dampening):
"""
Given a sentence similarity matrix, a topic bias vector and a dampening factor produce a unified matrix representation.
ARGS: similarity_matrix(2d matrix), topic_bias(1d vector), dampening(float)
Returns: unified matrix(1d)
"""
retu... | 9fef6ceaad40f01a9f89bf8331924eb56002a6ef | 661,988 |
def in_order(prev, current):
"""
Return True if the ordering is correct for these two lines ('prev' should be before 'current').
Codeowners should be ordered alphabetically, except that order is also significant for the codeowners
syntax (the last matching line has priority).
This means that wildc... | fe344b4e1bf74a35f12e7ab246d256e521b1f359 | 661,989 |
def truncate_comics(comics):
"""Truncate the list of comics based on (hardcoded) criterias.
On the long run, I'd like the criteria to be provided via command-line
arguments."""
limit = 3000
len_comics = len(comics)
if len_comics > limit:
print("Keeping %d comics out of %d" % (limit, len... | 5e092361780e6041eb484f426d5b492de0957a1e | 661,990 |
from collections import defaultdict
def edges_equal(edges1, edges2, need_data=True):
"""Check if edges are equal.
Equality here means equal as Python objects.
Edge data must match if included.
The order of the edges is not relevant.
Parameters
----------
edges1, edges2 : iterables of wit... | 5be7f531fceecf37a917d794f56aa417b8636281 | 661,991 |
def count_cuts(adj,vert_part):
"""
adj is an iterable object containing an adjacency matrix for a logically graph-like object
vert_part is a listing of which partition each graph vertex is in.
returns cut - integer with the number of edges that cross partitions
"""
edge_cuts = set()
... | 210229feee894f7f682543ab10ea96760627d6a2 | 661,993 |
import base64
import uuid
import re
def generate_download_link(file, filename):
"""
Generates a download link for the given string; filename is what the output filename will be.
This is made ad Streamlit does not support a download button natively.
An adaption of https://discuss.streamlit.io/t/a-downl... | 163efd7e59ea626c7adf9028ae86f5b33594aec5 | 661,994 |
import shlex
def read_desc(fname):
"""The function reads the descriptives output file and returns a dictionary that
contains the relevant parameters for test6 in test_integration.py.
"""
dict_ = {}
with open(fname, "r") as handle:
for i, line in enumerate(handle):
list_ = shlex... | 33260cd8025542fde6dd186382bbd8db361316c2 | 661,995 |
from typing import Dict
from typing import Any
from typing import List
def set_user_defined_results(
fha: Dict[str, Any], results: List[float]
) -> Dict[str, Any]:
"""Set the user-defined results for the user-defined calculations.
This allows the use of the results fields to be manually set to float
... | ca886e2221c0c5b0fcc8c3f00bbeff07182af6e4 | 661,996 |
import os
def get_path_files(path, keywords):
"""
Return sorted list of files from given path and keywords
Parameters
----------
path : str
Path
keywords : list
List of keywords
Examples
--------
>>> get_path_files("test_base_folder", ["py"])
['test1.py', 'tes... | e1167cc52265f620111459a9ad1c59b5d7b08d65 | 661,997 |
def check_nonprocess(cfg, log):
"""Function: check_nonprocess
Description: This is a function stub for mail_2_rmq.check_nonprocess.
Arguments:
(input) cfg
(input) log
"""
status = True
if cfg and log:
status = True
return status | 10a02898f385fd3de565b23bece758070944199f | 661,998 |
def cria_copia_posicao(pos):
"""
cria_copia_posicao: posicao -> posicao
Recebe uma posicao e devolve uma copia nova da posicao.
"""
return {'c': pos['c'], 'l': pos['l']} | d5178ceac5dda46c565fc974513578f283dd6bcb | 662,001 |
def reg8_delta(a, b):
"""Determine 8-bit difference, allowing wrap-around"""
delta = b - a if b > a else 256 + b - a
return delta - 256 if delta > 127 else delta | eb0554e38e05ad37214c58242a41a910685da7be | 662,002 |
def group_list(actions, agent_states, env_lens):
"""
Unflat the list of items by lens
:param items: list of items
:param lens: list of integers
:return: list of list of items grouped by lengths
"""
grouped_actions = []
grouped_agent_states = []
cur_ofs = 0
for g_len in env_lens:
... | bc6199f5cc0efcdfde7e9c9085c1ccc95c535e30 | 662,003 |
def find_settings(element, alternate_name):
"""Given an ElementTree.Element and a string, searches the element for
a subelement called "settings". If it doesn't find it, searches for
a subelement using the alternate_name.
Prior to Vespa 0.7.0, the settings in Analysis blocks had unique class
and ... | 9fae380cd64b64380d0770a20dd26aef5cd5cade | 662,004 |
from typing import List
from pathlib import Path
import torch
def average_checkpoints(filenames: List[Path]) -> dict:
"""Average a list of checkpoints.
Args:
filenames:
Filenames of the checkpoints to be averaged. We assume all
checkpoints are saved by :func:`save_checkpoint`.
Retur... | d6a534dfa62d7d0d1dfab1d58f5261080e889bb9 | 662,005 |
def docs_append_to_section(docstring, section, add):
"""Append extra information to a specified section of a docstring.
Parameters
----------
docstring : str
Docstring to update.
section : str
Name of the section within the docstring to add to.
add : str
Text to append t... | c4c58d809aaeff2a9f68c193894dae155fa7a9dd | 662,006 |
def denpify(f):
"""
Transforms a function over a tuple into a function over arguments.
Suppose that
`g` = ``denpify(f)``,
then
`g(a_1, a_2, ..., a_n) = f((a_1, a_2, ..., a_n))`.
Examples
--------
>>> flip((0, 1))
(1, 0)
>>> f = denpify(flip)
>>> f(0, 1) # note the the... | 57ee3aa381352eab2823da0a30e6252d0377bdfe | 662,007 |
import zipfile
def unzip_file(filename="10_food_classes_10_percent.zip"):
"""
Unzips a file with a defined full-path filename.
:param filename: A filename with absolute path
:return:
"""
try:
zip_ref = zipfile.ZipFile(filename)
zip_ref.extractall()
zip_ref.close()
e... | 069a804c326137d2f394a71b2b118ef3af4be3bb | 662,008 |
def default_config():
"""
Returns a dict with the default configuration
"""
return {
'stack_name': 'Lambda-Chat',
'tags': {
'Name': 'Lambda Chat',
'Creator': 'CloudNative'
}
} | 2a78520bbee0c3f801085a4da8e5d13d872cd5de | 662,009 |
import sys
def get_test_requirements():
"""
Returns a list of required packages to run the test suite.
"""
tests_require = []
if sys.version_info < (2, 7):
tests_require.extend(['unittest2'])
return tests_require | 9bfa4f5a0b4f08afcb7cf9dfc3d9252968da927d | 662,010 |
import math
def prob_no_match(n):
"""analytical result using integers - python can handle arb large numbers"""
return math.factorial(n)*math.comb(365,n)/(365**n) | fe292657654c4413fd3d9751e6a10be7c38f2c19 | 662,011 |
def standardize(obj):
"""
Take any Deezer obj and return a standard object (e.g. artist or author keys are renammed as creator)
"""
if 'picture_medium' in obj.keys():
obj['image'] = obj.pop('picture_medium')
if 'cover_medium' in obj.keys():
obj['image'] = obj.pop('cover_medium')
return obj | 81b69ba7ee7a77efd65078ded0dc7edf7f9773ba | 662,012 |
import argparse
import pathlib
def _get_cli_arg_parser() -> argparse.ArgumentParser:
"""Return a CLI argument parser."""
parser = argparse.ArgumentParser(description="Clean the raw data.")
parser.add_argument(
"input_directory",
help="Directory containing the raw data to be processed.",
... | a3f34295101b18853d0dede767b5f6e339eb3be4 | 662,013 |
def get_option(options=None, local_tag=None, doc=None, doc_tag=None, default=None, error_on_none=True):
"""
Fetch an option variable from either a local (element) level option/attribute tag,
a document level metadata tag, or a default.
:type options: ``dict``
:type local_tag: ``str``
:type d... | 56b0fe0face88b8c7a5c314d98559bb756c47e25 | 662,015 |
from typing import Union
def format_duration_us(t_us: Union[int, float]) -> str:
"""Formats the given microsecond duration as a string."""
t_us = int(t_us)
t_ms = t_us / 1000
t_s = t_ms / 1000
t_m = t_s / 60
t_h = t_m / 60
t_d = t_h / 24
if t_d >= 1:
rem_h = t_h % 24
... | d439854496aed9db26cf95f301cf03871d84daa0 | 662,016 |
import base64
def encode_connection_string(conn_string):
"""Encodes a MongoDB connnection URI as a hexadecimal authentication string"""
b = bytes(conn_string.encode('utf-8'))
return base64.urlsafe_b64encode(b).decode('utf-8') | 65b7f1d90a568628ed0d960d1c5d48eddf1a97ad | 662,017 |
import re
def fuzzy_match_repo_url(one, other):
"""Compares two repository URLs, ignoring protocol and optional trailing '.git'."""
oneresult = re.match(r'.*://(?P<oneresult>.*?)(\.git)*$', one)
otherresult = re.match(r'.*://(?P<otherresult>.*?)(\.git)*$', other)
if oneresult and otherresult:
... | 6346c411f0e20ad6a11723d531ce49014b0dfa62 | 662,019 |
import torch
def backproject_flow3d(flow2d, depth0, depth1, intrinsics):
""" compute 3D flow from 2D flow + depth change """
ht, wd = flow2d.shape[0:2]
fx, fy, cx, cy = \
intrinsics[None].unbind(dim=-1)
y0, x0 = torch.meshgrid(
torch.arange(ht).to(depth0.device).float(),
... | e615ca2b0a797748148a46fce8a9b2fdb27578a5 | 662,021 |
def get_file_extension(url):
"""Return file extension"""
file_extension = ''.join(('.', url.split('.')[-1:][0]))
return file_extension | cad58d95e2aee0bc5103ae331d080d01497c64fe | 662,022 |
import os
def convert_file_path(config, file_path, inverse=False):
"""Convert given file path to internal directory structure."""
basename = os.path.basename(file_path)
if inverse:
new_dir = config["exposed_base_dir"]
else:
new_dir = config["geoserver_target_dir"]
path = os.path.j... | 6ef8d523d5e14a3e25fc0fce6bf40445453e17ed | 662,023 |
def _concat_nbrs_output_shape(input_shapes):
"""
Needed since the inference of output shape fail in Keras for non-float
tensors.
https://github.com/keras-team/keras/issues/8437
"""
B = input_shapes[0][0]
N = input_shapes[0][1]
M = input_shapes[2][-1]
atom_fea_len = input_shapes[0][-1... | c8de713f91ec6a169d8a15398e49c5bb48d72406 | 662,024 |
def task_default():
"""Inform user to specify a concrete task"""
return {
'actions': [
['echo', 'Specify a concrete task. Run `doit list` for a task list.']
],
'verbosity': 2,
} | 3d4cb560b8a09b3cae3cae1422c8c4a2bd6bff3b | 662,026 |
import sys
def detect_platform():
"""
Detects if we are on osx, linux or win
"""
if sys.platform in ['linux', 'linux2']:
return 'linux'
elif sys.platform in ['darwin']:
return 'osx'
elif sys.platform in ['win32']:
return 'win'
raise Exception("Error: Unknown pl... | 208ba1a9a05ce1cc0332b8e989076d6fb84ebe5b | 662,027 |
def get_min_max_credits(day_count, max_credits_month):
"""
get the max and min credits with total avg
:param day_count: days of the month
:param max_credits_month: the maximum credits
:return: max_credits and min credits
"""
avg_credit = max_credits_month / day_count
max_credits = (3*avg... | b1ec030b378625b43fe0749e7111c4608b1c80ce | 662,028 |
def figure_defaults():
"""Generates default DAVID query arguments.
:param database: A string for the database to query, e.g. 'WORMBASE_GENE_ID'
:param categories: A comma separated string with databases
:param user: A user ID registered at DAVID for querying
:param ids: A list with identifiers
... | d87263d79f859616622df55801373c51575968b9 | 662,029 |
import numpy
def cca(H1, H2, outdim):
"""
An implementation of linear CCA
# Arguments:
H1 and H2: the matrices containing the data for view 1 and view 2. Each row is a sample.
outdim_size: specifies the number of new features
# Returns
A and B: the linea... | 970c9d77ad23224e733a624c7c03a3a8a82be46e | 662,030 |
import traceback
def process_error(err):
"""Take the given error raise by ProbLog and produce a meaningful error message."""
err_type = type(err).__name__
if err_type == "ParseException":
return (
400,
"text/plain",
"Parsing error on %s:%s: %s.\n%s"
... | 4014bd71edef65eef2c39faef8ea31b736f23a9e | 662,031 |
def query_orgs(paper_orgs, variable, name):
"""Returns ids for papers with a value in a variable"""
_ids = paper_orgs.loc[paper_orgs[variable] == name]["article_id"]
return set(_ids) | ed7b18b33d950e89a46b5bbd0545b0f0d2a8fbcf | 662,032 |
def create_stock_table(table: str) -> str:
"""
create_stock_table is used to create a table
:param table: table name to be created
:return:
"""
return f"""
CREATE TABLE {table}(
date_symbol VARCHAR (50) NOT NULL ,
id SERIAL,
date DATE NOT NULL,
symbol VARCHA... | d97c2a23c324ca7e9a81f693a36b028d11b874ca | 662,033 |
def find_subclasses(cls):
""" Finds subclasses of the given class"""
classes = []
for subclass in cls.__subclasses__():
classes.append(subclass)
classes.extend(find_subclasses(subclass))
return classes | 4464ed7024c592c860e624d2d9f1df9bda590a98 | 662,034 |
def comment_out_details(source):
"""
Given the source of a cell, comment out any lines that contain <details>
"""
filtered=[]
for line in source.splitlines():
if "details>" in line:
filtered.append('<!-- UNCOMMENT DETAILS AFTER RENDERING ' + line + ' END OF LINE TO UNCOMMENT -->... | 95e34cfae18fb66de33c22eed5419dfe51b2e52a | 662,035 |
def is_valid_v4addr(addr):
"""check is ipv4 addr is valid"""
if not addr:
return False
if addr.find('.') != -1:
addr_list = addr.split('.')
if len(addr_list) != 4:
return False
for each_num in addr_list:
if not each_num.isdigit():
ret... | cc30d51e305b669e801b71e5929b3bb851f96e99 | 662,036 |
from typing import List
def _deindent(text: str) -> List[str]:
"""
Remove text indentation from the given text string.
Args:
text: The text to be processed.
Returns:
The list of unindented text.
"""
lines, indent = text.split('\n'), -1
for i, line in enumerate(lines):
if len(line) == 0 or... | eeb3fe47c75b3e66a1b8f882dc845f79f156d524 | 662,037 |
def algo_output(algo_counter):
"""
This function is used to determine the appropriate output for the algorithm.
It takes in the algo_counter number as an argument (determined by calculations in the script),
And it spits out the recommended action and reason.
@param: algo_counter is ... | 807cae1d80a17499dbc52db8e957803a407f7418 | 662,038 |
def edit_header(my_vcf):
"""
Add INFO for new field to vcf
"""
header = my_vcf.header.copy()
header.add_line(('##INFO=<ID=GTCNT,Number=.,Type=Integer,'
'Description="Counts of genotypes for the allele (UNK, REF, HET, HOM)">'))
return header | bd36bc24ddbd0587cb202fdab142d0a594785fb9 | 662,039 |
def create_anc_lineage_from_id2par(id2par_id, ott_id):
"""Returns a list from [ott_id, ott_id's par, ..., root ott_id]"""
curr = ott_id
n = id2par_id.get(curr)
if n is None:
raise KeyError('The OTT ID {} was not found'.format(ott_id))
lineage = [curr]
while n is not None:
lineage... | bee459efd3c1ebb639aeee1433bfdde63c60fad7 | 662,040 |
def check_country_is_valid(country):
"""Given the country full name or two-letter code; check if it's a valid
country by searching the countries.txt file for a match.
@param Country full name or country two-letter code.
@return True if country is valid False otherwise.
"""
l = []
fhandler ... | be1841a75f69250d4a99ef93da4e8cc26f9c7ef9 | 662,041 |
import logging
def _get_stream_handler() -> logging.StreamHandler:
"""
Define parameters of logging in the console.
Returns:
logging.StreamHandler: console handler of the logger.
"""
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setF... | 4b46e55b24399750f4063c19dfd268891eb08641 | 662,042 |
async def full_fledged_handler(request, *args):
"""
Test of everything
in heres
"""
return "" | ce37e0be27a9bceca25eb09af838d27de8145725 | 662,043 |
import torch
def merge_list_feat(list_feat, list_batch_cnt):
"""
Merge a list of feat into a single feat
Args:
list_feat (list): each element is (N, C)
list_batch_cnt (list): each element is (B) - [N0, N1, ...]; sum(Ni) == N
Returns:
merge_feat (torch.Tensor): (M, C)
... | 2bd13e05655f0473430cb185bf11bb52840eb9fa | 662,044 |
def format_error(ex):
"""Creates a human-readable error message for the given raised error."""
msg = 'Error occurred in the Google Cloud Storage Integration'
if hasattr(ex, '__class__'):
class_name = ex.__class__.__name__
details = str(ex)
if isinstance(ex, BaseException) and detail... | cd15cfea87065f288970a4f3710a004b8642ec44 | 662,046 |
def crop_left_third(img):
"""Don't forget to modify extend!!! Returns a ref (not a copy) of the cropped area."""
dst_width = img.shape[1] // 3
cropped = img[:, 0:dst_width]
return cropped | 05d5dfe6d2c27484459734339edfbeffcf0b6337 | 662,047 |
def py_slice2(obj,a,b):
"""
>>> [1,2,3][1:2]
[2]
>>> py_slice2([1,2,3], 1, 2)
[2]
>>> [1,2,3][None:2]
[1, 2]
>>> py_slice2([1,2,3], None, 2)
[1, 2]
>>> [1,2,3][None:None]
[1, 2, 3]
>>> py_slice2([1,2,3], None, None)
[1, 2, 3]
"""
return obj[a:b] | 454315e7f22936547cfffb5b4529358518ca292f | 662,048 |
def solution(A):
"""
DINAKAR
Idea is minimum average can be either 2 or 3 element ie. if you want to choose 4 then that again can be divided in
to 2,2 groups, same for 6 can be divided in 3,3 group
We calculate prefix sum to find average easily for given start and end position
We do average eith... | 25d17fbd370822afa5ef2f4165f03160d5689da3 | 662,049 |
def sol(arr, n, t):
"""
Create a hash of the elements check if the diff+element exists in the
hash
"""
h = {}
for x in arr:
h[x] = True
for x in arr:
if t+x in h:
return 1
return -1 | d4072ef2f99d6e95847f94fe9a7433dad04a2f74 | 662,052 |
from typing import List
def remove_ad_search_refs(response: List[dict]) -> List[dict]:
""" Many LDAP queries in Active Directory will include a number of generic search references
to say 'maybe go look here for completeness'. This is especially common in setups where
there's trusted domains or other domai... | 8b0bf322834e9fdbc8cf552def155f33b6da63bd | 662,053 |
import re
def sanitise_float(value):
"""
Clean text input for the lat and lon values
Make sure that we return a float value.
Some cases the extracted value is of the form: -90.0f; // float
:param value:
:return:
"""
try:
return float(value)
except ValueError:
# Cl... | d872de9bc19e31d434cb12680c50c019135b339a | 662,054 |
def get_non_text_messages_grouped(groups):
"""Filters and structures messages for each group and non-text message type.
Args:
groups (list of lists of MyMessage objects): Messages grouped.
Returns:
A list of message types grouped:
[
{
"groups": [list of ... | 7ae67a38a3a5d3541ac0a443e69e21377b8e8fc0 | 662,055 |
def tn(n):
"""
This function calculates, for a given integer n, the result of the operation
n*(n+1)/2
"""
return n*(n+1)/2 | 35f9ce390c35a8528480def38f2d9dff06c6973a | 662,056 |
import os
def find_exec(executable):
"""
Search executable in PATH environment. Return path if found, None if not.
"""
path = os.environ.get("PATH")
if not path:
return
for p in path.split(os.path.pathsep):
p = os.path.join(p, executable)
if os.path.exists(p):
... | 98bd5bdc82d69b1b6722541a78c6593c1a1d12e0 | 662,058 |
def extract_content(soup):
"""Extract resources based on resource tags from a page."""
images = [ image.get('src') for image in soup.find_all('img') ]
stylesheets = [ sheet.get('href') for sheet in soup.find_all('link') ]
scripts = [ script.get('src') for script in soup.find_all('script') ]
videos =... | db2b12d33015c81b9abba1dd9ab0c34c46a94229 | 662,059 |
import warnings
def index_condensed_matrix(n, i, j):
"""
Return the index of an element in a condensed n-by-n square matrix
by the row index i and column index j of the square form.
Arguments
---------
n: int
Size of the squareform.
i: int
Row index of the... | eb51b6b4739de8c7058136e2a0f527629ff641f0 | 662,060 |
def to_repo(gh, owner, name):
"""Construct a Repo from a logged in Github object an owner and a repo name"""
return gh.get_user(owner).get_repo(name) | 7511afd4a2c67bcc5cea023f5d83acc939a78d44 | 662,061 |
def bubble_sort(a: list):
"""
Bubble sorting a list. Big-O: n^2 (average/worst) time; 1 on space.
"""
siz = len(a)
for i in range(siz):
swapped = False
top = siz - i - 1
for j in range(top):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
... | ce4ee8c937d3dde7708efd96abd5965a36da08dd | 662,063 |
def list2pyrata (**kwargs):
"""
turn a list into a list of dict
e.g. a list of words into a list of dict
with a feature to represent the surface form of the word
if parameter name is given then the dict feature name will be the one set ;
if parameter dictList is given then the list of dict will be exte... | f7172b86305ef9bb003f0bdc9f09f3c489cb7c1d | 662,064 |
import functools
def handle_wind_query_exception(logger):
"""
:param logger: logging, a logging object
:return: decorator, wraps exception loggers
"""
def decorator(query_func):
@functools.wraps(query_func)
def wrapper(*args, **kwargs):
try:
return quer... | de74b6d2bf3507a3274ee14c11893493529dcb95 | 662,065 |
import re
def slugify(text, delim='_', lowercase=True):
""" simple slugify of text """
text = str(text).strip()
_punct_re = re.compile(r'[\s!"#$%&\'()*\-/<=>?@\[\\\]^_`{|},\.;:]+')
"""Generates an slightly worse ASCII-only slug."""
result = []
if lowercase:
text = text.lower()
fo... | c84e5ada4b9e1f64e9f010ee7130403b3bb9fe31 | 662,066 |
def parse_smi(files):
"""
Return parsed files as list of dicts.
.. note:
parse_smi uses the x and y coordinate of the left eye.
Parameters
----------
files : sequence of str
file names. For every subject one tab separated file.
Returns
-------
subjects : sequence o... | d1a24467dc9c29f3b72159e06a5e5b6a138ff091 | 662,067 |
def load_data(filename):
"""加载数据
单条格式:(query, title, label)
"""
D = []
with open(filename, encoding='utf-8') as f:
for l in f:
data_list = l.strip().split('\t')
if not len(data_list) == 3:
continue
query = data_list[0]
title = data_list[1]
label = data_list[2]
D.append((query, title, int(la... | 44888c501cf5eb8b70acdfc43b852b9425bc808d | 662,068 |
from datetime import datetime
def days_from_date(strdate):
""" Returns the number of days between strdate and today. Add one to date
as date caclulate is relative to time
"""
currentdate = datetime.today()
futuredate = datetime.strptime(strdate, '%Y-%m-%d')
delta = futuredate - currentdate
... | 5aacdc8b0c5e3750bd635105364c500609a5e0b9 | 662,069 |
import torch
def log_sum_exp(vec, m_size):
"""
calculate log of exp sum
args:
vec (batch_size, vanishing_dim, hidden_dim) : input tensor
m_size : hidden_dim
return:
batch_size, hidden_dim
"""
_, idx = torch.max(vec, 1) # B * 1 * M
max_score = torch.gather(vec, 1, ... | 362b794355e0bdf7760776ad0c4ed807c677a650 | 662,070 |
def litres(time) -> int:
"""
Because Nathan knows it is important to stay hydrated,
he drinks 0.5 litres of water per hour of cycling.
You get given the time in hours and you need to return
the number of litres Nathan will drink, rounded
to the smallest value.
:param time:
:return:
... | 299843b49a1eb9a11df6fb4ed7e566189d4e9988 | 662,071 |
def restrict_text( content, section ):
"""
Disable Text sections
This tool filter will disable all Tools groups under a 'Text' section when enabled.
"""
if section.name.find('Text') != -1:
return False
return True | 4087b558308342186cc0cd2e695f9903b48f1a03 | 662,072 |
def maketrans(frm, to): # real signature unknown; restored from __doc__
"""
maketrans(frm, to) -> string
Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length.
"""
return "" | c2e4a59f0f7a9eec6727db87677034ba9f195507 | 662,073 |
def next_zero(signal, x0, steps=1000, precision=10e-6, gamma=0.01):
"""
Finds a position of zero of a signal using Newton's method
Args:
signal (SignalExp): bandlimited function which will be searched for a zero
x0 (float): starting point for the search
steps (int): maximal possible... | 2f4366d13bd22527cdd018c992eeaea40aa9f6d2 | 662,075 |
import typing
import aiohttp
async def get_categories() -> typing.List[typing.Dict[str, typing.Any]]:
"""
Get all the categories and their IDs.
Used to get categories without a game or session object.
"""
url = "https://opentdb.com/api_category.php"
async with aiohttp.request("GET", url) as r... | 0cbb6914c9bf3fd8063ffe04ab85d3e6b05b31c9 | 662,076 |
import os
def upload_uuid_filename(instance, filename):
"""Upload filename with convention name
Convention is to use name of class plus uuid of object, width and
height. UUID is used to fix a privacy issue with private objects.
"""
__, filename_ext = os.path.splitext(filename)
parent = getat... | c9fe11f445d5974fa870960c79fd206655b58fa5 | 662,077 |
def getStr(target, pos):
"""
Get a string from a list/whatever.
Returns the string if in-range, False if out of range.
"""
try:
result=str(target[pos])
return result
except IndexError:
return False | 8169228926a3b15177e71e478545cee81915130d | 662,078 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.