content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def create_dataverse_url(base_url, identifier):
"""Creates URL of Dataverse.
Example: https://data.aussda.at/dataverse/autnes
Parameters
----------
base_url : str
Base URL of Dataverse instance
identifier : str
Can either be a dataverse id (long), a dataverse alias (more
... | 8dcaacf58c7ca8b601ed2543f8d8de20bbcbc8a2 | 27,906 |
import re
def createMetaFile(bookList,fileCount):
"""
Method creates meta file. Meta file stores information on which book is currently playing,
and the current file number and progress for each book.
"""
currentBook = 0
try: # code for if meta file already exists
f = o... | 62bd24a311713164e4f5cec439948faa408f0508 | 27,907 |
def refs_should_be_omitted(ref: str):
"""
Determine if a ref should be completely omitted from json output, we do not want
to show origin
@param ref: string containing the ref
@return: True if this ref should be omitted from the list
"""
return ref.startswith("origin/") | 79e923b1be03f0b552c989250bd1cadfc528e25b | 27,909 |
def isinsetf(s):
"""
Returns a function which tests whether an element is in a set `s`.
Examples
--------
>>> colors = ['red', 'green', 'blue']
>>> f = isinsetf(colors)
>>> map(f, ['yellow', 'green'])
[False, True]
"""
s = set(s)
return lambda e: e in s | 492f5381a66ef42670e5dd229c41a5481290114a | 27,910 |
def ccalc_turbo(x, rgbmax):
""" viridis 'turbo' colour map"""
r = [0.18995, 0.19483, 0.19956, 0.20415, 0.2086, 0.21291, 0.21708, 0.22111, 0.225, 0.22875, 0.23236, 0.23582, 0.23915, 0.24234, 0.24539, 0.2483, 0.25107, 0.25369, 0.25618, 0.25853, 0.26074, 0.2628, 0.26473, 0.26652, 0.26816, 0.26967, 0.27103, 0.27226, 0.27... | ddfe1cf465cdc804363075b3371214184b1a05e4 | 27,911 |
def to_component_dict(component):
"""
:rtype: ``dict``
"""
result = {
'id': component.id,
'name': component.name
}
return result | 8b8102529cfa4bd54cce3a6710cb7db5af7d0320 | 27,913 |
import math
def f(n):
"""
Define f(n) as the sum of the digit factorials for given number n.
For example:
f(342) = 3! + 4! + 2! = 32
:param n: number
:return: sum digit factorial
"""
return sum(math.factorial(int(ch)) for ch in str(n)) | 334ca97a936876d79643cad70994c3da8cbee98e | 27,914 |
def get_custom_name_record(ttfont, text):
"""Return a name record by text. Record ID must be greater than 255"""
for record in ttfont['name'].names[::-1]:
if record.nameID > 255:
rec_text = record.toUnicode()
if rec_text == text:
return record
return None | 80e6b267753ba0ece3f75dc83c3ace3dfdd1dda0 | 27,915 |
import os
def default_root():
"""
Default root for the lilcaches.
"""
home_dir = os.path.expanduser("~")
path = os.path.join(home_dir, ".lilcache")
if not os.path.exists(path):
os.mkdir(path)
return path | ecfdb38a58d39e09ffb37b2dbe5b48044c620745 | 27,917 |
def plot_line(x1, y1, x2, y2):
"""Brensenham line drawing algorithm.
Return a list of points(tuples) along the line.
"""
dx = x2 - x1
dy = y2 - y1
if dy < 0:
dy = -dy
stepy = -1
else:
stepy = 1
if dx < 0:
dx = -dx
stepx = -1
else:
step... | 2d0f1e2e9efda98ce19a93ca3e0aa830e7793f64 | 27,918 |
import asyncio
import socket
async def getfirstaddrinfo(
host, port, family=0, type=0, proto=0, sock=None, flags=0, loop=None
):
"""
retrieve sockaddr for host/port pair with given family, type, proto settings.
return first sockaddr. raises socket.gaierror if no result was returned.
"""
if soc... | 32d5e6e3559c19f9e25dbdbcebe35aeeb6f4699c | 27,919 |
def createc_fbz(stm):
"""
Function returning Createc channel feedback z value
Parameters
----------
stm : createc.CreatecWin32
Createc instance
Returns
-------
value : str
"""
# from createc.Createc_pyCOM import CreatecWin32
# stm = CreatecWin32()
return stm.... | affda33fd1050fdf865544cfc66e3899788fccc2 | 27,922 |
def similar(x,y):
"""
function that checks for the similarity between the words of
two strings.
:param x: first string
:param y: second string
:return: returns a float number which is the result of the
division of the length of the intersection between the two strings'
wor... | 92edaf8ebcedcbfbb1adf2b87c8d00f159b3ccc8 | 27,923 |
import uuid
import os
def random_fname():
"""Generates a random file name. In the *very* unlikely case that `uuid4`
generates a file name that already exists, we'll generate a new one until
a unique file name is generated.
Returns:
A unique file name `str`.
"""
fname = "{}.tmp".format... | 1e40db54939f48edb7d03f33026b5af456c8536b | 27,924 |
from typing import Dict
from typing import List
from typing import Any
def get_entity_embedding(
examples,
tokenizer,
subject_start_marker: str,
subject_end_marker: str,
object_start_marker: str,
object_end_marker: str
) -> Dict[str, List[Any]]:
""" returns entity embeddings """
subj_s... | b1ae8d1d901d3c2f0ae7e0f6b553bc43edf2a364 | 27,925 |
from datetime import datetime
def convert_time(ts):
"""converts timestamps from time.time() into reasonable string format"""
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d::%H:%M:%S") | 195124dac4c4c145c397fe8e4fd10d3ab3d6700f | 27,926 |
def valid_url_input(zip_url, urls):
"""Helper function, to check if input was valid"""
if zip_url in urls:
return True
else:
return False | 5e49598835d478d759e3b64979129de19d2d810d | 27,927 |
import os
def test_cassandra_tarball():
"""default cassandra tarball of a given version to use for all tests"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "testdata", "diag", "cassandra") | 8183ce61799f81bb3a6d73e688f7640effbb9487 | 27,928 |
def isEncodingWith(filePath, encoding):
"""
已知问题
1. 若文件编码为UTF8-BOM,isEncodingWith(GBK)返回True
"""
def isUTF8(encoding):
return encoding.lower() in ('utf8', 'utf-8', 'utf_8', 'u8')
def isUTF8WithBOM(encoding):
return encoding.lower() in ('utf_8_sig')
"""
注意utf8和utf_8_sig都... | be8a0f5ac3c33ad96949546f5cb733a053452a14 | 27,929 |
def get_nr_to_check(selection, line_scores):
"""
Gets the number of checks the annotators should do given a selection and a line_score
:param selection: selection of the lines to check
:param line_scores: the lines with the given score
:return: the number of checks that still need to be performed
... | 4560a1f6a8ab3671b73513e6eab193dd5300ec82 | 27,930 |
def dmc_task2str(domain_name, task_name):
"""Convert domain_name and task_name to a string suitable for environment_kwargs"""
return '%s-%s-v0' % (domain_name, task_name) | 5a124b6a73a35fe898f24910d8f8bedda9eaa807 | 27,932 |
def read_pair_align(read1, read2):
""" Extract read pair locations as a fragment oriented in increasing chromosome coordinates
:param read1: read #1 of pair in pysam AlignedSegment format
:param read2: read #2 of pair in pysam AlignedSegment format
:return 4-item array in the following format: [fragA-s... | f9d1476330a8cf1c9e836654d67a8bcda9e18eb7 | 27,933 |
def _xds_version(xds_output_list):
"""Return the version of XDS which has been run."""
for line in xds_output_list:
if "XDS VERSION" in line:
return line.split("XDS VERSION")[1].split(")")[0].strip()
if "XDS" in line and "VERSION" in line:
return line.split("(VERSION")[1... | bf0da2a837e2139e9a2e21ed3e743cdc91ea21e7 | 27,934 |
from datetime import datetime
def days(date):
"""Convert a single datetime to a Julian day number"""
delta = date - datetime(date.year, 1, 1, 0, 0, 0)
result = delta.total_seconds() / 24 / 60 / 60
return result | cc3ae8f79ac0c4e558b813aaaa928a429ca33006 | 27,935 |
def InitTagger4Sentence(FREQDICT, sentence):
"""
Dictionary-based initial tagger for a particular language.
Labeling a sentence.
"""
words = sentence.strip().split()
taggedSen = ''
for word in words:
if word in FREQDICT:
taggedSen += word + "/" + FREQDICT[word] + " "... | 761d7e893becdd21fad2e1364bf553051e86a9a5 | 27,937 |
from typing import List
from typing import Union
def normalise(num_list: List[Union[int, float]]) -> List[Union[int, float]]:
""" Simple normalisation into [0,1] """
max_x = max(num_list)
min_x = min(num_list)
return [(x - min_x) / (max_x - min_x) for x in num_list] | c76ecd6064b474b8c1e1d7ac8bbe4966518dc76e | 27,939 |
def getaxeslist(pidevice, axes):
"""Return list of 'axes'.
@type pidevice : pipython.gcscommands.GCSCommands
@param axes : Axis as string or list of them or None for all axes.
@return : List of axes from 'axes' or all axes or empty list.
"""
axes = pidevice.axes if axes is None else axes
if ... | 6a01538eb46a7f19efcc2bfb737bf1945ec4db52 | 27,942 |
def diff(current_block, previous_block, *args):
"""Subtracts the previous block from the current block."""
return (current_block - previous_block[:len(current_block)]) | 06c6cd2ba1bc403d25d0dfcb0ae477bca5593ac9 | 27,943 |
import mimetypes
def is_html(path: str) -> bool:
"""
Determine whether a file is an HTML file or not.
:param path: the path to the file
:return: True or False
"""
(mime_type, _) = mimetypes.guess_type(path)
return mime_type in ('application/xhtml+xml', 'text/html') | bfd570f19c78447adf2ab28b2d94f1119922b97d | 27,945 |
import decimal
import math
def shannon_inform(feature_matrix, gradations_list):
"""
Procedure to count shannon's information content.
:param feature_matrix: list of lists with objects of different classes.
:param gradations_list: list of gradations of feature
:return: information content value
... | 02ae72a9ebfe8f29fffbd26d5f9631397906ae9e | 27,946 |
def parse_dats_information(dats_dict):
"""
Parse the content of the DATS dictionary and grep the variables of interest for
the summary statistics.
:param dats_dict: dictionary with the content of a dataset's DATS.json file
:type dats_dict: dict
:return: dictionary with the variables of intere... | c1847d6b107ea3277f235d1298030932d2e4ff9b | 27,947 |
def escapeHTML(txt):
"""transform Unicode character -> DEC numerical entity"""
return txt.encode("ascii", "xmlcharrefreplace").decode() | b4af51030f8f035017bbbe08dec6c7d794402b65 | 27,948 |
import ast
def stripped_literal(literal):
"""
evaluate literals, ignoring leading/trailing whitespace
This function is capable of handling all literals supported by
:py:func:`ast.literal_eval`, even if they are surrounded by whitespace.
"""
return ast.literal_eval(literal.strip()) | 9a2b6eb3af5df23bcd756e4fb261efe420fccaab | 27,949 |
import re
def only_scripts(input_iterable):
"""
Given HTML input, transform it by removing all content that is
not part of a script (between <script>…</script> tags).
Any non-script content is blanked out. The number of lines
returned is identical to the number of lines in the input so
line-n... | 6abb53a92ecf7a993d9ecbc368ab90809d11eeaf | 27,950 |
def _next_set(args):
"""
Deterministically take one element from a set of sets
"""
# no dupes, deterministic order, larger sets first
items = sorted(list(map(frozenset, args)), key=lambda x: -len(x))
return items[0], set(items[1:]) | 37d1fdf1796d2b0b455f638bc8e03de030d668f0 | 27,951 |
import re
def is_lower_camel_case(id_name):
"""Check if id_name is written in camel case.
>>> is_lower_camel_case('')
False
>>> is_lower_camel_case('_')
False
>>> is_lower_camel_case('H')
False
>>> is_lower_camel_case('h')
True
>>> is_lower_camel_case('hW')
True
>>> is... | 8f560a6bd6ea634526573342a58fbba11f8dab37 | 27,953 |
import re
def config_filename(name, ext="json"):
"""
>>> config_filename("system global")
'system_global.json'
>>> config_filename('system replacemsg webproxy "deny"')
'system_replacemsg_webproxy_deny.json'
>>> config_filename("system.*")
'system_.json'
"""
cname = re.sub(r"[\"'\.]... | 906c35bee18ec0128ff18338174eeab93a6e89c2 | 27,954 |
import os
def getOxum(dataPath):
"""
Calculate the oxum for a given path
"""
fileCount = 0
fileSizeTotal = 0
for root, dirs, files in os.walk(dataPath):
for fileName in files:
fullName = os.path.join(root, fileName)
stats = os.stat(fullName)
fileSiz... | 75d0ecf09aa00d015b0d3e768639816143364622 | 27,955 |
def num_to_frak(n):
"""Convert a number to a Fraktur character.
Args:
n (int): Number
"""
return "𝔞𝔟𝔠𝔡𝔢𝔣𝔤𝔥𝔦𝔧𝔨𝔩𝔪𝔫𝔬𝔭𝔮𝔯𝔰𝔱𝔲𝔳𝔴𝔵𝔶𝔷"[n] | 1de34494d71548526d616ff631253502c14f5dc5 | 27,956 |
def _get_figure_size(numaxes):
"""
Return the default figure size.
Width: 8 units
Height: 3 units for every subplot or max 9 units
Return
------
(width, height)
The figure size in inches.
"""
figure_width = 8
figure_height = max(6, min(numaxes * 3, 10))
return (figur... | bb6f3a08b974cac2d5da2b69eac8653e9b41411e | 27,957 |
def _simpsons_inner(f, a, f_a, b, f_b):
"""Calculate the inner term of the adaptive Simpson's method.
Parameters
----------
f : callable
Function to integrate.
a, b : float
Lower and upper bounds of the interval.
f_a, f_b : float
Values of `f` at `a` and `b`.
Return... | e0e9170b8030f8f5c2f66927b91b034d9cd4a82f | 27,958 |
def portfolio_vol(weights, comvat):
"""
Weights -> Volatility
@ is matrix multiplication
"""
return (weights.T @ comvat @ weights) ** 0.5 | 529053e5868aad6ac106eb6997e8eb66bf42a3d6 | 27,960 |
import glob
def globimgs(path, globs:list):
"""returns a list of files with path with globing with more than one extensions"""
imgs = []
for i in globs:
imgs.extend(glob.glob(path + i))
paths = []
for path in imgs:
paths.append(path.replace("\\", "/"))
return paths | d9ffdee24fd1de496286e165333232c0b7b087be | 27,962 |
def upload_to_dict(upload):
"""Creates a Python dict for an Upload database entity.
This is an admin-only function that exposes more database information than
the method on Upload.
"""
return dict(
id=upload.id,
flake=upload.flake,
filename=upload.filename,
mimetype=... | c6fdc5b53dbbc1fa28e64fb574c5a3919f5e780e | 27,963 |
def wrong_adjunction(left, right, cup):
""" Wrong adjunction error. """
return "There is no {0}({2}, {3}) in a rigid category. "\
"Maybe you meant {1}({2}, {3})?".format(
"Cup" if cup else "Cap", "Cap" if cup else "Cup", left, right) | 263684e737a3212a1d44fcd88ba719fc9f1c07a1 | 27,965 |
def brute_force_optimized(game):
"""
Solves MasterMind by running through generators.
This saves memory but is dumb in the sense that it returns
through possible solutions in lexical order.
Returns the solution translated back into the game colors.
"""
solutions = game.create... | b408d6ae6c271d23c0ac0f92ecd915a33a994980 | 27,967 |
def mock_url_for(endpoint, **kwargs):
"""Simple mock for :func:`flask.url_for`."""
params = '/'.join(map(str, kwargs.values()))
return f'http://{endpoint}/{params}' | f95c9ae00915a0d40c2bd3199f77beee8e95383f | 27,969 |
import hashlib
def get_file_hash(filename, dhash=None, bufsize=None):
"""Return SHA256 hash for file"""
if dhash is None:
dhash = hashlib.sha256()
buffer = bytearray(128 * 1024 if bufsize is None else bufsize)
# using a memoryview so that we can slice the buffer without copying it
buffer_v... | 2309a87660d3940cf30bba5a425863c47e40c184 | 27,970 |
import os
def identify_file_extension(fpath):
"""
:param fpath:
:return:
"""
fp, fn = os.path.split(fpath)
comp_ext = fn.rsplit('.', 1)[1]
is_compressed = comp_ext in ['zip', 'gz', 'gzip', 'bz', 'bz2', 'bzip2']
if is_compressed:
ext = '.'.join(fn.rsplit('.', 2)[1:])
else:
... | 662049adfbbd36ddb472c084505fe83ebfd02d4d | 27,971 |
from datetime import datetime
def get_time_obj(date_time_str):
"""Check if date format is correct"""
try:
date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')
return date_time_obj
except ValueError as error:
print(f'Error: {error}')
return None | 77b6dbe20c1e3813ce7ebc9474cfde69c6ad6e09 | 27,972 |
import os
def path_from_root(path):
""" Returns a path computed relative to the repository root.
This is determined by computing the path to this script, then
traversing up one directory and appending the `path` argument.
"""
self_path = os.path.abspath(__file__)
self_dir = os.path.dirname(s... | e742a36d43634156139f3ce3dd50d64a1ca7e01b | 27,973 |
def count_envs(lines, ignore_chars=0):
"""Reads env counts from lines. Returns dict of {name:{env:count}}.
Assumes all name-env mappings are unique -- will overwrite counts with the
last observed count rather than adding.
"""
result = {}
for line in lines:
fields = line.split()
... | 99bbbbf07a4f3d17a951fc6823d95f73a26fbb55 | 27,977 |
def magnify_contents(contents, features):
"""
Create additional features in each entry by replicating some column
of the original data. In order for the colums to differ from the
original data append a suffix different for each new additional
artificial column.
"""
magnified_contents = []
... | ec2a43cdb280da74b44a6fec96d0708c90d03f18 | 27,978 |
def binary_search(arr, first, last, element):
"""
Function to search an element in a given sorted list.
The function returns the index of the first occurrence of an element in the list.
If the element is not present, it returns -1.
Arguments
arr : list of elements
first : position of the fir... | d006f751bf13efe04d55ab72e166ea279bef9d3d | 27,979 |
def _as_list(arr):
"""Force being a list, ignore if already is."""
if isinstance(arr, list):
return arr
return [arr] | 3af09d6aae798be53d4f99fb63f17a3fd8e0f3ed | 27,980 |
import os
def find_files_in_dirs(dirs, extensions=('.wav', '.mp3', '.aif', '.aiff', '.flac')):
"""
Find all files in the directories `dir` and their subdirectories with `extensions`, and return the full file path
Parameters
----------
dirs : list[str]
extensions : list[str]
Returns
-... | 2699df51a429cfaa65a623dfd2bdcd873ec1af49 | 27,981 |
def right_digit(x):
"""Returns the right most digit of x"""
return int(x%10) | 3f52393e9241714839e97a41f858753485cc5c89 | 27,983 |
import random
def generate_string(length: int) -> str:
"""Generates a random string of a given lentgh."""
symbols: str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
final_string: str = ""
for i in range(length):
final_string += symbols[random.randint(0, len(symbols) - 1)]
... | 9e6d4cbccf52f8abb6adf462a9a37b384a707ca3 | 27,985 |
def is_number(n):
"""
Return True if the value can be parsed as a float.
"""
try:
float(n)
return True
except ValueError as _:
return False | d9a2f8e4893b7379c2dcabf24f7f5f731423a753 | 27,987 |
import posixpath
import os
def _JoinPaths(path1, path2, gsutil_path=False):
"""Joins paths using the appropriate separator for local or gsutil."""
if gsutil_path:
return posixpath.join(path1, path2)
else:
return os.path.join(path1, path2) | 76b85abd71ec811e170ac526cd5047721f94257f | 27,988 |
import select
def get_hub():
"""
Checks whether poll is available and falls back
on select if it isn't.
Note about epoll:
Review: https://review.openstack.org/#/c/18806/
There was a problem where once out of every 30 quadrillion
connections, a coroutine wouldn't wake up when the client
... | e94a6964a40d1f311de5b5c7459d22f9427804cf | 27,990 |
def death_fraction():
"""
Real Name: b'Death Fraction'
Original Eqn: b'7/1000'
Units: b'1/Year'
Limits: (None, None)
Type: constant
b''
"""
return 7 / 1000 | cf6c2988cf79c9638f5c9e401dc5b006d275d544 | 27,992 |
def fx_ugoira_body():
"""Ugoira page data."""
with open('./tests/mock/ugoira.html') as f:
return f.read().encode('u8') | 2a9ab6295536b049d6d9a409bf1b63a832b98b18 | 27,994 |
import numpy
def meshgrid(xrange, yrange):
"""HIDE"""
xar = numpy.arange(*xrange)
yar = numpy.arange(*yrange)
shape = (len(yar), len(xar))
nx = len(xar)
ny = len(yar)
x = numpy.transpose(numpy.reshape(numpy.repeat(xar, len(yar)), (len(xar), len(yar))))
y = numpy.reshape(numpy.repeat(yar, len(xar)), shape)
... | 9d02e56126fa5b2cf84fd8f38ac87a675dca7565 | 27,995 |
from pathlib import Path
def create_flag_file(filepath: str) -> str:
"""
Create a flag file in order to avoid concurrent build of same previews
:param filepath: file to protect
:return: flag file path
"""
flag_file_path = "{}_flag".format(filepath)
Path(flag_file_path).touch()
return f... | 80ad8e181574600fcb1b9ded6e5c64c3c0d5b457 | 27,996 |
def stringify_ossl_cert(a_cert_obj):
""" try to stryingy a cert object into its subject components and digest hexification.
E.g. (with extra newline added for line-wrap):
3E:9C:58:F5:27:89:A8:F4:B7:AB:4D:1C:56:C8:4E:F0:03:0F:C8:C3
C=US/ST=State/L=City/O=Org/OU=Group/CN=Certy Cert #1... | b6fef23a1d4b8c3ab73f8f2ef9d2f033b0a25514 | 27,998 |
import os
import pickle
def load_prediction_dict():
"""Load the prediction_dict.pkl as a dict. """
cwd = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(cwd, "data/prediction_dict.pkl"), "rb") as f:
prediction_dict = pickle.load(f)
return prediction_dict | 233b7021b40ede54b4045b923a02cbc03bc42678 | 27,999 |
def _get_range_clause(column, value, bucket_interval):
"""Returns an SQL clause specifying that column is in the range
specified by value. Uses bucket_interval to avoid potentially
ambiguous ranges such as 1.0B-1.9B, which really means [1B, 2B).
"""
if value[0] == '-':
# avoid minus sign wit... | 7b0e9da8fa1ac9365e93ccd1137d519f08dadbed | 28,000 |
def mysterious_func(nums):
"""Find the holes.
input: int, number
output: int, count of how many holes
ex: getNum(300) #-> returns 2
getNum(90783) #-> returns 4
getNum(123321) #-> returns 0
getNum(89282350306) #-> returns 8
getNum(3479283469) #-> returns 5
"""
hol... | c523a516eeab76f7192a5fef1f220ddce85320b3 | 28,002 |
def createNewLoghostConfig(deviceLoghostUndoConfig):
"""
returns the needed syntax to remove the non-compliant config
"""
deviceLoghostUndoConfig.insert(0, 'system-view')
deviceLoghostUndoConfig.append('info-center enable')
deviceLoghostUndoConfig.append('info-center loghost 172.25.32.78')
r... | 4a0a023280fc1fc1754fe2a0f2b1a0d997abf9fc | 28,004 |
def zzx_compose_term(f, k):
"""Map y -> x**k in a polynomial in Z[x]. """
if k <= 0:
raise ValueError("'k' must be positive, got %s" % k)
if k == 1 or not f:
return f
result = [f[0]]
for coeff in f[1:]:
result.extend([0]*(k-1))
result.append(coeff)
return resul... | 0fa2bc791945d567fa653a2e92f772cde8b93914 | 28,006 |
def createStructuringElement(radius=1, neighborhood="8N"):
"""Create a structuring element function based on the neighborhood and the radius.
Args:
radius (integer): The radius of the structuring element excluding the center pixel.
neighborhood (string): 4N or 8N neighborhood definition around... | f99601729155fb6993a63a6317454d9359c4fd69 | 28,008 |
def get_real_coordinates(ratio, x1, y1, x2, y2):
"""
Method to transform the coordinates of the bounding box to its original size
"""
real_x1 = int(round(x1 // ratio))
real_y1 = int(round(y1 // ratio))
real_x2 = int(round(x2 // ratio))
real_y2 = int(round(y2 // ratio))
return (real_x1, ... | a2876b1c3d91b14f63ea6dca7a4dec3f8a0b6842 | 28,009 |
def get_id_update(update: dict) -> int:
"""Функция для получения номера обновления.
Описание - получает номер обновления из полученного словаря
Parameters
----------
update : dict
словарь, который содержит текущий ответ от сервера телеграм
Returns
-------
update['update_id'] :... | 68672ff86cda83a11d557ff25f1a206bd1e974b3 | 28,010 |
def earth_radius(units="m"):
"""Get earth radius in different units
:units: units
"""
if "m" == units:
return 6371000
elif "km" == units:
return 6371
elif "mi" == units:
return 3959 | 3afca64b55f14c6b964536451ee7db5093711072 | 28,012 |
def extract_some_key_val(dct, keys):
"""
Gets a sub-set of a :py:obj:`dict`.
:param dct: Source dictionary.
:type dct: :py:obj:`dict`
:param keys: List of subset keys, which to extract from ``dct``.
:type keys: :py:obj:`list` or any iterable.
:rtype: :py:obj:`dict`
"""
edct = {}
... | 80dff136ada8cfd754e1a02423e7eef364223a48 | 28,013 |
def to_hex_string(i: int) -> str:
"""
Returns the given integer as an unsigned hex representation.
:param i: The integer.
:return: The hex-string.
"""
# Check for non-negative integers only
if i < 0:
raise ValueError(f"{to_hex_string.__qualname__} only takes non-negative intege... | f41567a0f949a3447de09d43e057556ed60a56ef | 28,016 |
def ddiff_pf_contact(phi):
""" Double derivative of phase field contact. """
return -3.*phi/2. | 53150d05e6c2b6399da503b87c6ff83f2585483b | 28,018 |
def removeSpaces(string):
"""Returns a new string with spaces removed from the original string
>>> string = '1 173'
>>> removeSpaces(string)
'1173'
"""
return ''.join([char for char in string if char != ' ']) | ce00687c43ce521c14b578105bd9412c31b9817a | 28,019 |
from typing import Any
def do_nothing_collate(batch: Any) -> Any:
"""
Returns the batch as is (with out any collation
Args:
batch: input batch (typically a sequence, mapping or mixture of those).
Returns:
Any: the batch as given to this function
"""
return batch | 45cd76fb2ab1e4ad11053041a70ae9eb9c1948ec | 28,020 |
def digits():
"""
0: 1: 2: 3: 4:
aaaa .... aaaa aaaa ....
b c . c . c . c b c
b c . c . c . c b c
.... .... dddd dddd dddd
e f . f e . . f . f
e f . f e . . f . f
gggg .... gggg ggg... | 2c784bf150d1435007f9f95bd36e2b4e769ba34b | 28,022 |
def braking_index(p0=1.0, p1=1e-12, p2=1e-20):
"""
Accepts a spin period, pdot and pdotdot and returns the braking index, n.
"""
n = 2 - (p0 * p2) / p1**2
return n | 30bc7d612047a3358991f3ac0730e8660c175e64 | 28,023 |
import re
def server_version_compare(v1, v2):
"""compare Demisto versions
Args:
v1 (string): string representing Demisto version (first comparable)
v2 (string): string representing Demisto version (second comparable)
Returns:
int.
0 for equal versions.
positive i... | 12ad3c03bcef40eeb74d599aacedd195524acc7c | 28,024 |
def minutes2milliseconds(minutes):
"""
Converts minutes to milliseconds.
:param minutes: duration in minutes as string
:return: duration in milliseconds as int
"""
if minutes:
return round(float(minutes) * 60 * 1000)
else:
return 0 | fbf812340725ff841b93c270cefe3cead04664af | 28,025 |
import os
import random
import string
def testfile_playbook_generator(testdir):
"""
Return an object with ``get()`` method to generate a playbook file which
creates a test file along with expected path and content.
This is usefull when one needs one or more playbooks with simple and easy
to check... | de7bfd9ffe6fe0fcac3fb889688fb5c9c65244c7 | 28,026 |
import re
def fpd_package_installed(ctx):
"""
:param ctx
:return: True or False
"""
active_packages = ctx.send("show install active summary")
match = re.search("fpd", active_packages)
if not match:
return False
else:
return True | 5dcb095d6c39c11c714f147d1c7b350b387d06e8 | 28,027 |
import logging
def context_rewriter(function, rewrite=None, **kwargs):
"""Change arguments for the function.
Args:
function: callable for which to change arguments.
rewrite: dictionary with rewrite params in format new_key -> old_key
kwargs: the rest of the arguments (to be rewritten)... | 1b1c46fc6fcb61ed8f31642250574ba55336d31f | 28,029 |
def _load_table_data(table_file):
"""Load additional data from a csv table file.
Args:
table_file: Path to the csv file.
Returns:
header: a list of headers in the table.
data: 2d array of data in the table.
"""
with open(table_file, encoding="utf-8") as f:
lines = f... | c1f1ee84c2f04a613616897b897a01ee2364b98c | 28,030 |
def tab_error():
"""Mixing tabs and spaces for indentation."""
try:
exec('if True:\n pass\n\tpass')
except TabError:
return "mixed tab and space" | f0cefd9435dcea54e5e4c2447817c2d68b3532ea | 28,031 |
def backlog_color(backlog):
"""Return pyplot color for queue backlog."""
if backlog < 5:
return 'g'
if backlog > 24:
return 'r'
return 'y' | 551413b28c9c9736ea19e63c740f9c28613784ee | 28,032 |
import zlib
def gzip_entropy(s):
"""
Return the "GZIP" entropy of byte string `s`. This is the ratio of
compressed length to the original length. Because of overhead this
does not gives great results on short strings.
"""
if not s:
return 0
if isinstance(s, str):
s = s.enc... | 4642a79e85f3fd0adb117bc20811d7a325b14c5c | 28,033 |
from datetime import date
def jqueryUIDates(datestr):
"""Preps dates for jqueryUI widgets"""
#03/02/2011
datestr = datestr.rstrip('?format=csv')
chunks = datestr.split('/')
month = int(chunks[0])
day = int(chunks[1])
year = int(chunks[2])
return date(year, month, day) | a924d99da1ec0687bfc97391248e80d2657c0aca | 28,034 |
import requests
def get_url_content(url):
"""
返回url对应网页的内容,用于分析和提取有价值的内容
:param url: 网页地址
:return: url对应的网页html内容
"""
return requests.get(url).text | 07f2e7ce8c365e601fd7ed4329f04e6ae56e214f | 28,035 |
def reference_repr(self):
"""The string representation compatible for Reference fields."""
self.ensure_one()
return "{name},{id}".format(name=self._name, id=self.id) | 6f8e1e848cd6c0f57250500dbbc565a313bcd1f2 | 28,037 |
def fexists(sftp, path):
"""os.path.exists for paramiko's SCP object
"""
try:
sftp.stat(path)
except IOError:
return False
else:
return True | 3cff765bbc8cc3f5ed3a3165473961ebfc04ec94 | 28,038 |
import numpy
def makeSemBins(semArray, nBins):
"""
Makes the semantic bins.
A spot in semRows[i] and semCols[i] are the indices of words that
fall in the ith semantic bin
"""
# Split up the semantic space into equal segments
semBins = list(numpy.linspace(semArray.min(),semArray.max(),nBin... | 51adaf43816900ac2c5cc0db64f5fa0659c2792c | 28,041 |
import random
def random_guesser_v1(passage):
"""Takes in a string and returns a dictionary with
6 keys for the binary values representing
features of the string, and another six keys
representing the scores of those features.
Note: for the scores, 0 represents no score,
while -1 represents '... | b2759839fcdd59d36aa2bf6643750970affc77a1 | 28,042 |
import os
import sys
def this_path(this_file=None):
"""
Root of the operation.
Parameters
----------
this_file: str
Filename, default is this script location.
Returns
-------
str: path
"""
exec_dir = os.path.dirname(os.path.realpath(sys.argv[0] or 'whocares'))
... | 2eb816486175c304d46cf1b26e3d4d43b94fde48 | 28,043 |
def most_similar(train,
test,
distances):
"""
get the most similar program name
Parameters
----------
train: list
a list of string containing names of training programs
test: list
a list containing names of test progra... | 324722574bbbdbda61e7e4bc65669c2ce9674630 | 28,045 |
def decimal_hours(timeobject, rise_or_set: str) -> float:
"""
Parameters
----------
timeobject : datetime object
Sunrise or -set time
rise_or_set: string
'sunrise' or 'sunset' specifiying which of the two timeobject is
Returns
-------
float
time of timeobject in d... | 44fe260abf8751cb78cf6e484dbf223d05233713 | 28,046 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.