content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import hashlib
def _get_file_sha256_hash(file_path):
"""
Takes a file and returns the SHA 256 hash of its data
Args:
file_path (str): path of file to hash
Returns: (str)
"""
sha256hash = hashlib.sha256()
chunk_size = 8192
with open(file_path, "rb") as f:
while True:
... | 34db2c1a35bb34dd192f3ea8ac22b475d987619e | 635,258 |
def CheckProg(context, prog_name):
"""
Configure check for a specific program.
Check whether program prog_name exists in path. If it is found,
returns the path for it, otherwise returns None.
"""
context.Display("Checking whether %s program exists..." % prog_name)
path = context.env.WhereI... | 82b163b35617b8433c7e2921f2d6a28879b789ce | 635,259 |
def hwc_to_chw(x):
"""image format HWC to CHW"""
if len(x.shape) == 3:
return x.permute(2, 0, 1)
else:
return x.permute(0, 3, 1, 2) | f1278e91ddccb65245834ce8c84d99cdab74ef49 | 635,260 |
def helloWorld():
"""
Root route
Returns:
String -- Return a valid string
"""
return "Hello, cross-origin-world!" | 1217ef84236ddeda123472a9bf0649140771168c | 635,262 |
def get_dictionary(filename):
"""returns a dictionary with the word being the key to it's
phonetic pronunciation"""
rhymedict={}
with open(filename) as wordfile:
lines=wordfile.read().splitlines()
for line in lines:
line=line.split(" ")
rhymedict[line[0]]=lin... | 2bbb1d1107b79231f569854051b9477ea3055ab5 | 635,263 |
def _filtering_extensive(iss, neighs, neighs_oi, dists_oi):
"""Filtering previously visited nodes."""
indices = [i for i in range(len(neighs_oi))
if neighs_oi[i] not in neighs[iss]]
neighs_oi = [neighs_oi[i] for i in indices]
dists_oi = [dists_oi[i] for i in indices]
return neighs_oi,... | f60585a34b4794b24efb693cd1c18ededc657d3f | 635,264 |
def rescale_prediction(prediction, scalers):
"""
:param prediction: the closing price prediction, which has been scaled
:param scalers: dict of standardscalers used to scale known data
"""
return scalers['close'].inverse_transform(prediction.reshape(-1, 1))[0][0] | c93afc163deaefc3d620d85da05843a6d0920000 | 635,265 |
import requests
from bs4 import BeautifulSoup
def get_synset_image_urls(synset_id):
"""
Takes a synset id and fetches urls of associated images
The function uses the synset ID to open a website from ImageNet
corresponding to the synset ID that displays nothing but a long list of
links of images a... | 2c4dbe163bc7d2ada574c3bbaaabeddc83252611 | 635,266 |
def chrome_options(chrome_options, create_tmp_dir):
"""Set configuration to run Chrome with specific options."""
prefs = {"download.default_directory": create_tmp_dir,
"download.prompt_for_download": False}
chrome_options.add_experimental_option("prefs", prefs)
return chrome_options | bd1a25192bff87f54da62794aec9288c1497f488 | 635,267 |
from typing import Dict
def solve_part2(identified: Dict[str, str]) -> str:
"""
identified:
'eggs': 'hn',
'fish': 'dgsdtj',
'nuts': 'kpksf',
'peanuts': 'sjcvsr',
'sesame': 'bstzgn',
'shellfish': 'kmmqmv',
'soy': 'vkdxfj',
'wheat': 'bsfqgb'
Solution:
hn,dgsdtj,kpksf,s... | a1842b78c6ff08cfb7c8a7d7c4ebaf59e16c4f14 | 635,269 |
def use_loop(f, list_input):
"""Single processing"""
list_result = []
for input in list_input:
list_result.append(f(input))
return list_result | 8eb7afe1646e13f7713af920c7bbea57f23cbcc1 | 635,270 |
import sys
import statistics
def weight_article(weight_paragraph_result, weighting_metric):
"""
weight metric between paragraphs
:param weight_paragraph_result: list of dicts
:param weighting_metric: String
:return: weighted weight_paragraph_result (final)
"""
article_dict = dict()
we... | 3a256a0534ba4190efdc53e3b89102e83a2e4da7 | 635,271 |
def _list_info(candidate_element):
"""Log element id, title or placeholder
"""
outer_html = candidate_element.get_attribute('outerHTML')
if outer_html != '' or outer_html is not None:
return "OuterHTML: {}".format(outer_html)
return candidate_element | c400126e927c399beb99aac699c276a7e1ffb3aa | 635,272 |
def index():
"""Unprotected API
"""
return "Hello, World!" | 59a11afa5a1febea7bb7b019de045d63197a3819 | 635,274 |
def cdot(C, nb, F, c0, g):
"""
Inputs:
C : nutrient concentration at time t
nb : total bacteria population size at time t
F : chemostat flow rate
c0 : initial nutrient concentration
g : bacterial growth rate
"""
return F*(c0-C) - g*C*nb | 1c3d7be8161f18428ac90b5245311516f875ecef | 635,275 |
import os
import re
def save_comments(outputdir, ta_name):
"""
Save index and content of comments in conf file and return dictionary thereof
"""
config_file = os.path.join(outputdir, ta_name,'default', "app.conf")
comment_map = {}
with open(config_file, 'r') as file:
i = 0
line... | ddf7233deb3b4760d140b9fccec870bd07f47855 | 635,276 |
from subprocess import PIPE
import subprocess
import shlex
def run_command_and_get_result(command):
""" Runs a command in the console and gets the result.
Command can be a string (single command) or a tuple of strings (multiple
commands). In the multi-command setting, commands will be joined
... | 371d6dd42ce7b0a89311f525dff3df5bb6ff28b4 | 635,277 |
def linear(x):
"""Linear activation function :math:`\\varphi(x) = x`
Parameters
----------
x : float32
The activation (the summed, weighted input of a neuron).
Returns
-------
float32
The output of the identity applied to the activation.
"""
return x | a67bdaef84ae7f227693ae03ce44f2bcefdad94f | 635,278 |
def parse_cdk_file(file):
"""
Function to parse CDK output
Parameters
----------
file : str
file to parse the chemical descriptors from
Returns
-------
dict
dictionary containing the chemical descriptor name and
the chemical descriptor value
"""
cdk_file... | aa4c541af2163c546c9dada91020a929ff3f16f0 | 635,280 |
def get_distance(highway_now: list, car_index: int) -> int:
"""
membuat jarak antara kendaraan dan kendaraan selanjutnya
>>> get_distance([6, -1, 6, -1, 6], 2)
1
"""
distance = 0
cells = highway_now[car_index + 1 :]
for cell in range(len(cells)):
if cells[cell] != -1:
... | ad5a13f0949c788cd77a455bf4a1dcfc0ea1fd8a | 635,281 |
def templates():
"""Dictionary of dockerfile templates and settings."""
return {
'ros2': [
{
'name': 'foxy',
'ubuntu_distro': '20.04',
'ros_distro': 'foxy',
'python_version': '3.8'
},
{
'n... | 46b1d6a67c9f829691a080612626c2fc52f35f25 | 635,282 |
def _normalise(s):
"""
Normalise the supplied string in the following ways:
1. String excess whitespace
2. cast to lower case
3. Normalise all internal spacing
:param s: string to be normalised
:return: normalised string
"""
if s is None:
return ""
s = s.strip().lower()... | f89b219e04e83d3e8fc9feae1aad6a00d24d525b | 635,283 |
import socket
def create_socket_connection(hostname, port=443, sock_type=socket.SOCK_STREAM, timeout=10):
"""See: https://github.com/python/cpython/blob/40ee9a3640d702bce127e9877c82a99ce817f0d1/Lib/socket.py#L691"""
err = None
try:
for res in socket.getaddrinfo(hostname, port, 0, sock_type):
... | 512ea16beae23a053d526f302ca7e40015cedd00 | 635,284 |
import six
def inclusion_only_unlimited_args_from_template(*args):
"""Expected inclusion_only_unlimited_args_from_template __doc__"""
return {
"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (
', '.join(six.text_type(arg) for arg in args)
)
} | 4ebce01c95457e7f063a52b70097a0c23cbf65e9 | 635,285 |
def round_mean(avg_bias, sentences, k=4):
"""Compute the average and round to k places"""
avg_bias = round(float(avg_bias) / float(len(sentences)), k)
return avg_bias | cd47f33964ac5d190c0a5280cab0b337f6fc1cac | 635,286 |
def package_fixture():
""" DC/OS package fixture.
:rtype: dict
"""
return {
"apps": [
"/helloworld"
],
"command": {
"name": "helloworld"
},
"description": "Example DCOS application package",
"maintainer": "support@mesosphere.io",
... | c2789a73e9703d26d3065445acfa8b9089f0394f | 635,287 |
import warnings
def no_of_events(tweet_file, t_observation, t_prediction, time_factor=1):
"""
calculate the number of retweets at the observation time (=t_observation) and at the final time of prediction (=t_prediction)
:param tweet_file: data file
:param t_observation: observation time
:param t_p... | ee198f820503e29aa2b3733811e49302a76e61b5 | 635,291 |
def each_unit_sum(number):
"""
:param number :
:return:
"""
sum_value = 0
for item in str(number):
sum_value += int(item)
return sum_value | cdbad3506520d53eee50a8bda8c7438518d51e7c | 635,292 |
def combine_rs_and_ps(regular_season, post_season):
"""Combine Regular Season and Post-Season Data into one table.
Args:
regular_season: player RS data for table type
post_season: player PS data for table type
Returns:
combined RS and PS table
"""
total = []
if regular_... | c536f94771cff795a69e4051eccdd336708db4e0 | 635,294 |
def option_str_list(argument):
"""
An option validator for parsing a comma-separated option argument. Similar to
the validators found in `docutils.parsers.rst.directives`.
"""
if argument is None:
raise ValueError("argument required but none supplied")
else:
return [s.strip() fo... | e198f0351dc67d9b90826f9d597e6e6e4c23d6c6 | 635,295 |
def discard_empty(s: str) -> bool:
"""Return true if the provided string is non-empty."""
if s:
return True
return False | fa647606297b2fb0d67f610d88681d98363c8f32 | 635,297 |
def calcDistance(ent1, ent2):
"""
Calculate the distance between two entities
"""
dimensionDelta = (ent1.dimension-ent2.dimension) * 1000
deltaPos = [ent1.pos[a]-ent2.pos[a] for a in (0, 1)]
return (deltaPos[0]**2 + deltaPos[1]**2)**0.5 + dimensionDelta | 6940f9332656677c42a79a4470e715acb1a9de16 | 635,298 |
import torch
def create_batch_from_data_list(data_list):
"""Given a list of datapoints, create a batch.
Args:
data_list (list): List of items returned by SceneRenderDataset.
"""
imgs = []
azimuths = []
elevations = []
for data_item in data_list:
img, render_params = data_i... | 416777a8ee3fffd8fb572707408e1bd34e2e597c | 635,299 |
import io
def _encode_image(image_array, fmt):
"""encodes an (numpy) image array to string.
Args:
image_array: (numpy) image array
fmt: image format to use
Returns:
encoded image string
"""
from PIL import Image # pylint: disable=g-import-not-at-top
pil_image = Image.fromarray(image_array)
... | 9fa65e7f158b766e670bd5bd10120be22d39485c | 635,300 |
from typing import AnyStr
def detect_space_after(txt: AnyStr, end: int):
"""Given text and an end index returns True if there is a space after the end index, false
otherwise.
Parameters
----------
txt : str
the text itself.
end : int
the end index of the token.
Returns
... | ed64cb63ec77cdca92b2e312852f6f21f7fdd4ee | 635,301 |
def dict2string(dictionary, typ='dictionary'):
"""
DEFINITION:
converts strings (as taken from a database) to a dictionary or a list of dictionaries
VARIABLES:
dictionary : dictionary
typ : dictionary, listofdict, array
"""
... | 9daadd1ac2ef4aa2e56b2c85a2308d84413ef6e5 | 635,303 |
import os
def check_if_file_exists(file):
"""Check if a given file exists either as a file, dir or symlink"""
if any([
os.path.isfile(file),
os.path.isdir(file),
os.path.islink(file)
]):
return True | 3654cd40ecc0671f3e26afb73304ada07fa19de8 | 635,305 |
def split_file_name(file_absolute_name):
"""
Splits a file name into: [directory, name, extension]
:param full_name_template:
:return:
"""
split_template = file_absolute_name.split('/')
[name, extension] = split_template[-1].split('.')
directory = "/".join(split_template[0: len(split_te... | f3144b0f75cbde26c8a8244cb8d8eda712e8edfa | 635,306 |
import requests
def check_http_307_redirection():
"""Чтобы корректно работать на новом домене HTTP-клиент должен поддерживать редирект HTTP 307.
Подробнее: https://ads.tiktok.com/marketing_api/docs?rid=esb88xalm6m&id=1709207085043713"""
response = requests.post(
url='https://httpbingo.org/redirect... | 6e1715133f8b7755a29c1b55cd8f42563c027f43 | 635,307 |
def fig_file(m):
"""Returns the first group of the match"""
return [ 'fig', m.group(1) ] | efcef6bb05399bbb9603f9c0897e432e2af502b2 | 635,308 |
import subprocess
def run_blastp(query_file, database_file, e_value_cutoff, processes):
"""
Runs BLASTp...
:param query_file: The amino acid query FASTA file.
:param database_file: The amino acid BLAST database location (amino acid FASTA file at this location)
:param e_value_cutoff: The e-value cutoff for BLASTp... | 4556c80784f0dc358a8bf97605bf90e769adf7b2 | 635,309 |
import socket
from contextlib import closing
def check_socket(port):
"""Check whether the given port is open to bind"""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock:
try:
sock.bind(('', port))
except:
#Port is not open
res = False... | 93bce5290e0b1774c18c1ecdc592af3dd80f976d | 635,310 |
import json
import hashlib
def get_hash(block):
"""
Creates a SHA-256 hash of a Block
:param block: Block
"""
# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string)... | 7b3c7f1f7c7ec566199f6742bdcc67d2f0e99d9a | 635,311 |
import os
def get_env(name):
"""Returns environment variable"""
return os.environ[name] | 21ad0c55d7460317fd453620f533405a7c65cada | 635,312 |
def transaction_type_6():
"""Transaction of type "timelock transfer"
"""
data = {
'data': {},
'serialised': ''
}
return data | c18f6491e45c33922d456ef2367a48c3c28f5f17 | 635,313 |
import argparse
def set_cmd_line_args():
"""
get the command-line arguments needed to convert the Excel input file into Define-XML
:return: return the argparse object with the command-line parameters
"""
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--define", help="path and fi... | 229baf0e74377167fb3a6ba1156dab83053c3e2c | 635,314 |
def ranges_intersect(pair1, pair2, buffer=0):
""" true if ranges entersect by more than buffer """
return (pair1[0] < pair2[1] - buffer) and (pair1[1] > pair2[0] + buffer) | c5d5ec893b98833a860ee6a83ce6fbde2ee637ae | 635,315 |
def KNMConfig(config):
"""
Creates config required for KNM from the clarity-ext config (which has more than that)
"""
return {
key: config[key]
for key in [
"test_partner_base_url",
"test_partner_code_system_base_url",
"test_partner_user",
... | 02d6b9cf134aa0179ca372c9f41c57e6a84ffb4e | 635,316 |
import warnings
def dummy_func(arg1, keyval1=None):
""" Dummy function to test """
if arg1 == "User":
msg = "Raising User error"
warnings.warn(msg)
return arg1, keyval1 | 0909f1789fcec0efae0bebc02d4334bc870f4871 | 635,317 |
def return_ttl(name: str) -> int:
"""
**return_ttl**
returns ttl for cache depending on long, short, and medium
:param name: string -> period = short, medium, long
:return: int -> time to live
"""
cache_ttl_short: int = 1800 # (60*60 * 0.5) 30 minutes
cache_ttl_medium: int ... | cdedc8617c86828ee6fb00965a5ceb2b206c7537 | 635,319 |
from pathlib import Path
from typing import List
import os
def get_gdal_incdirs(gdal_dir: Path) -> List[str]:
"""
This function finds the include directories
"""
gdal_incdir = os.environ.get("GDAL_INCDIR")
incdirs = []
if gdal_incdir is None:
if (gdal_dir / "include").exists():
... | 0780f2dbbed9712176c1a58e45c5b16c42e35f32 | 635,320 |
import subprocess
def do_rsync(srcs, dest, suffix, log, owner, no_sudo):
"""
run rsync to copy all dirs in SRCS under DEST, making a back up of
overwritten files with SUFFIX; a line saying suffix=SUFFIX and
all outputs from rsync are put into a file named LOG. It will
be read by read_copied_files... | 3a1d538beceb66c9ef611fd03701cc17f2c254b5 | 635,321 |
import json
def get_filtered_keys_from_map(key_map, payload):
"""
Filter the payload for the given keylist and return the filtered dict
:param key_list: a json old_key:new_key map in string format
:param payload: dict payload which needs to be filtered
:return: dict with new_key, value pair based ... | e5476d352c7969606a52b7c4260aea0877756cf6 | 635,322 |
def isATriangle(neigh_orders, face):
"""
neigh_orders_163842: int, (N*7) x 1
face: int, 3 x 1
"""
neighs = neigh_orders[face[0]*7:face[0]*7+6]
if face[1] not in neighs or face[2] not in neighs:
return False
neighs = neigh_orders[face[1]*7:face[1]*7+6]
if face[2] not in neighs:
... | 782e34534af7d0073f58267ff6f8fe2d55eb09d1 | 635,323 |
def chunk_string(input_str, length):
"""
Splits a string in to smaller chunks.
NOTE: http://stackoverflow.com/questions/18854620/
:param input_str: str the input string to chunk.
:param length: int the length of each chunk.
:return: list of input str chunks.
"""
return list((input_str[... | 77d6d04bae52429f5a31de96baf1b761e224dd43 | 635,324 |
import os
def is_final_group(group_dir) -> bool:
"""Checks if group does not contain any directories other than in or out"""
dirs = [path for path in os.listdir(group_dir) if os.path.isdir(path)]
if len(dirs) == 0 or 'in' in dirs:
return True
return False | 8bfd684a0cb87b10ce4b01948fb0ec4a5ba742f7 | 635,325 |
def transform_table(table):
"""
Unsqueeze keys aligning with values
Args:
table: table defining key-value pairs
Returns:
- unsqueezed key-value dict
"""
keys, values = [], []
for sample in table:
ks, vs = [], []
for k, vals in sample.items():
ks.... | 08b232af802d4b4d79051470b20bd51753d5931b | 635,327 |
def line_from_2_points(x1, y1, x2, y2):
"""
Gets the coefficients of a line, given 2 points
:param x1:
:param y1:
:param x2:
:param y2:
:return:
"""
a = y1 - y2
b = x2 - x1
c = x1 * y2 - x2 * y1
return a, b, c | c0ce5d3963a1dcd6ef83b09edcef4a08a2e4faed | 635,328 |
def is_pandigital(n):
"""Tests if n is a 1-9 pandigital"""
if len(str(n)) != 9:
return False
if "0" in str(n):
return False
return len(str(n)) == len(set(str(n))) | 404595a3cd75829cc4c4f324a0b8bfe86884d6a5 | 635,329 |
def numeric_strings(s):
"""
:param s: num string
:return: is num
"""
def is_num(s, allow_dot = True, allow_E = True):
"""
:param s: num string
:param allow_dot: if allow .
:param allow_E: if allow E/e
:return: Bool
"""
number = ['0', '1', '2',... | 94526d042399a02e77ba11114b7fe928a6e37566 | 635,330 |
def mulrowcol(row, col, K):
"""
Multiplies two lists representing row and column element-wise.
Gotcha: Here the column is represented as a list contrary to the norm
where it is represented as a list of one element lists. The reason is
that the theoretically correct approach is too expensive. This p... | 448aec2928b314cabe707f19f69bfd687b8fe31c | 635,331 |
import base64
def load_wrap(filename, attach=False):
"""
Encodes a load or attach command as valid Python code.
INPUT:
- ``filename`` - a string; the argument to the load or attach
command
- ``attach`` - a boolean (default: False); whether to attach
``filename``, instead of loading ... | 563b48d56d121d5df87d5f577390b4cd5a6a0abc | 635,332 |
def bool_to_bin(bool_value):
"""
Helper function to map a boolean value to a binary value.
:param bool_value: boolean boolean value [bool]
:return: binary value [int]
"""
if bool_value:
return 1
else:
return 0 | 4d05f6644d434fe8eb99743f17f2fd1b472cbdb5 | 635,333 |
def _has_tag(Estimator, tag):
"""Check whether an Estimator has the given tag or not.
Parameters
----------
Estimator : Estimator class
tag : str
An Estimator tag like "skip-inverse-transform"
Returns
-------
bool
"""
# Check if tag is in all tags
return Estimator._... | ceb580cbcb89a208a290080e0efe429e2ecb1e95 | 635,335 |
def target():
"""Input target name."""
return 'ENCELADUS' | ccf426e2cb5ef822352fb910ff44c8574254acaf | 635,336 |
import logging
def get_lower_level(l0, l1):
"""Compare logging levels and return the lower level."""
if isinstance(l0, (str)):
l0 = logging.getLevelName(l0)
if isinstance(l1, (str)):
l1 = logging.getLevelName(l1)
return l0 if l0 < l1 else l1 | c9bde5945ad5d88729e0181e46b2a14576f94d1f | 635,337 |
def _conv2d3d_strides_or_dilations(name, value, data_format, default_value=1):
"""Compute strides or dilation values for 2D and 3D convolutions."""
if value is None:
value = default_value
if not isinstance(value, (int, list)):
raise ValueError("{} must be an int or list".format(name))
#... | c757bdffeae3f324b49b2fea89d8bd627b762808 | 635,338 |
def check_prefixes(parsed, expected_prefixes):
"""Make sure each rank has the expected prefix"""
for name, prefix in zip(parsed, expected_prefixes):
try:
obs, level_name = name.split('__', 1)
except ValueError:
return False
if obs != prefix:
return Fa... | e85488eca0a9b2adbe014da7b7da1bea5f0c2044 | 635,339 |
import string
import re
def clean_text_round3(text):
"""
Clean up text data.
Do what clean_text_round1 does, adding:
Remove pontuations, except accents.
Remove words if less than 3 letters
Remove some special chars commom in papers
"""
remove = string.punctuation
remove = remove.r... | a9897ace93ec564a50cfb32718fa4753f06e6334 | 635,340 |
def _compare_glue_connection_params(user_params, current_params):
"""
Compare Glue connection params. If there is a difference, return True immediately else return False
:param user_params: the Glue connection parameters passed by the user
:param current_params: the Glue connection parameters currently... | b046373541ebacdb18c0fcd780edb865af6641fb | 635,341 |
import time
def time_it(func):
"""记时装饰器函数"""
def inner():
start = time.time()
func()
end = time.time()
print("程序用时:{}".format(end - start))
return inner | edefddf670cbea9312d53241283269911904cc03 | 635,342 |
def model_snowdepthtrans(Sdepth = 0.0,
Pns = 100.0):
"""
- Name: SnowDepthTrans -Version: 1.0, -Time step: 1
- Description:
* Title: snow cover depth conversion
* Author: STICS
* Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002
... | c5b9a471a8a3a860cd305af58a5c4b4614fc1918 | 635,343 |
def match_path(path, partial_paths):
"""Does the given path contain any of the stubs in partial_paths?"""
return any(partial_path in str(path)
for partial_path in partial_paths) | 54d69378ac4f03848a1bed331f9eebdbc426ea24 | 635,344 |
def minmax_normalize(X):
"""Normalizes X into the -0.5, 0.5 range."""
# X -= X.min()
# X /= X.max()
# X -= 0.5
X = (X-X.min()) / (X.max() - X.min())
return X | 54b20a5f615fc0cef315a8373962c9d6a973bdd8 | 635,345 |
def validate_tags(tags):
"""makes sure the tags are well formed"""
tags_good = True
for tag in tags:
if not all (key in tag for key in ('Key', 'Value')):
print("the following tag is malformed: {}".format(tag))
tags_good = False
return tags_good | 7104456127218e0b98d80e6be6efcc7a532a63c8 | 635,346 |
def det_new_group(i, base=0):
"""Determine if new_group should be added to pipetting operation.
Helper to determine if new_group should be added. Returns true when
i matches the base, which defaults to 0.
Parameters
----------
i : int
The iteration you are on
base : int, optional
... | 56085d034084abb77a6db6e436f0bd5e21756829 | 635,347 |
def get_T(Theta):
"""(6)
Args:
Theta: 空気温度(℃)
Returns:
絶対温度(K)
"""
return Theta + 273.16 | 04ae822c3de8958bd81a16ace0e393fc07edfa52 | 635,348 |
def restructure_ctd_response(json_doc):
"""restructure the JSON output from CTD API
parameters
* json_doc: the API response from CTD API
"""
# convert from list to dict
if isinstance(json_doc, list):
json_doc = {'data': json_doc}
for _doc in json_doc['data']:
if "PubMedI... | 239d875fc9905b9f75b1ebdcf693fdf78f9c862d | 635,349 |
def cumulative_gain(rank_list):
"""Calculate the cumulative gain based on the rank list and return a list."""
cumulative_set = []
cumulative_set.append(rank_list[0])
for i in range(1, len(rank_list)):
cg = cumulative_set[i-1] + rank_list[i]
cumulative_set.append(cg)
return cumulative... | cbe36e7cd6ba75e267c3d5887501c988febbceca | 635,350 |
import argparse
def parse_args(home):
"""Parse CLI arguments."""
parser = argparse.ArgumentParser(description="Manage GitLab via API.")
parser.add_argument("action", help="Define action to take.", choices=[
"get_all_groups", "get_group_details", "get_group_projects",
"get_issues", "get_use... | beb2fb3d427b390166e10dde48548573d4f1fc7e | 635,352 |
import click
def atomic_to_global_desc_options(f):
"""Create common options for global descriptors constructed based on atomic fingerprints """
f = click.option('--reducer_type', '-r',
help='type of operations to get global descriptors from the atomic soap vectors, e.g. \
... | 5765d98445134a0e5795dd1d87d44eb02e3eefc4 | 635,353 |
def RK4(x, h, f):
"""Runge-Kutta 4th-order integration method for an autonomous system f."""
K1 = h*f(x)
K2 = h*f(x+(K1 * 0.5))
K3 = h*f(x+(K2 * 0.5))
K4 = h*f(x+K3)
return x+(1/6.0)*(K1 + 2*K2 + 2*K3 + K4) | c34310e3d2789f11a9d46ee78ddfdc54ba2ca63e | 635,354 |
import torch
def pad_collate_fn(data_list):
"""
Here we pad with last image/ timestamp to get a contiguous batch
"""
images, _ = zip(*data_list)
max_len = max([item.shape[0] for item in images])
b = len(images)
_, c, h, w = images[0].shape
shape = (max_len, b, c, h, w)
out_images =... | 0420e97ac6147f8597b5fbba751c9432c243a7db | 635,356 |
def get_aa_at_gene_pos(row, ref_aa_seq_dict):
"""
Helper function to apply on every row of a data frame
to find the reference amino acid at given a gene and amino acid position.
Parameters:
==============
- row: dict
Row of dataframe in dict form. Should have fields aa_pos (1-based aa po... | d237e7a29d6b2cd2eb39b58e6a88106fedfb2a6e | 635,357 |
def lower_text(text: str) -> str:
"""
Given ``text`` str, transform it into lowercase
Parameters
----------
text : string
Returns
-------
string
"""
return text.lower() | d90308073617a3e7884edb4253aa5ac221f3b672 | 635,358 |
from datetime import datetime
def get_current_datetime() -> datetime:
"""
Generate datetime in UTC timezone.
Returns:
datetime: datetime.
"""
return datetime.utcnow() | f93af05b4660306545e2e505c50a7fd016ec2773 | 635,359 |
def _for(x):
""" _for """
ret = x * x
for i in (2, 3):
ret = ret * i
return ret | b6071cad420f2bc7977cdeddb8c4ec4b8b43bbb7 | 635,361 |
def _extract_match_id(match_json):
"""
Extract the match_id from json response.
{
"matches": [
{
"id": "0000...",
"match_id": 1313,
"similarity": "001000"
}
]
}
"""
matches = match_json.get('matches', [])
... | 60109a70aceae4f5074338b268f498da56af65f0 | 635,362 |
def ascii_encodable(text):
"""
Return True if the given TEXT can be losslessly encoded in
ASCII. Otherwise, return False.
"""
return all(ord(char) < 128 for char in text) | 1defb4b6453445bf26650bd0169045b70b8f053e | 635,363 |
import logging
import os
def process_logfile(job_obj, ci_log):
"""
Runs after code has been cloned and built
Checks to see whether build was successful or failed
"""
logger = logging.getLogger('BUILD/PROCESS_LOGFILE')
fail_string = 'FAIL'
success_string = 'ALL BUILDS SUCCEEDED'
build_s... | 29db4661946548d8bcce5f41a165f309254e3024 | 635,364 |
from functools import reduce
def url_path_join(parts: list) -> str:
"""拼接 url path"""
return reduce(lambda a, b: a.rstrip("/") + "/" + b.lstrip("/"), parts) if parts else "" | 5a031d69e9f1606d67490b8d7761a7792327902c | 635,366 |
def join_wisely(left, right, remove_duplicates=True, echo=False, **kwargs):
"""
joins two dataframes and returns a dictionary with 3 members: left_only, right_only, and both (the results of the two joins)
:type left: DataFrame
:type right: DataFrame
:type kwargs: dict
:rtype: dict of DataFrames
"""
left=left.co... | 1d2da24cca78802725348a40c6bbf74702a24571 | 635,367 |
import base64
def decode_part(raw, encoding="utf-8"):
"""Decode a part of the JWT.
JWT is encoded by padding-less base64url,
based on `JWS specs <https://tools.ietf.org/html/rfc7515#appendix-C>`_.
:param encoding:
If you are going to decode the first 2 parts of a JWT, i.e. the header
... | 8413ae54e31e1ebbebae5752410f62f43a38a242 | 635,368 |
import time
def allow_retries(retry_on=[], wait=time.sleep, retries=3, delay=2):
""" A general purpose decorator that allows a given function to be retried
after certain failures.
**Example**
Suppose we have a function that occasionally throws errors if it doesn't get
its way. In that case we ca... | 453f8ef0af44dad4347bef21d09ff63f226a4e1a | 635,369 |
import socket
def ping_command(ping_binary, address, version=socket.AF_INET, count=1, payload_size=None):
"""Generate a ping shell command for Popen"""
args = [ping_binary]
if version == socket.AF_INET6:
args.append('-6')
else:
args.append('-4')
# ping interval
args.append('-i... | 6401db8a5052bcecf6eb256d9a3b9c094a7bc6dd | 635,370 |
import os
import fnmatch
def find_files(directory, pattern='*.csv'):
""" Recursively finds all files matching the pattern.
:param directory: directory path
:param pattern: reggex
:return: list of files
"""
files = []
for root, dirnames, filenames in os.walk(directory):
for filen... | b015b6516462ba76faaa0f0dcb2085e0dcacdd52 | 635,371 |
def df2geojson(df, lat='latitude', long='longitude', remove_coords_properties=True):
"""
Convert um dataframe, com colunas de latitude e longitude, em um objeto geojson de pontos
https://notebook.community/gnestor/jupyter-renderers/notebooks/nteract/pandas-to-geojson
# Usage
feature_collection = da... | cb4ffc75e84f0a201ff10ba60ec4b82ab1c8e683 | 635,372 |
def a2s(a):
"""
helper funciton: Convert to string
"""
str=''
return str.join(['%g '%(v) for v in a.ravel()]) | 31894d6181d5d726232d8d8798922ef770da6441 | 635,373 |
def swap_last_element(lst_to_swap: list) -> list:
"""Intercambiate first element with the last in the list"""
new_lst = lst_to_swap.copy()
new_lst[0], new_lst[-1] = lst_to_swap[-1], lst_to_swap[0]
return new_lst | bc32138c4c54b6eb3044f5df9f662eb4ba8fc972 | 635,374 |
def google_map(context):
"""
Dependencies for google_map gizmo.
"""
return ('tethys_gizmos/js/tethys_map.js',) | 036f03be322b10b03a3233eb4c47b8db1eaa4c88 | 635,375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.