content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def get_res_entry(line, dir):
"""Return an A2X resource file/directory found in a resource spec.
See the a2x man page for details on the format.
"""
line = line.split('=')
res = line[0]
# resource files are also searched relatively to the source directory, so if
# a resource sp... | 1723bd7a03367c7613d2010002649080065ec116 | 675,000 |
def get_required_inputs(algorithm):
"""
Get the input files requires to run this algorithm
@param algorithm: algorithm name
@return: A list of strings of input files types
"""
try:
algorithm_runner = globals()[algorithm.lower()]
except KeyError:
raise NotImplementedError(f'{a... | d3dc809b85e7e04716dc7068b6095fd0ba542a4b | 675,002 |
def link_is_valid(link_info, query_words, mode="all"):
"""
Tests if a link is valid to keep in search results, for a given query
:param link_info: a dict with keys "url" and "text"
:param query_words: a list of query words
:param mode: can be "all" (default), or "any"
:return: True or False
... | 78e98ea157a9d4fd93f6e53c832e24c9db06377d | 675,003 |
def error_list (train_sents, test_sents, radius=2):
"""
Returns a list of human-readable strings indicating the errors in the
given tagging of the corpus.
:param train_sents: The correct tagging of the corpus
:type train_sents: list(tuple)
:param test_sents: The tagged corpus
:type test_sen... | 7e4f0aa722ccead0fe6104a7575ee474faf241e8 | 675,004 |
import torch
def soft_dice_score(
y_pred: torch.Tensor,
y_true: torch.Tensor,
smooth=0,
eps=1e-7,
dims=None,
weight=None,
) -> torch.Tensor:
"""
Args:
y_pred: (N, NC, *)
y_true: (N, NC, *)
smooth:
eps:
Returns:
scalar
"""
assert y_pre... | 9c09a1fd750b1f904f094a0dce2e7aedbd4a99fa | 675,005 |
def pascal_case_to_snake_case(input_string):
"""
Converts the input string from PascalCase to snake_case
:param input_string: (str) a PascalCase string
:return: (str) a snake_case string
"""
output_list = []
for i, char in enumerate(input_string):
if char.capitalize() == char: # if ... | 62f710935cb2ff0feabbbaeffbb2320192720505 | 675,006 |
def ellipsis2slice(input_, shape):
"""Converts ellipsis to slice."""
input_slice = input_
result = []
if isinstance(input_, type(...)):
input_slice = (input_,)
ell_count = 0
for _, element in enumerate(input_slice):
if not isinstance(element, type(...)):
result.append... | c91b0512be5504867c60535b4b9203a72ea20a63 | 675,007 |
def leiaInt(msg=''):
"""
-> Valida entradas numéricas do tipo inteiro.
:param msg: (opcional) Mensagem que será exibida na tela para entrada do valor numérico.
:return: O valor numérico recebido como caracter transformado em inteiro.
"""
while True:
num = input(msg).strip()
if nu... | 5bae1b3fd66fd40f7750e4e0ef6ef37819ee923b | 675,008 |
from typing import Sequence
import argparse
def parse_args(argv: Sequence[str]) -> argparse.Namespace:
"""Parse the command line arguments."""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('--verbose', '-v', ac... | 75bfaa4367b0f268fcb7c7ea3eda3062b7b433ea | 675,009 |
def to_dict(d):
""" Convert EasyDict to python dict recursively.
Args:
d (EasyDict): dictionary to convert
Returns:
dict
"""
d = d.copy()
for k, v in d.items():
if isinstance(d[k], dict):
d[k] = to_dict(d[k])
return dict(d) | e6dcb313190b814100b1caacdbcef7383f72fc2d | 675,010 |
from pathlib import Path
def get_file_size_in_bytes_3(file_path):
""" Get size of file at given path in bytes"""
# get file object
file_obj = Path(file_path)
# Get file size from stat object of file
size = file_obj.stat().st_size
return size | 0dfdcdcdf0e3b77a8664d9e9161498ae6f7e712a | 675,011 |
from typing import List
import re
def get_assignees(content: str) -> List[str]:
"""Gets assignees from comment."""
regex = r"\+([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"
matches = re.findall(regex, content)
return [m for m in matches] | 0c5c90237eff1c3d07767bfb7434d5ca977e03e2 | 675,013 |
def unpad_list(listA, val=-1):
"""Unpad list of lists with which has values equal to 'val'.
Parameters
----------
listA : list
List of lists of equal sizes.
val : number, optional
Value to unpad the lists.
Returns
-------
list
A list of lists without the padding... | 8354f3c78168aafa86a0a07997895d964d81cb31 | 675,015 |
def decode_outputs(probs, inds, decoder):
"""
Decode from network probabilities and compute CER
Arguments:
probs: Tensor of character probabilities
inds: List of character indices for ground truth
decoder: instance of a Decoder
Returns:
Tuple of (ground truth transcript,... | 1571df5ac1fcea9e3dd5206357c920cbfd1a1011 | 675,016 |
from typing import Tuple
def _get_ds_file_offset(
parm_start: int, span: Tuple[int, int], inclusive: bool = False
) -> Tuple[int, int]:
"""Get the file offsets for the parameter.
:param parm_start: The start position of the parm.
:param span: The span of the parm data.
:param inclusive: Whether t... | acd8055564400cf59d73642707695b51a3c38e99 | 675,018 |
import cProfile
import pstats
def profile(func):
"""Decorator to execute cProfile"""
def _f(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
print("\n<<<---")
res = func(*args, **kwargs)
p = pstats.Stats(pr)
p.strip_dirs().sort_stats('cumtime').print_stats(... | cb6a6069ee8f003553144f16e1ee9299faac563c | 675,019 |
import time
def fetch_all_from_start_end_table(conn):
"""
Fetches all entries from start_end table
:param conn: Timescaledb connection
:type conn: psycopg2.connect()
"""
start = time.time()
cursor = conn.cursor()
cursor.execute("SELECT * FROM start_end;")
end = time.time()
prin... | 3b14c9d834d9ed3ee06348505e1b98430b7f22c9 | 675,020 |
def _join_tokens_to_string(tokens, master_char_set):
"""Join a list of string tokens into a single string."""
token_is_master = [t[0] in master_char_set for t in tokens]
ret = []
for i, token in enumerate(tokens):
if i > 0 and token_is_master[i - 1] and token_is_master[i]:
ret.append(u" ")
ret.app... | a5545ca25b039ee3b343a7889b024e9dacdde372 | 675,021 |
def check_around(position: tuple, matrix, size: int):
"""position is x y , matrix is 2d :
checks around a position + size of shape if wall
returns False
"""
for row in matrix[position[1]: position[1] + size]:
for cell in row[position[0]: position[0] + size]:
if cell == 1:
... | b01a29a8e0e96927d590ad0493dfd259b77f2597 | 675,022 |
def parse_games_wins(r):
""" Used to parse the amount of games won by a team.
"""
return int(r.get("wedWinst", 0)) | e305507c297d923eab5181da0b5b9531914e5ec6 | 675,023 |
import random
import string
def get_random_string(starting_letter: str):
"""Returns a random string starting with starting_letter, consisting of letters (uppercase and lowercase) and
numbers."""
return starting_letter + ''.join(random.choices(string.ascii_uppercase + string.digits, k=20)) | 3f12a95741fce80f768f69749a4811bd9d13366b | 675,024 |
def _num_two_factors(x):
"""return number of times x is divideable for 2"""
if x <= 0:
return 0
num_twos = 0
while x % 2 == 0:
num_twos += 1
x //= 2
return num_twos | d122f5a084c38e9b6a8de251f2a0658957f23b63 | 675,025 |
import re
def _fix_empty_string_marks(text):
"""Fix the empty string notation in text to what PostgreSQL expects."""
# COPY command expects the empty string to be quoted.
# But csv quotes the double-quotes we put.
# Replace the quoted values either at the first entry, the last or one in
# between ... | 9747634026356f4f721892123d06040372c43546 | 675,026 |
def isaudio(file: str)->bool:
"""
test whether param file is has a known ending for audio formats
:param file: str
:return: bool
"""
audio_files = ["mp3", "aac", "ogg", "m4a"]
end = file.rsplit(".", 1)[-1]
return True if end in audio_files else False | 150e937266cd971a1fdd7bf2dce5deb96bec1fae | 675,027 |
import subprocess
def shell(cmd, check=True, stdin=None, stdout=None, stderr=None):
"""Runs a subprocess shell with check=True by default"""
return subprocess.run(
cmd, shell=True, check=check, stdin=stdin, stdout=stdout, stderr=stderr
) | 8a6b84e74169fb1302ad43fc03a04def45e43438 | 675,028 |
import re
def convert_binary_alt(data):
"""
Transforms a list of items to a binary vector product representation, using model words in the title and decimals in
the title and feature values.
:param data: a list of items
:return: a binary vector product representation
"""
# For computatio... | 051d4952eac51ac41bfed027847f65f659e942a0 | 675,029 |
def choose_gc_from_config(config):
"""Return a (GCClass, GC_PARAMS) from the given config object.
"""
if config.translation.gctransformer != "framework": # for tests
config.translation.gc = "marksweep" # crash if inconsistent
classes = {"marksweep": "marksweep.MarkSweepGC",
... | 93af505e0dd81bed6fedfcce206e01a6a3835ff9 | 675,030 |
import re
def format_kwargs(string, *args):
"""Return set or dict (optional) of keyword arguments ({keyword}) in provided text"""
keywords = {x.strip('{}') for x in re.findall(r'((?<!{){(?!{).*?(?<!})}(?!}))', string)}
if args and args[0] == "dict":
return {sub: "" for sub in keywords}
return ... | b828223072d8c8e3902af7b5e1d4400b6bd93e8c | 675,031 |
def canConstruct_v2(ransomNote: str, magazine: str) -> bool:
"""The LeetCode solution runner judges this as the fastest solution of all four."""
for letter in set(ransomNote):
if ransomNote.count(letter) > magazine.count(letter):
return False
return True | c88b4272c629f6b15defb6e38699aac3f4a5a3bb | 675,032 |
def _trynumber(value):
"""Try to convert a string to a number"""
# Let's catch true / false here too
if value in ["true", "false"]:
return True if value == "true" else False
# This should catch both positive counters (int)
# and locations (float). If ALE yields negative numbers
# for any... | ebf6cf1f708c371892556c19676b3021087acc4a | 675,034 |
import random
def randcolor(mode):
"""Makes a random color for the given mode"""
ri = lambda v: random.randint(0, v)
if mode == 'L':
return ri(255)
elif mode == '1':
return ri(1)
elif mode == 'I':
return ri(2**23-1)
elif mode == 'F':
return random.random()
e... | 7dcc9fc09c792c7919e9aafff6e5c5733186116c | 675,035 |
def drop_columns(df, columns, inplace=False):
"""drop a list of columns from a Pandas dataframe,
in place"""
if not inplace:
df = df.copy()
for c in columns:
df.pop(c)
return df | 91eb261c184f20ed9051976c5c65afe1f2439fd2 | 675,036 |
def merge_lists(two_d_list):
"""Merges a 2d array into a 1d array. Ex: [[1,2],[3,4]] becomes [1,2,3,4]"""
# I know this is a fold / reduce, but I got an error when I tried
# the reduce function?
return [i for li in two_d_list for i in li] | 24ff74a9345cdfb1590a053a20f45fea21164454 | 675,037 |
def sorted_bulk_data_header() -> str:
"""creates the bulk data echo header"""
msg = '0 S O R T E D B U L K D A T A E C H O \n'
msg += ' ENTRY ... | 710a2b1c902e411bb8c571f5d356f4c116fcb366 | 675,038 |
def char(int):
"""
CHAR int
outputs the character represented in the ASCII code by the input,
which must be an integer between 0 and 255.
"""
return chr(int) | 7fa90e06d9b4498a1603fa2439776789c98bd2be | 675,039 |
def _find_depender(dkey, blade):
"""_find_depender to find which target depends on the target with dkey.
"""
target_database = blade.get_target_database()
for key in target_database:
if dkey in target_database[key].expanded_deps:
return '//%s:%s' % (target_database[key].path,
... | 53673811686fe54f39d2a59b78d0d2d10bc68306 | 675,040 |
def to_port(port_str):
"""
Tries to convert `port_str` string to an integer port number.
Args:
port_str (string): String representing integer port number in range
from 1 to 65535.
Returns:
int: Integer port number.
Raises:
ValueError: If `port_str` ... | 3ed89b058d7658d6faec307031252238351ffba2 | 675,041 |
def pk_encrypt(data, public_key):
"""
Return list of chunks of `data` encrypted by `public_key`.
data: string
The message to be encrypted.
public_key: :class:`Crypto.PublicKey.RSA`
Public portion of key pair.
"""
# Normally we would use 8 rather than 16 here, but for some reaso... | 2ead6bd51c8e1f07703739690853d0174bd7750a | 675,042 |
def get_best_alignment(record_list):
"""
Get the best alignment from a list of alignments. The best alignment has the lowest distance to the reference. If
more than one alignment has the minimum distance, then the first one in the list is returned.
:param record_list: List of records.
:return: Bes... | 133956b0ecac5b948e3ff7dd20e6a9167f362d9e | 675,043 |
def isAdditivePrimaryColor(color):
"""
return True if color is a string equal to "red", "green" or "blue", otherwise False
>>> isAdditivePrimaryColor("blue")
True
>>> isAdditivePrimaryColor("black")
False
>>> isAdditivePrimaryColor(42)
False
>>>
"""
return ( (color == "r... | 91a13b47d4143adab9fe27135044dcc6df58de56 | 675,044 |
import re
def clean_string(string):
"""
Performs tokenization and string cleaning for the AG_NEWS dataset
"""
# " #39;" is apostrophe
string = re.sub(r" #39;", "'", string)
# " #145;" and " #146;" are left and right single quotes
string = re.sub(r" #14[56];", "'", string)
# " #147;" an... | c28e5ea0e3602dd98cfe905a22d0a4925abc26fc | 675,046 |
import argparse
def get_args():
"""Function for parsing arguments. For now the only argument is that the
configuration json file has to be specified.
Returns:
args: returns the argument (JSON file).
"""
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument(
... | f3efd351fdabe0dedb92296482cda005f89230c4 | 675,047 |
def map_attributes(properties, filter_function):
"""Map properties to attributes"""
if not isinstance(properties, list):
properties = list(properties)
return dict(
map(
lambda x: (x.get("@name"), x.get("@value")),
filter(filter_function, properties),
)
) | cfb6d22fdaccc21ba3ff7b957a4d8379313f9e12 | 675,048 |
def vector_single():
"""
"""
return [1.0, 0.0, 1.0] | 7df69f843a763da5361c11f6b42f7918a8760fb2 | 675,049 |
def checking_features(columns:list, lst_features:list) -> bool:
"""
Parameters:
* columns [list]: list of columns in the dataframe.
* lst_features [list]: list of required features.
Return:
True/False [bool]: If all / not all the required features
are in the dataframe.
"""
if all([feat in columns f... | 5cdaa5751a6fee832b378e12db3263976a88f89a | 675,050 |
def get_key_symbol(key, index):
"""
If length of our key is less than initial string
we get next symbol from the start in a loop
"""
if index > len(key) - 1:
return key[index % len(key)]
return key[index] | 134cfc6a703852867f2a918c1848eb32141db7c1 | 675,051 |
def pres2depth(self, add_nominal_depth=True, density='sea-water', inplace=True):
"""
It creates the DEPTH index of the WaterFrame from the PRES column.
Parameters
----------
add_nominal_depth: bool
Returns a WaterFrame with an extra parameter called 'NOMINAL_DEPTH'
that ... | 8da4694220d887e1856e42f0d0a82c276fe9f13d | 675,052 |
def _Delta(a, b):
"""Compute the delta for b - a. Even/odd and odd/even
are handled specially, as described above."""
if a+1 == b:
if a%2 == 0:
return 'EvenOdd'
else:
return 'OddEven'
if a == b+1:
if a%2 == 0:
return 'OddEven'
else:
return 'EvenOdd'
return b - a | 5708a934b18e87b3719e16df967d8320b9be7e8d | 675,053 |
import difflib
def diff_files(filename1, filename2):
"""
Return string with context diff, empty if files are equal
"""
with open(filename1) as file1:
with open(filename2) as file2:
diff = difflib.context_diff(file1.readlines(), file2.readlines())
res = ""
for line in diff:
... | 37031f9918bc02cb63365b5206847bbf8671b957 | 675,054 |
def add_args(parser):
"""
Create parser for command line utility
:meta private:
"""
parser.add_argument(
"--pairs", help="Candidate protein pairs to predict", required=True
)
parser.add_argument("--model", help="Pretrained Model", required=True)
parser.add_argument("--seqs", he... | 7ca4bbdd2ccc09db472cbd1bdf9ec23dcd9b9a00 | 675,055 |
def min_list(lst):
"""
A helper function for finding the minimum of a list of integers where some of the entries might be None.
"""
if len(lst) == 0:
return None
elif len(lst) == 1:
return lst[0]
elif all([entry is None for entry in lst]):
return None
return min([entr... | 5287286c843086c271f6fc709b275796cc68f314 | 675,056 |
def first_letters(text):
"""(string) -> string
>>> first_letters('this is a test')
This Is A Test
"""
return text.title() | 066d148da6da62cb29b4025681015327f2640980 | 675,057 |
def inherit_params(
new_params,
old_params):
"""Implements parameter inheritance.
new_params inherits from old_params.
This only does the top level params, matched by name
e.g., layer0/conv is treated as a param, and not layer0/conv/kernel
Args:
new_params: the params doing the inheriting
ol... | 0129494a09d34e54b48214c3a7619a89027c462a | 675,058 |
def manhattan_distance(coordinate_p, coordinate_q):
"""
曼哈顿距离
:param coordinate_p: p坐标
:param coordinate_q: q坐标
:return: 曼哈顿距离值
"""
point = (abs(x - y) for x, y in zip(coordinate_q, coordinate_p))
return sum(point) | 1958fce76612f53b87dbe89817392990d9e8039d | 675,059 |
def tabescape(unescaped):
""" Escape a string using the specific Dovecot tabescape
See: https://github.com/dovecot/core/blob/master/src/lib/strescape.c
"""
return unescaped.replace(b"\x01", b"\x011")\
.replace(b"\x00", b"\x010")\
.replace(b"\t", b"\x01t")\
... | fb275d2d1e775e8038f32fcc03584ab07930c273 | 675,060 |
import re
def header_anchor(text, level):
"""
Return a sanitised anchor for a header.
"""
# Everything lowercase
sanitised_text = text.lower()
# Get only letters, numbers, dashes, spaces, and dots
sanitised_text = "".join(re.findall("[a-z0-9-\\. ]+", sanitised_text))
# Remove multip... | 13aa875b90e4e2cf9ce258e6af2bb3e3610c03db | 675,061 |
def cd2W(intensity, efficiency, surface):
"""
intensity in candles
efficency is a factor
surface in steradians
"""
lumens = intensity * surface
return lumens / (efficiency * 683) | 39b6873108d40e7782561d0e1f3483fd1478cf75 | 675,062 |
def pywemo_model():
"""Pywemo LightSwitch models use the switch platform."""
return "LightSwitchLongPress" | c2c2ce14cd4ad8d716cf76e4c43c9029766384cd | 675,063 |
def vmp(t):
"""return propellant burn rate as function of time"""
if t <= 5.:
return 20.
else:
return 0. | 1f41f6fa57d492a9f7de3935a9b658795af0b161 | 675,064 |
import itertools
from typing import List
def itertools_combinations_with_repl(string: str, n: int) -> List[str]:
"""
>>> itertools_combinations_with_repl('HACK', 2)
['AA', 'AC', 'AH', 'AK', 'CC', 'CH', 'CK', 'HH', 'HK', 'KK']
"""
return sorted(''.join(tup)
for tup in itertools.co... | 80ce4c2727126668b6ac31f57383161f2dbf1310 | 675,065 |
import re
def parse_show_dhcp_server(raw_result):
"""
Parse the 'show dhcp-server' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show ntp trusted-keys command \
in a dictionary of the form:
::
{
... | b5e4cd8d39e08cad8c4d24fd36ff19c373c00825 | 675,066 |
def list_to_err(errs):
"""convert list of error strings to a single string
:param errs: list of string errors
:type errs: [str]
:returns: error message
:rtype: str
"""
return str.join('\n\n', errs) | a01e12d282ed3419f1c3cccf4dbfc70704c32efe | 675,067 |
def get_other_identifier(element, code):
"""Get other identifiers associated with an author from their ISNI record"""
identifiers = element.findall(".//otherIdentifierOfIdentity")
for section_head in identifiers:
if (
section_head.find(".//type") is not None
and section_head... | cf18a2f80d85640a62f445cb1d4429cfa50275e1 | 675,069 |
def gcd(a, b):
"""
Greatest common divisor (greatest common factor)
Notes
---------
Euclidean algorithm:
a > b > r_1 > r_2 > ... > r_n
a = b*q + r
b = r_1*q_1 + r_2
...
r_n-1 = r_n*q_n
gcd(a,b) = gcd(b,r)
gcd(a,0) = a
"""
while b != 0:
a, b = b, a % ... | 62c2301013458fae6cb2827e087bb5266fb2fafa | 675,070 |
def _derive_key(pubkey, x):
"""
Derive shared secret from the public key of the sender and private key of the
user.
:parameters:
pubkey : object of class `PublicKey`
x : secret key of the user
Returns the derived shared key
"""
p = pubkey.p
g = pubkey.g
h = pub... | a8b83a5e33410dd054b2dba3f6ec1d547100d874 | 675,071 |
import re
import fractions
def get_quantity(parts):
""" returns a tuple (quantity, parts without quantity) """
quantity = 1
for i, part in enumerate(parts):
if re.match(r'[0-9]*\.*[0-9]', part) is not None:
try:
quantity = float(fractions.Fraction(part))
... | 9355fcb8cb444af36edc69324e445d8301c66665 | 675,072 |
import os
def user_mkdir(cmd, **kwargs):
"""
Used in system tests to emulte a user creating a directory
"""
if type(cmd) is str:
assert cmd is not '', "no arguments passed to mkdir, not allowed"
cmd = cmd.split()
if len(cmd) == 2:
assert '-p' in cmd, "two args to mkdir, nei... | a0de7e4058806d83b9305a86dfb3f8d37e5e3bac | 675,073 |
def group_device_names(devices, group_size):
"""Group device names into groups of group_size.
Args:
devices: list of strings naming devices.
group_size: int >= 1
Returns:
list of lists of devices, where each inner list is group_size long,
and each device appears at least once in an inner list.... | 9685bdae126a42738425334de98a33b2263fdf51 | 675,074 |
import aiohttp
import asyncio
async def handler(fcn, args=None):
"""
:param fcn:
:param args:
:param kwargs:
:return:
"""
tasks = []
async with aiohttp.ClientSession() as session:
if args is None:
tasks.append(asyncio.ensure_future(fcn(session)))
elif isinst... | 43757e8ed1afdbcc5e2e8a0df15a8c53811c67db | 675,075 |
def cut_line(line_copy, index_candidates):
"""Cut the sentence.
Args:
line: a list contains the vocabs.
ratio: the percentage of the parts of the line to be removed.
Default None, ramove randomly.
Returns:
a list.
"""
length = len(line_copy)
retu... | 2034e8b30569fc9ccde431bbc2d3afbce048f026 | 675,076 |
import time
def gmtime_for_datetime(dt):
"""
Pass in a datetime object, and get back time.gmtime
"""
return time.gmtime(time.mktime(time.strptime(dt.strftime("%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S"))) if dt is not None else None | 136992420c1c181441c70dc6747d15cadae0ff19 | 675,078 |
import torch
def _repackage_hidden_bidirectional(h_result):
"""
Repackages the hidden state into nn.GRU format. (bidirectional use)
"""
h_all = [t[0] for t in h_result]
c_all = [t[1] for t in h_result]
return torch.cat(h_all, dim=0), torch.cat(c_all, dim=0) | e17d77ebabc287fea04e82d25a0faeaa8aed8c7c | 675,079 |
def find_numbers(row, column, block, blocksize):
"""Deze functie krijgt de rij, de kolom en het block van een leeg vak in
de sudoku mee en returnt een lijst van alle waarden die in dit vak passen.
"""
result = []
for i in range(1, int((blocksize**2)+1)):
if i not in row and i not in column a... | d681cbcf887499591177422e64519042d2fe1b88 | 675,080 |
from typing import Dict
import numbers
def valid_config(config: Dict) -> bool:
"""Ensure that any configuration errors are caught before starting analysis."""
# Make sure some values are numeric
numeric = [isinstance(config[k], numbers.Number) for k in
["xfrom", "xto", "xstep", "bandwidth", "shift... | a904f53c2ec664b1bc82c556e2e0e75c7f6a880a | 675,081 |
def is_palindrome(s):
"""
Check whether a string is a palindrome or not.
For example:
is_palindrome('aba') -> True
is_palindrome('bacia') -> False
is_palindrome('hutuh') -> True
Parameters
----------
s : str
String to check.
Returns
-------
bool
... | cb233ad7eccfa22d7e0ccdfb7e7041d57d9eee05 | 675,082 |
def suffix(n: int) -> str:
"""Return number's suffix
Example:
1 -> "st"
42 -> "nd"
333 -> "rd"
"""
return "th" if 11 <= n <= 13 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th") | ed8ccd0d6db63a04509f4ea14b5f85337e566ffb | 675,083 |
def switch_string_to_numeric(argument):
"""
Switch status string to numeric status (FLAT - POOR: 0, POOR - POOR TO FAIR = 1, FAIR TO GOOD - EPIC = 2)
"""
switcher = {
"FLAT": 0,
"VERY POOR": 0,
"POOR": 0,
"POOR TO FAIR":1,
"FAIR":1,
"FAIR TO GOOD":2,
... | 009a6e7e994fcc3cff0e4e3944b159a36bfc224e | 675,084 |
import re
def camel_to_snake_case(name, exclude_key_words=['']):
"""tanslate the name to the snake case according to the named conventions
1. split the class name with the capital letter
2. remove all the spaces and join the elements in the array with '_' sign, and lower the string you get
:param nam... | b317ca842c3fc36280c8d3205bf1e42c8ed16331 | 675,086 |
def get_printable_banner(input_str=None):
"""
Returns a string that when printed shows a banner with the given string in the center.
Args:
input_str: str. Any string of moderate length roughly less than 30 that you want placed inside a
pound/hashtag (#) banner.
Returns:... | d5f90bc7063107941387c4579f932f6f6636f31f | 675,087 |
def weight_combination(entropy, contrast, visibility, alpha1, alpha2, alpha3):
"""
Combining the entropy, the contrast and the visibility to build a weight layer
:param entropy: The local entropy of the image, a grayscale image
:param contrast: The local contrast of the image, a grayscale image
:pa... | 6d0ef8b58204ad90bed1f07097c23473463ed577 | 675,088 |
def mk_inclusion_filter(include=(), key=None):
"""
Creates a function to perform inclusion filtering (i.e. "filter-in if x is in include list")
:param include: a list-like of elements for an inclusion filter
:param key: None (default), a callable, or a hashable. If
* None, the filter will be det... | 4ba96f257cb2ba267b551f00bc573bee0969a839 | 675,089 |
def adj_dists_fast(clusts1, clusts2):
"""computes distance between adjacency matrices implied by partions without instantiating them.
This is faster than first computing adjacency matrices and then using
adj_dists when the number of clusters is small.
"""
# sum of square set sizes
dist = sum(len... | f1981d1fbb729dfed49b8b4a76a9e5fad3834b40 | 675,090 |
def map256(vals):
""" Map dictionary key values to a 0-255 range.
Your input dictionary will have a smaller range than 0-256. For instance
you may have 49-91. The return dictionary will contain keys 0, 255 and some
values in between. The point is to normalize the span of the input acrouss
and 8-bit... | 359b9e4149a45f1f22b5c341f52bec108d8e0a77 | 675,091 |
def _calc_tstop(n_bins, bin_size, t_start):
"""
Calculates the stop point from given parameters.
Calculates the stop point `t_stop` from the three parameters
`n_bins`, `bin_size`, `t_start`.
Parameters
----------
n_bins : int
Number of bins
bin_size : pq.Quantity
Size o... | 995ea49417cfd4c2a036af86e7ac7463ccbf0ed2 | 675,092 |
import requests
def goa_calmgr(user_request, verbose=False):
"""
Query the GOA galmgr API
Parameters
user_request: Search request URL string, it should not contain 'calmgr'
\
Return
request_xml: Query result in XML format
"""
response = requests.get(
'https://arc... | 7d39de8256a7f25e432b8acfd9e5d879a2e268c7 | 675,093 |
def camel_case_to_under_score(x):
"""
CamelCase --> camel_case
:param x: (str)
The CamelCase string to
be converted to pep8.
:return: (str)
The formatted pep8 string.
lower case
upper case prefixed with underscore.
"""
string = ''
x = str(x)
for i,... | 84ee9f5ae79170a6db832282c4fcff6178a3b2cf | 675,094 |
def _datesplit(timestr):
"""
Split a unit string for time into its three components:
unit, string 'since' or 'as', and the remainder
"""
try:
(units, sincestring, remainder) = timestr.split(None, 2)
except ValueError:
raise ValueError(f'Incorrectly formatted date-time unit_strin... | 587293853afbf5cfee1103c1a48c087f59c9d3d8 | 675,095 |
import requests
import json
def move_hosts_to_new_group(platform, key, client, group):
"""
Move hosts defined by a filter to a new group, specified by group ID.
:param platform: URL of the RiskSense platform to be queried.
:type platform: str
:param key: API Key.
:type key: ... | 41eed8e50a7917e21f39d5f5d37aad6e271f0dcf | 675,096 |
def get_bollinger_bands(rm, rstd):
"""Return upper and lower Bollinger Bands."""
upper_band = rm + 2 * rstd
lower_band = rm - 2 * rstd
return upper_band, lower_band | 1c63ba90047cdfc902606f5978b38db00256d31c | 675,097 |
import os
def get_out_dir(out_dir, dataset):
""" Returns a new, dataset-specific, out_dir under 'out_dir' """
out_dir = os.path.abspath(out_dir)
out_dir = os.path.join(out_dir, dataset)
return out_dir | 264fd7e1e1d2bf45baaeefcff10d122f309df5c3 | 675,098 |
import calendar
def timestamp_from_datetime(dt):
"""
Returns a timestamp from datetime ``dt``.
Note that timestamps are always UTC. If ``dt`` is aware, the resulting
timestamp will correspond to the correct UTC time.
>>> timestamp_from_datetime(datetime.datetime(1970, 1, 1, 0, 20, 34, 500000))
... | 3a46b739e6b15b904b2bb13cb424ec6688aaa3ed | 675,099 |
def mean_bits(freq, codes):
""" Calculate mean bits used by a code table """
total = sum([f[1] for f in freq]) / 1.0
mbs = sum([f/total * len(codes[sym]) for sym, f in freq])
return mbs | 92022c4dcc341e5830f6b2b806dc71ce44575f58 | 675,100 |
def _parse_bond_line( line ):
"""Parse an AMBER frcmod BOND line and return relevant parameters in a dictionary. AMBER uses length and force constant, with the factor of two dropped. Here we multiply by the factor of two before returning. Units are angstroms and kilocalories per mole per square angstrom."""
tm... | 892637a597e80724e1285bc32646ed1a25978c61 | 675,101 |
def _find_code_cell_idx(nb, identifier):
"""
Find code cell index by provided ``identifier``.
Parameters
----------
nb : dict
Dictionary representation of the notebook to look for.
identifier : str
Unique string which target code cell should contain.
Returns
-------
... | 53e3ff071e0d5b9266ad3f6cfc44d26355553362 | 675,102 |
def _get_QActionGroup(self):
"""
Get checked state of QAction
"""
if self.checkedAction():
return self.actions().index(self.checkedAction())
return None | 0581a9176c6291714f81b5f6570fac1504153ddb | 675,103 |
import time
def seconds_per_run(op, sess, num_runs=50):
"""Number of seconds taken to execute 'op' once on average."""
for _ in range(2):
sess.run(op)
start_time = time.time()
for _ in range(num_runs):
sess.run(op)
end_time = time.time()
time_taken = (end_time - start_time) / num_runs
return t... | a16abfa914f2069ca9b91281d1999af7303946b3 | 675,104 |
def normalise_name(name):
"""
Normalise name to: Forename Surname
"""
elements = name.split()
new = elements[0].title() + " "
new += elements[-1].title()
return new | bb6c3bac2b8de68880d4f6a32390cab6703a1b29 | 675,105 |
def nospace(string):
"""
Strip all space characters from a string.
This function does not remove any other whitespace characters.
>>> nospace(' t hi \t s has n o \n s p a ces ')
'thi\tshasno\nspaces'
@type string: C{string}
@param string: The string to remove all space char... | 2e9b3558993cc6b1de2dfdbb03228a163695c236 | 675,106 |
def to_pandas(modin_obj):
"""Converts a Modin DataFrame/Series to a pandas DataFrame/Series.
Args:
obj {modin.DataFrame, modin.Series}: The Modin DataFrame/Series to convert.
Returns:
A new pandas DataFrame or Series.
"""
return modin_obj._to_pandas() | 740a84989f0c24e2671cce0a1029d457b447af74 | 675,107 |
import time
def get_range_query_args_from_duration(duration_secs=240):
"""Get start and end time for a duration of the last duration_secs."""
return (int(time.time()) - duration_secs, int(time.time())) | bb46469b1489bdf3759709269bdaee4ca45acdfd | 675,108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.