content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import re
def check_english_str(string):
"""
检测英文字符串
"""
pattern = re.compile('^[A-Za-z0-9.,:;!?()_*"\',。 ]+$')
if pattern.fullmatch(string):
return True
else:
return False | 2a1ce45b44bf4b10c7c433bddbc83ad1826eb448 | 682,958 |
def subtract(fml1, fml2):
""" the difference between two molecular formulas
"""
atms = set(fml1) | set(fml2)
diffs = {}
for atm in atms:
cnt1 = fml1[atm] if atm in fml1 else 0
cnt2 = fml2[atm] if atm in fml2 else 0
if cnt1 != cnt2:
diffs[atm] = cnt1 - cnt2
ret... | dd8ba2c2e308c69eba59bb2745818ee8175f161b | 682,959 |
def createECGGraph(df, plot_index, ecg_class, mi_class):
"""
Method to create the line plot graph object
@param df - The intermediate dataframe with predicted classes
@param plot_index - The index of the data file to be plotted
@param ecg_class - The ecg calss identified for the index being plotted
... | 692e0cc55010489641affd6476fe971877ee250e | 682,960 |
def finalize_model(input_model):
"""
Extracts string from the model data. This function is always the last
stage in the model post-processing pipeline.
:param input_model: Model to be processed
:return: list of strings, ready to be written to a module file
"""
finalized_output = []
for m... | 88c03ed9b4b6158895ac6e88ef27b573de2b0027 | 682,961 |
from typing import OrderedDict
def load_object(worksheet):
"""
Converts worksheet to dictionary
Args:
object: worksheet
Returns:
object: dictionary
"""
#d = {}
#d = OrderedDict()
d = OrderedDict()
for curr_col in range(0, worksheet.ncols):
liste_elts = work... | d9c70f6805fbe906042d9a94293b4b989bee02b1 | 682,962 |
import base64
def fast_execute_script(client):
"""
快速执行脚本函数
"""
script_content = base64.urlsafe_b64encode(b"df -h /|sed '1d'|awk '{print $5}'|sed 's/%//g'|sed -n 1p")
script_param = base64.urlsafe_b64encode(b'/')
ip_list = [
{
"bk_cloud_id": 0,
"ip": "10.0.1... | 2fd93b7284fc7cece77de7e3a6c9383fae84ebe1 | 682,964 |
def obj_to_list(sa_obj, field_order):
"""Takes a SQLAlchemy object - returns a list of all its data"""
return [getattr(sa_obj, field_name, None) for field_name in field_order] | 25882acc3ec70d3d26f53bb6519b4a24752ca7a1 | 682,965 |
import re
def join_subtraction(text):
"""Merges lines that are separated because of a line starting with
dash, when it's actually a subtraction.
Args:
text (string): markdown text that is going to be processed.
Returns:
string: text once it is processed.
"""
subtraction_regex = re.compile(r'(\d) *\n+ *(-... | 09036fc9f28e2c1ddd63c54e600fd4b7b96d0602 | 682,966 |
def valid_answer(response, acceptable, statement):
"""Check value and iterate until valid or too many attempts.
:param response: response from user
:param acceptable: tuple or list; acceptable values
:param statement: string; response to... | 4cbd8943e66fc0f3c010b9f86598f6b1235beba9 | 682,967 |
import copy
def _parse_params(params, default_params):
"""Parses parameter values to the types defined by the default parameters.
Default parameters are used for missing values.
"""
# Cast parameters to correct types
if params is None:
params = {}
result = copy.deepcopy(default_params)
for key, valu... | 3c404086e929c6f41f4bf01d32cc79e2157994b5 | 682,968 |
def div(n):
"""
Just divide
"""
res = 10 / n
return res | 3acbfa2c2defd172e90f324d34d916158965d41a | 682,970 |
def solr_url():
"""Return Solr URL."""
return 'solr://127.0.0.1:8983/solr' | dd38fc4c282ce36ead4b27290ec1323b2674d1e4 | 682,971 |
from typing import Dict
import sys
import platform
import pkg_resources
def get_system_spec() -> Dict[str, str]:
"""Collect information about the system and installation."""
if sys.platform == 'darwin':
system_info = 'macOS {} {}'.format(
platform.mac_ver()[0],
platform.archite... | fb4599e3ccb2aa99206b00a96941de915a04efa6 | 682,972 |
def _detJ_3D(J):
""" manually compute determinant of 3x3 matrices in J format """
detJ = J[:,0,0,:] * (J[:,1,1,:] * J[:,2,2,:] - J[:,2,1,:] * J[:,1,2,:]) \
- J[:,1,0,:] * (J[:,0,1,:] * J[:,2,2,:] - J[:,2,1,:] * J[:,0,2,:]) \
+ J[:,2,0,:] * (J[:,0,1,:] * J[:,1,2,:] - J[:,1,1,:] * J[:,0,2,... | 90976d25a42882d85c909c792c55a20d1e6acb8f | 682,973 |
def resize_egomotion(egomotion, target_size):
"""Transforms camera egomotion when the image is resized.
Args:
egomotion: a 2-d transformation matrix.
target_size: target size, a tuple of (height, width).
Returns:
A 2-d transformation matrix.
"""
del target_size # unused
return egomotion | 8df4a8046b1eaeab4c90d1324a31799b04590c99 | 682,974 |
def getConstructors(jclass):
"""Returns an array containing Constructor objects reflecting all the public
constructors of the class represented by this Class object."""
return jclass.class_.getConstructors()[:] | c7dc893002ab913b55ce6e6e121af322fd6ab7b6 | 682,975 |
def ask_move(player: int) -> int:
"""Ask the player which pawn to move. Returns an integer between 0 and 3."""
while True:
try:
pawn_number = int(input(f"Player {player}: Choose a piece to move (0-3): "))
except ValueError:
continue
else:
if 0 <= paw... | b5b23052fe24078f44ff4bddb52e4bbd693807d0 | 682,976 |
def calc_mean_dists(Z, node_index, out_mean_dists):
"""
Calculates the mean density of joins
for sub-trees underneath each node
"""
N = Z.shape[0] + 1 # number of leaves
left_child = int(Z[node_index, 0] - N)
right_child = int(Z[node_index, 1] - N)
if left_child < 0:
left_ave... | f2ffd9ef3dc3118a07b4269053469fccda310bf8 | 682,978 |
def strip_outer_whitespace(text):
"""Strip surrounding blank lines in a multiline string.
This does not affect first-line indentation, or trailing whitespace on the
last line.
"""
lines = text.rstrip().splitlines()
i = 0
try:
while not lines[i].strip():
i += 1
except... | 03ad2d8af159d31cb534898d240268a5f30ea65b | 682,979 |
import os
def locate_file(file_name: str, executing_file: str) -> str:
"""
File must exist
:type file_name: str|unicode
:type executing_file: str|unicode
:return: str
"""
# if executing_file is None:
# executing_file = __file__
file_path = os.path.join(
os.path.dirname(... | 771b43b1d3c29a3c4a9ff1e086999ec657b555c6 | 682,980 |
def find(arr, icd_code=False):
"""Search in the first column of `arr` for a 'Yes' and return the respective
entry in the second column."""
search = [str(item) for item in arr[:,0]]
find = [str(item) for item in arr[:,1]]
try:
idx = [i for i,item in enumerate(search) if "Yes" in item]
... | 87fe9d1e98a4feece19222e8a84a3e6ffb90540d | 682,981 |
from typing import IO
def open_file_or_stream(fos, attr, **kwargs) -> IO:
"""Open a file or use the existing stream. Avoids adding this logic to every function that wants to provide
multiple ways of specifying a file.
Args:
fos: File or stream
attr: Attribute to check on the ``fos`` ob... | 9f7955a0ced009039095f35c7f7deb1eb25f97b9 | 682,983 |
def find_max_sub(l):
"""
Find subset with higest sum
Example: [-2, 3, -4, 5, 1, -5] -> (3,4), 6
@param l list
@returns subset bounds and highest sum
"""
# max sum
max = l[0]
# current sum
m = 0
# max sum subset bounds
bounds = (0, 0)
# current subset start
s = 0
... | ebf42b58f9fea4276d0ba7d15b02faed4558efc6 | 682,984 |
def _index_to_bitstring(index, n, big_end=False):
"""Transfor the index to bitstring"""
s = bin(index)[2:].zfill(n)
if big_end:
return s[::-1]
return s | 25f9699235e0426e7d8279b4092b943fd531822b | 682,985 |
def sanitize_path(path):
"""
This applies only to Windows paths.
"""
return path.translate(None, r'<>"/|?*' + ''.join(map(chr, range(0, 31)))) | 54be308ad660dc54fe5a9e051ed7744ae8cd86f2 | 682,986 |
def as_paired_ranks(x, y):
"""return as matrix of paired ranks"""
n = len(x)
paired = list(zip(x, y))
x = list(x)
y = list(y)
x.sort()
y.sort()
rank_val_map_x = dict(list(zip(x, list(range(n)))))
rank_val_map_y = dict(list(zip(y, list(range(n)))))
ranked = []
for i in range(n... | 961b9fcd9ebc8a911e73f463befd32766f68a521 | 682,987 |
def f_W(m_act, n, Wint):
"""
Calculate shaft power
"""
return m_act * n - Wint | 4e1182c1fd55a0fb688a7146038cf7c2d0916a3c | 682,988 |
def _formatDict(d):
""" Returns dict as string with HTML new-line tags <br> between key-value pairs. """
s = ''
for key in d:
new_s = str(key) + ": " + str(d[key]) + "<br>"
s += new_s
return s[:-4] | be9749e5f69c604f3da95902b595f9086b01baa5 | 682,989 |
from typing import List
def clusters_list(num_clusters: int) -> List[list]:
"""Create a list of empty lists for number of desired clusters.
Args:
num_clusters: number of clusters to find, we will be storing points in these empty indexed lists.
Returns:
clusters: empty list of lists.
... | d6130f67e72d1fd31def20f2bac1fd81c6878ba5 | 682,990 |
def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal places"""
places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""
count = 0
formatted = ... | 6d6f2412fa94857f77043a30ec2a14f809c5f039 | 682,991 |
import pandas
def format_dates(df, columns):
"""Convert UNIX timestamp columns to datetime"""
if df.size > 0:
df[columns] = df[columns].apply(lambda v: pandas.to_datetime(v, unit="s"))
return df | b22d6c6d41af86971fd88dfaddc963b4f5076a5b | 682,992 |
def unflatten(structure, schema):
"""doc"""
start = 0
res = []
for _range in schema:
res.append(structure[start:start + _range])
start += _range
return res | d23492e1eb45ba23567400b27b607d9df6a7cf90 | 682,994 |
def get_cdm_cluster_location(self, cluster_id):
"""Retrieves the location address for a CDM Cluster
Args:
cluster_id (str): The ID of a CDM cluster
Returns:
str: The Cluster location address
str: Cluster location has not be configured.
str: A cluster with an ID of {cluster_id... | f8d3aa787b625e5461fd22eb11f2495a33bace0b | 682,995 |
import random
def _paired_random_crop(img_gts, img_lqs, h_patch, w_patch, if_center=False):
"""Apply the same cropping to GT and LQ image pairs.
scale: cropped lq patch can be smaller than the cropped gt patch.
List in, list out; ndarray in, ndarray out.
"""
if not isinstance(img_gts, list):
... | 88fb3e74dbd5642258c5d91ccba6555ce1730fb5 | 682,997 |
def is_session_dir(path):
"""Return whether a path is a session directory.
Example of a session dir: `/path/to/root/mainenlab/Subjects/ZM_1150/2019-05-07/001/`
"""
return path.is_dir() and path.parent.parent.parent.name == 'Subjects' | 474096a74068222ca8672fed838dc2703668648e | 682,998 |
import re
def safeStripPort(address):
"""
Strip port from address\n
Properly strips on IPv6, IPv4, and FQDN addresses
:param address: address to strip port from
:type address: str
:return: address with port stripped
:rtype: str
"""
match = re.searc... | 25dfb81779f14d688a1423f394243116ecfa4f38 | 682,999 |
import torch
def isinf(input):
"""
In ``treetensor``, you can test if each element of ``input``
is infinite (positive or negative infinity) or not.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.isinf(torch.tensor([1, float('inf'), 2, float('-inf... | 5800b8bf1389e8be347ffe0b9f4132690094b430 | 683,000 |
def coalesce(*xs):
"""
Coalescing monoid operation: return the first non-null argument or None.
Examples:
>>> coalesce(None, None, "not null")
'not null'
"""
if len(xs) == 1:
xs = xs[0]
for x in xs:
if x is not None:
return x
return None | 2210de29cb2fbc9571bd4bed9fc8a89feddbb8c8 | 683,001 |
def first(it):
"""Return first element in iterable."""
return it.next() | dbda71c8693fe8e84398a597baa93f2d00ea4f8a | 683,002 |
import platform
def islinux():
"""Returns true if host OS is Linux."""
return "linux" in platform.platform().lower() | 7d298b5d8f50903cc59917e1e380acbdcf5bfd79 | 683,003 |
from typing import Callable
def curry_explicit(func: Callable, arity: int) -> Callable:
"""
Transforms function from several arguments to function that takes arguments sequentially, for example:
f(a, b, c, d) -> f(a)(b)(c)(d)
"""
def inner_fun(*args) -> Callable:
if len(args) == arity:
... | 6d6b7a8fd3ba1e14a5ff0b73260260474475a93f | 683,004 |
def get_valid_scaler_class():
"""Return list of implemented xscaler objects."""
scaler_classes = ['GlobalStandardScaler', 'TemporalStandardScaler',
'GlobalMinMaxScaler', 'TemporalMinMaxScaler',
'SequentialScaler']
return scaler_classes | 7a50a63a4d48ecf5c67bdea09b4fb7ce6134795d | 683,005 |
def quicksort(arr):
"""
Fuction to do quicksort.
:param arr: A list of element to sort.
"""
less = []
pivotList = []
more = []
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
for i in arr:
if i < pivot:
less.append(i)
... | 7f24db52c321eee3d3f2807573a7d9f3354d28d3 | 683,006 |
import re
def __is_rut_perfectly_formatted(rut: str) -> bool:
"""
Validates if Chilean RUT Number is perfectly formatted
Args:
rut (str): A Chilean RUT Number. For example 5.126.663-3
Returns:
bool: True when Chilean RUT number (rut:str) is perfectly formatted
** Only valida... | 42fbeb3968a1c2536e44154ab9e690817a57ccd4 | 683,007 |
def ru(value, quantitative):
"""возвращает строку со склоненным существительным"""
if value % 100 in (11, 12, 13, 14):
return quantitative[2]
if value % 10 == 1:
return quantitative[0]
if value % 10 in (2, 3, 4):
return quantitative[1]
return quantitative[2] | a8b15d6036962669e523cb6f789edaca9ebddb23 | 683,008 |
import os
def get_rcfilename():
""" Returns the full path of the acmd config file. """
home = os.path.expanduser("~")
rcfilename = "{home}/.acmd.rc".format(home=home)
return rcfilename | 9710939c150a86952bacab8034a5422f8464b88c | 683,009 |
import os
def choice(directory, files):
"""
:param directory: directory of files in.
:param files: list of file be choice
:return: first existed path
"""
for name in files:
fpath = os.path.join(directory, name)
if os.path.exists(fpath):
return fpath
return None | 27a7274d11b7bcf9ac93484ee9315e30c6a60408 | 683,010 |
import os
def user_data():
"""
return: location_name, crs, grass_version, main_dir, grass_dir, sen_down_dir, sen_processed_dir, subset_dir,
boundary_shape
self-explanatory returns, for acces through the Path classes "GrassData" and "Paths"
"""
#################### USER DEFINED ... | 61714b55315a74ad32f554263f451aad9cb58cb3 | 683,011 |
import six
def to_iter(e):
"""转换可迭代形式"""
if isinstance(e, (six.string_types, six.string_types, six.class_types, six.text_type,
six.binary_type, six.class_types, six.integer_types, float)):
return e,
elif isinstance(e, list):
return e
else:
return e | ce0ba0ccf03d1d1cc131f498a2e4c0f7170490d1 | 683,012 |
def FilterListClass(objclass,inlist,exclude=False):
"""
select list elements that [NOT when exclude=True] belong to (a group of) classes.
Arguments:
objclass --> class name or tuple of class name
"""
if exclude==True:
return [lm for lm in inlist if not isinstance(lm,objclass)]
e... | d10834ab98d5b943a23516dcef5a0cc2bb586ccb | 683,014 |
def task_to_json_list_of_list(df_task):
"""
Returns a list of list (without columns name) like:
[['Saint Auban', 'Go', 'Coupe S',
'3 Eveches', 'DORMILLOUSE FORT', 'Saint Auban'],
[44.054901123046875, 44.01508712768555, 44.0536003112793,
44.288883209228516, 44.41444778442383, 44.054901123... | 8da85ca87469b9c22dfca52a56a7205179daba67 | 683,015 |
def create_single_object_response(status, object, object_naming_singular):
"""
Create a response for one returned object
@param status: success, error or fail
@param object: dictionary object
@param object_naming_singular: name of the object, f.ex. book
@return: dictionary.
"""
return {"... | 9626fc5594e5677196454594e719ebf415fc1ebc | 683,016 |
import argparse
def parse_args():
"""Parses arguments."""
parser = argparse.ArgumentParser(
description='Train boundary with given data and labels.')
parser.add_argument('data_path', type=str,
help='Path to the data for training.')
parser.add_argument('scores_path', type=str,
... | c7d4461227f7d5200bcaf941f7dc2b105c2dd3b5 | 683,017 |
def bubble_sort(iterator):
"""
Here’s what our Bubble sort algorithm might look like, in Python3:
"""
length = len(iterator) -1
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(length):
if iterator[i] > iterator[i+1]:
is_sorted =... | 8555fe104ba66f66ac33f9a9ae371ae579752de5 | 683,019 |
def _query_item(item, query_id, query_namespace):
"""
Check if the given cobra collection item matches the query arguments.
Parameters
----------
item: cobra.Reaction or cobra.Metabolite
query_id: str
The identifier to compare. The comparison is made case insensitively.
query_namesp... | f3e418ab5cf2830d2c1dd6b4e83275e14dc8f4c8 | 683,020 |
def num2str(x):
"""Converter for numeras to nice short strings.
"""
n = ""
if x >= 0:
n += "+"
else:
n += ""
n += "{:0.1e}".format(x)
return n.replace("e", "") | 56b695e66203ab307426bc9b9a9a38d899468dc9 | 683,021 |
import re
def strip_html_tags(text):
"""Strip HTML tags in a string.
:param text: String containing HTML code
:type text: str
:return: String without HTML tags
:rtype: str
:Example:
>>> strip_html_tags('<div><p>This is a paragraph</div>')
'This is a paragraph'
>>> strip_html_ta... | e7b060bdea980cfee217d81feccf56cf964f5557 | 683,022 |
import glob
import re
def list_all_sys_net_if():
"""
List the machine's network interfaces and return their name in a list of strings
\return A list of network interfaces (strings)
"""
sys_net_path = glob.glob('/sys/class/net/*')
# Now remove the /sys/class/net prefix, keep only the interface ... | 1efb5549f40cd530be1868c46ebe1c27542d789c | 683,023 |
def get_next_open_row(board, col):
"""
Finds the topmost vacant cell in column `col`, in `board`'s grid.
Returns that cell's corresponding row index.
"""
n_rows = board.n_rows
# check row by row, from bottom row to top row ([0][0] is topleft of grid)
for row in range(n_rows - 1, -1, -1):
... | 7f6e45a0c136e53482a10264fc88020168056d8a | 683,024 |
def read_names(fh):
"""Read taxonomic names from a file.
Parameters
----------
fh : file handle
Taxon name mapping file.
Returns
-------
dict
Taxon name map.
Notes
-----
Can be NCBI-style names.dmp or a plain map of ID to name.
"""
names = {}
for li... | a84d532db99fe1477d7a1b32713775b65fe7ae07 | 683,025 |
import csv
def proc_attendees(att_file, config):
"""Opens the attendee list file, reads the contents and collects the
desired information (currently first name, last name and email addresses)
of the actual attendees into a dictionary keyed by the lowercase email
address. This collection is returned.
... | e9a4a59ec557c999b2ff423df8a02ca04a4545a8 | 683,026 |
import re
def _parse_arn(arn):
"""
ec2) arn:aws:ec2:<REGION>:<ACCOUNT_ID>:instance/<instance-id>
arn:partition:service:region:account-id:resource-id
arn:partition:service:region:account-id:resource-type/resource-id
arn:partition:service:region:account-id:resource-type:resource-id
Returns: r... | c267a63cb82ce3c9e2dd0dadaea3ac5a53630d53 | 683,027 |
def get_product_linear_bias(sets, bound):
""" Return the product of the input sets (1-D combinatorial)
@param sets: Input sets
@type sets: List
@param bound: Max number of the product
@type bound: Int
@return: Product (partial) of the input sets
@rtype: List
"""
# check not emp... | 2a4ec4fd200ccfdf0c27baa14de93466adaa0389 | 683,028 |
def cast_uint(value):
"""
Cast value to 32bit integer
Usage:
cast_int(1 << 31) == 2147483648
"""
value = value & 0xffffffff
return value | 241346691d0931dd5ee8d2cf4f6ead0212835020 | 683,029 |
from pathlib import Path
def is_subpath(parent_path: str, child_path: str):
"""Return True if `child_path is a sub-path of `parent_path`
:param parent_path:
:param child_path:
:return:
"""
return Path(parent_path) in Path(child_path).parents | 6852efb5eede8e16871533dca9d0bf17dd7454bb | 683,030 |
def getIPaddr(prefix):
"""
Get the IP address of the client, by grocking the .html report.
"""
addr="Unknown"
f=open(prefix+".html", "r")
for l in f:
w=l.split(" ")
if w[0] == "Target:":
addr=w[2].lstrip("(").rstrip(")")
break
f.close()
return(addr... | de1e80e978eeef8ca74b05a7a53e0905e79a29e0 | 683,031 |
def squelch(prop_call, default=None, exceptions=(ValueError,)):
""" Utility function that wraps a call (likely a lambda function?) to return a default on specified exceptions """
if not exceptions:
return prop_call()
try:
return prop_call()
except exceptions:
return default | b39b4c53807be59e421c18d1a30d418ce23fef0f | 683,032 |
import re
def clean_text(text, max_words=None, stopwords=None):
"""
Remove stopwords, punctuation, and numbers from text.
Args:
text: article text
max_words: number of words to keep after processing
if None, include all words
stopwords: a list of words to skip d... | c5fe9bb01928355d81b566ad4ebee1232ebae810 | 683,033 |
import argparse
from pathlib import Path
def exist_dir():
""" Check for existing directory """
class DirCheck(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
p = Path(values)
if not p.exists():
msg='Argument "{f} denoting the... | da901d2dab48e7236f0f336e2472edb53e75f9b1 | 683,034 |
def c_array(centroids):
"""
Returns new dictionary with a ready-to-copy string representation of data for use as array in C
"""
c_centroids = {}
for label in centroids.keys():
c_centroid = str(centroids[label].tolist()).replace('[', '{')
c_centroid = c_centroid.replace(']', '}')
... | ff3bf9c38c1866f020f053635494c001c0e775c8 | 683,035 |
def exempt(a, b):
"""
exempts b from a
"""
if a is None:
return set()
if b is None:
return a
return set(a) - set(b) | 65e72502189de3e94ca54c387963be5769094874 | 683,036 |
def check_file(fname):
"""
('filepath')->file contents
Opens given file path (or file name if file is in same folder as proj9)
reads contents if able, and prints those contents if able.
returns none
>>> check_file("\\Users\\Hufflebluff\\Example.txt")
Example file contents line 1
Exampl... | 8b5916652e346aa4cfda3c99902c712102a636fc | 683,037 |
def CalcUi(U2, U1):
"""Return the backward differencing result of the dependent var."""
return U2 - U1 | 108c2b95b786f7ac3c9dd29997e81ad88e9dc42c | 683,038 |
def array_value(postiion, arr):
"""Returns the value at an array from the tuple"""
row, col = postiion[0], postiion[1]
value = arr[row, col]
return value | d8a83ef4870d304fefe33220e38b78c8c8afee56 | 683,039 |
def get_padding(ks, s, hw):
""" choose padding value to make sure:
if s = 1, out_hw = in_hw;
if s = 2, out_hw = in_hw // 2;
if s = 4, out_hw = in_hw // 4;
"""
if hw % s == 0:
pad = max(ks - s, 0)
else:
pad = max(ks - (hw % s), 0)
if pad % 2 == 0:
return pad // 2
... | 1fffec0037275bb71566b1967015f1ed7fb6a9bb | 683,040 |
def generate_header_list(unsorted_keys):
"""Return a list of headers for the CSV file, ensuing that the order of the
first four headers is fixed and the remainder are sorted."""
unsorted_keys.remove('identifier')
sorted_remainder = sorted(unsorted_keys)
header_list = ['identifier', 'label1', 'lab... | 18cb8d4be40e16da1b3c05070494dc791a7e4e02 | 683,041 |
def hamming_distance(str1, str2):
"""Calculate the Hamming distance between two bit strings
Args:
str1 (str): First string.
str2 (str): Second string.
Returns:
int: Distance between strings.
Raises:
ValueError: Strings not same length
"""
if len(str1) != len(str2... | 8ca962c82b1321c32c34052ccf8f9a74d0f9245d | 683,042 |
import requests
def get_all_topk_articles(day_range):
"""
Accepts a list of dicts with year, month, and day values
Returns a dictionary (article titles as keys)
with all articles that were in the topk list during those dates
and the pageview counts for each of the dates the article appeare... | 4dfad93b94ef4efed2d9018b62bee721edf54b89 | 683,043 |
def mecab_eval(sys_data, ans_data):
"""
This script is written by referring to the following code.
https://github.com/taku910/mecab/blob/master/mecab/src/eval.cpp
"""
if not len(sys_data) == len(ans_data):
raise AssertionError("len(sys_data) != len(ans_data)")
num_sents = len(sys_data)
... | 6bd3ba380c132314dfabfa4ca85373d5c077424b | 683,044 |
def sync(printer, ast):
"""Prints a synchronization "chan(!|?)"."""
channel_str = printer.ast_to_string(ast["channel"])
op_str = ast["op"]
return f'{channel_str}{op_str}' | ae3c9045a48a169e37602df13eb88da8ac9a65b6 | 683,045 |
from datetime import datetime
import os
def getDBBackupPath(backupDir: str) -> str:
"""Get a database backup path."""
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
dbFile = f"norsebooks.backup.{timestamp}.json"
dbPath = os.path.join(backupDir, dbFile)
return dbPath | bc38032185725159e648d375ad0ad755de78e1f3 | 683,046 |
from typing import Union
from typing import List
import pickle
def parse_list(data: Union[str, List],
indicator: int = 0,
query=['MCF7']) -> List:
"""Filter the data based on compound, cell line, dose or time
This function takes the directory of dataset, indicator that indicates
w... | 67a0fa75c659a5bcbff2aa44e131a56096bf8865 | 683,047 |
def convert_list_in_str(list_in: list) -> str:
"""Обособляет каждое целое число кавычками, добавляя кавычку до и после элемента
списка, являющегося числом, и дополняет нулём до двух целочисленных разрядов.
Формирует из списка результирующую строковую переменную и возвращает."""
str_out = ""
... | a2a1253ca267b24586458136c5603cc56bc10700 | 683,048 |
import os
def get_user_config_file():
"""Returns the path where the user-level configuration file is stored"""
return os.path.expanduser("~/.igraphrc") | c8d6dd47ec0260bbbb99983183864461012a2f69 | 683,049 |
def list_creator(nbBins):
"""Create the necessary number of lists to compute colors feature extraction.
# Arguments :
nbBins: Int. The number of bins wanted for color histogram.
# Outputs :
lists: A list of 2*3*`nbBins` empty lists.
"""
nbLists = 2*3*nbBins
return [[] for _ in ... | a0f8d3977583f300d5f0ca0f5f1666f8749a1899 | 683,050 |
def compress(string):
"""Creates a compressed string using repeat characters.
Args:
string_one: any string to be compressed.
Returns:
A compressed version of the input based on repeat occurences
Raises:
ValueError: string input is empty.
"""
if string:
... | 2bb483b0961cf5e6f4736aff1ab08a5ffb6b5ccc | 683,051 |
def map_squares(numbers):
"""
:param numbers: list of numbers
:return: square of the numbers
"""
return list(map(lambda x: x ** 2, numbers)) | 2287477e56cb5f8132f62dfc9a616793aa6e2910 | 683,052 |
def get_flight_distance(cassandra_session, origin, dest):
"""Get the distance between a pair of airport codes"""
# query = cassandra_session.prepare(
# """
# SELECT "Distance" FROM agile_data_science.origin_dest_distances
# WHERE "Origin"=? AND "Dest"=?
# LIMIT 1
# ALLOW FILTERING;
# """
... | 2edc45ddee8bd80f4dfc5d73c2f43eac27ce8a24 | 683,053 |
import sys
import os.path
def to_posix(fname):
"""
Convert a path to posix-like format.
:param str fname: The filename to convert to posix format.
:return: The filename in posix-like format.
:rtype: str
"""
if sys.platform == "win32": # pragma: nocover
if os.path.isabs(fname):
... | a2dd1de325a75502f051156b33ef62341a2fff29 | 683,054 |
def extend_flight_distance(distance: float) -> float:
"""Add factor to shortest flight distance to account for indirect flight paths
Following https://www.icao.int/environmental-protection/CarbonOffset/Documents/Methodology%20ICAO%20Carbon%20Calculator_v11-2018.pdf
section 4.2 we add a correction factor to... | a4dedcbfcba663be757ba97cd28b6afac1c77a01 | 683,055 |
def triwhite(x, y):
""" Convert x,y chromaticity coordinates to XYZ tristimulus values.
"""
X = x / y
Y = 1.0
Z = (1-x-y)/y
return [X, Y, Z] | dd2dd418c4643e10d3b9fd685bd6df1a3cc5afd7 | 683,056 |
import os
import codecs
def has_shipibo_suffix(str):
""" Function that returns the possible existence of a shipo suffix in a a word
:param str: word to evaluate
:type str: str
:returns: True or False
:rtype: bool
:Example:
>>> import chana.lemmatizer
>>>... | c23df6c220ed2b3d77920ae0033fbf49d132651d | 683,057 |
def get_ode_params(**alt_params):
"""General Ode simulation params, not filename specific"""
params = {'disableUnits': True, # disable unit checking
# set sim params
'startTime': 0,
'stopTime': 30,
'timestep': 0.001,
'period': 0.1,
... | d7d9eea98982c4dfc5ea03d3e0a0b9915c32e576 | 683,058 |
def create_header(args):
"""Constructs the header row for the csv"""
header = ["Propublica Number", "Org Name", "Tax Year", "Data Source",
"PDF URL"]
if args.totalrev:
header.append("Total Revenue")
if args.totalexp:
header.append("Total Functional Expenses")
if args.ne... | b47dd3254262624e63b32cd269bef8890883707d | 683,059 |
def predict_large_image(model, input_image):
"""Predict on an image larger than the one it was trained on
All networks with U-net like architecture in this repo, use downsampling of
2, which is only conducive for images with shapes in powers of 2. If
different, please crop / resize accordingly to avoid... | f762c997c953487df32e111babfb25059a2d344d | 683,060 |
def make_subrequest(request, path):
""" Make a subrequest
Copies request environ data for authentication.
May be better to just pull out the resource through traversal and manually
perform security checks.
"""
env = request.environ.copy()
if path and '?' in path:
path_info, query_s... | 1927b4469ded5ff157b8327c886f78902f08684d | 683,061 |
import errno
import ctypes
import os
import logging
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
# http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
if os.name == 'posix':
# OS X and Linux
if pid < 0:
... | 1bc416094323d1e4dbf568406925617ee87f6683 | 683,062 |
def termino_aerodinamico(tmed, vv_promedio, c_sicrometrica, p_media_vapor, pendiente_curva, c_sicrometrica_modificada, p_vapor_real):
"""
calcula el término aerodinámico de la ecuación de PM en mm/día
param: tmed : temperatura media
param: vv_promedio : velocidad del v... | 600c82fff834eed34f9b4a76a4be9ab2ef67e34c | 683,064 |
import logging
def get_logger(*components) -> logging.Logger:
"""Get a logger under the app's hierarchy."""
name = '.'.join(['skipscale'] + list(components))
return logging.getLogger(name) | 9060f07091ac19ae90a61b69b2eca3ef1daf1d05 | 683,065 |
def boto3_tag_list_to_ansible_dict(tags_list, tag_name_key_name=None, tag_value_key_name=None):
""" Convert a boto3 list of resource tags to a flat dict of key:value pairs
Args:
tags_list (list): List of dicts representing AWS tags.
tag_name_key_name (str): Value to use as the key for all tag k... | e2f458ea33620494c8c629586d004ada7b86c607 | 683,066 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.