content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import jinja2
def interpolate_value(value: str, context: dict):
"""Expand Jinja templating in the definitions."""
if type(value) == str and "{{" in value:
t = jinja2.Template(value, undefined=jinja2.StrictUndefined)
try:
v = t.render(**context)
except jinja2.exceptions.Tem... | f1fca637ab57152743cf955e04a2b59d794c49cb | 650,632 |
def process_stream(g):
"""
Process a given stream into a nodes and edges dictionary.
"""
nodes = {}
edges = {}
for rec in g:
if rec:
if len(rec) == 4:
key = (rec[0], rec[1])
if key in edges:
edges[key].append(rec[-1])
... | 562c57ecc316483856cb9e7d4cdd66e304379483 | 650,633 |
def append_to_dataset(dataset, sample):
"""
Append a new sample to a provided dataset. The dataset has to be expanded before we can add value to it.
:param dataset:
:param sample: data to append
:return: Index of the newly added sample.
"""
old_size = dataset.shape[0] # this function always... | 334f9d7ede7d3b394e1fbd45be76e1a25ee2b900 | 650,634 |
def get_str_from_global(node):
""" Returns the string from the global node """
result = list()
for inp in node.inputs:
result.append("[%s]" % inp.label)
result.append("%s" % node.name)
for out in node.outputs:
result.append("[%s]" % out.label)
result.append(";")
return '... | e67462162ba337eda5e861ec348ab88739987c6b | 650,635 |
from typing import List
from typing import Any
def transpose(rows: List[List[Any]]) -> List[List[Any]]:
"""Converts rows to cols or vice versa"""
nrows = len(rows)
assert nrows > 0, "Expected at least one row in input"
ncols = len(rows[0])
cols = [[None for _ in range(nrows)] for _ in range(ncols)]
for i ... | 43b0c58afa26f2b0f4e4409bd6dfeafe142babe4 | 650,636 |
from typing import List
def get_data_element_total(
data_element_id: str,
data_values: List[dict],
) -> int:
"""
A DHIS2 data element may be broken down by category options, and
``data_values`` can contain multiple entries for the same data
element. This function returns the total for a given
... | d466a372bc353aa00135eb6a431b37a1029f80fc | 650,637 |
import torch
def _pad_bert_inputs(examples, max_len, vocab):
"""Defined in :numref:`subsec_prepare_mlm_data`"""
max_num_mlm_preds = round(max_len * 0.15)
all_token_ids, all_segments, valid_lens, = [], [], []
all_pred_positions, all_mlm_weights, all_mlm_labels = [], [], []
nsp_labels = []
for ... | c0fa980f1870e74ede58fc3918f0a7c80b887a59 | 650,638 |
def to_megabytes(size_bytes):
"""
Convert size in bytes to megabytes
"""
return size_bytes * 1024 * 1024 | a7acb200c5c3067f902c190fca54e9bd362beccb | 650,640 |
def get_email_domain(email):
"""
Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_emai... | 941717a8a614235dd17b1573fc8a962c5f869cb9 | 650,641 |
def factR(n):
"""Assumes n an int > 0
Returns n!"""
if n == 1:
return n
else:
return n*factR(n - 1) | a53dd510438592bfd64799812da3e5a21b524d13 | 650,642 |
from typing import Callable
def get_values_by_keys(k: list, default=None)->Callable[[dict], list]:
"""
Filter dictionary by list of keys.
Parameters
----------
k: list
default: any, optional
Set as default value for key not in dict.
Default value is None
"""
return lam... | 2306493ef30753cac90d16529a4f128c45877fba | 650,643 |
def listToStr(x):
""" concatenate lists for use with data.
"""
return ' '.join(map(str, x)) | 1b2ce80542ea5111f44c0086110baf1ecb95fd59 | 650,644 |
import argparse
def get_args(args_str=""):
"""Parse the command line arguments (displays information if the -h or
--help option is used)
"""
description = "Tool to generate the roofline model."
parser = argparse.ArgumentParser(description=description)
parser.add_argument("-o", dest="output_... | 57970236ac629e94e6f378cf4c629abf529471ae | 650,645 |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... | 76a0a2e5148327f4ca311be74d974492129d4a3f | 650,647 |
def find_version_attribute(obj):
"""Depending on the object, modified, created or _date_added is used to store the
object version"""
if "modified" in obj:
return "modified"
elif "created" in obj:
return "created"
elif "_date_added" in obj:
return "_date_added" | 3b1068e65dd9341e4887a0c65904d41b6c9bea22 | 650,648 |
import hashlib
import requests
def get_url_data(url):
""" Return data for a URL """
# First check for cached file - if so return its
# contents. Note that we are not checking for
# age of the file - so content may be stale.
filename = hashlib.md5(url).hexdigest()
try:
with open(filena... | f7612528eb5111dac5349d83496bfb211b128237 | 650,649 |
import locale
def b2gr3(dt):
""" Format a datetime instance's month as a 3-char string
Needs locale package and el_GR available
sudo apt install locales-all
"""
locale.setlocale(locale.LC_ALL, "el_GR")
mgr = dt.strftime("%b")
locale.setlocale(locale.LC_ALL,locale.getdefaultlocale()... | cd929ceb108961ab89a00c43c450bb1512321496 | 650,650 |
def twoNumberSum(array, targetSum):
"""
This works completely on pointers, here we are having two pointers
One is left pointer and another being right pointer
idea here is to have left+right=sum, this can have three outcomes
1. First outcome
targetsum = sum
2. Second outcome
tar... | 50a890d760f67de1c6eecf209ebf4a96db7a98d4 | 650,651 |
def returnTrue(layer):
"""Returns True for any object passed to it."""
return True | 4a4fac0cb57e4f092571e395ae435c4069d26496 | 650,652 |
def all_debates(debates):
"""Debate filter returning all debates.
"""
return debates | 2b4144cc640018198b6c85cb71fe1e5af5c6b1b6 | 650,654 |
import argparse
def parse_arguments():
"""
Parser.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--model_name_or_path",
type=str,
required=True,
help="Path to pre-trained model or shortcut name",
)
parser... | ac833a8747856d2bc6ec4eddab0190fc639ef064 | 650,655 |
import os
import json
def get_supervisord_proxy():
"""Get the supervisor configuration and refactor it as a proxy file
Returns:
dict: The dictionary showing the proxy configurations.
"""
# check if the supervisor file exists
if not os.path.isfile("./supervisord/supervisor_config.json"):... | 12dd03bafa9829db471b4e8e630e797c3daf6e51 | 650,656 |
def build_exec(loopfunc, func):
"""Generator function that returns exec functions for operators """
def exec_func(self, context):
loopfunc(self, context, func)
return {'FINISHED'}
return exec_func | 66372afa0d1fc2398aa98fd52bee64eb72801181 | 650,657 |
import re
def fix_img(html):
"""
修正HTML图片大小自适应问题
"""
result = re.sub(
r"(<p>)*?<img([\s\S]*?)>(</p>)*?",
r'<section class="img-wrapper"><img\2></section>',
html,
)
return result | 7f1092b4802843a8014d4fa94427c84ea8d62850 | 650,658 |
import requests
import re
def get(url: str) -> dict:
"""
title、videos
"""
data = {}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
}
rep = requests.get(url, headers=headers, timeout=10)... | a96788138ffbbb1eadebc208557c84cee3ba798d | 650,659 |
def get_shell_from_file(shellname):
"""
Returns the shell from a .shell file in the shell directory as a string. It
can then be formatted to place ip and port in the file.
"""
filecontents = None
with open('shells/{}.shell'.format(shellname), 'r') as f:
filecontents = f.read()
return... | c82951afeef53d571a3fc453279df51b820970b3 | 650,660 |
import time
def currentTimeMillis():
"""Current system time in milliseconds"""
return time.time() * 1000 | 5cbe7fdbac834124d25d0103045d4790b18f0220 | 650,661 |
def setKeyPath(parent, keyPath, value):
"""
Allows the setting of arbitrary nested dictionary keys via a single
dot-separated string. For example, setKeyPath(parent, "foo.bar.baz",
"xyzzy") would create any intermediate missing directories (or whatever
class parent is, such as ConfigDict) so that t... | c92b1312b54e4a71be81c6577024def06a0b85f8 | 650,662 |
def temp_coeff_cold(lower, upper):
"""
Calculates and returns the m and b coefficients for y = m*x + b
for a line intersecting (lower, 0) and (upper, 255).
"""
m = 255/(upper-lower)
b = 255 - m * upper
return m, b | 0391f2d918627f43577555056d09e9c9efe1d15d | 650,663 |
import torch
def become_constant_trick(x, lengths):
"""
Input:
x: a tensor of shape (batch, stream, channel)
lengths: a tensor of shape (batch,)
Returns:
A tensor y of shape (batch, stream, channel), such that
y[i, j, k] = x[i, j, k] if j < lengths[i] else x[i, lengths[i],... | be8a0938f58b5274de1e030f75b4c4976e2a4bf8 | 650,664 |
def df_last_column(df, column_name):
"""Move a dataframe column to the right-most position.
Parameters
----------
df: :class:`pandas.DataFrame`
Dataframe to rearrange
column_name: :obj:`str`
Column to move.
Returns
----------
:class:`pandas.DataFrame`
... | 4ec7bfac2ed2099ff940456d78482ef0b368fcf8 | 650,665 |
from typing import Optional
def get_colour(label: str) -> Optional[str]:
"""Given the label of the thing to plot, determine the colour."""
if "given investment" in label:
return "orange"
if "all-in day one" in label:
return "blue"
if "cash" in label:
return "red"
if "nomina... | 7c9788ff22e5deaf83ad0272a487a69e67c91c3b | 650,666 |
def domain(url):
"""
Extracts the domain of an url
>>> domain('https://gitlab.laas.fr/pipo')
'gitlab.laas.fr'
>>> domain('gitlab.laas.fr/pipo')
'gitlab.laas.fr'
"""
if '://' in url or url.startswith('//'):
url = url.split('//')[1]
return url.split('/')[0] | eebef75ec3a418bb6afe830a6a3a98f31d54e7a8 | 650,667 |
import math
import numpy
def arcball_map_to_sphere(point, center, radius):
"""Return unit sphere coordinates from window coordinates."""
v0 = (point[0] - center[0]) / radius
v1 = (center[1] - point[1]) / radius
n = v0 * v0 + v1 * v1
if n > 1.0:
# position outside of sphere
n = math... | f0ae5feca8561fa96f0fa1ba5d18aa2cf06173c8 | 650,668 |
import requests
def request_data(coin, past, now):
"""
Receive and treats BTC/ETH Candles data from Mercado Bitcoin Candles API
"""
url = f'https://mobile.mercadobitcoin.com.br/v4/{coin}/candle?from={past}&to={now}&precision=1d'
try:
response = requests.get(url)
except requests.excepti... | 105d1b06e10f4321c8f57864088e3e261d557c9f | 650,669 |
def sequential_block(input, *layers):
"""helper function for sequential layers"""
for layer in layers:
layer_func, layer_conf = layer
input = layer_func(input, **layer_conf)
return input | 349edbdb513c032ace0d354abba42c0af4706980 | 650,670 |
import copy
def get_shared_data(component):
"""
Returns the actual list of component data based on how data is
stored in component, either from the `data` attribute or from the
`data['content']` attribute.
Returns:
list: List of component data.
"""
if component:
return (co... | 59fb8fd717973f7c0767497f7b28cc7dab94f27a | 650,671 |
from pathlib import Path
def read_df(t, tfmt, store, path):
"""
Read a matrix present in a `store` at a certain `path` with
the appropriate formatting of the date `t`.
"""
key = Path(path) / t.strftime(tfmt)
df = store[str(key)]
return df | d164135f83f9bc427a0c839d53a729df68d85047 | 650,672 |
import re
def filename_filter(filename: str, repl: str = '') -> str:
"""
将文件名替换成合法的文件名
:param filename: 原文件名
:param repl: 替换字符
:return: 合法文件名
"""
return re.sub('[/:*?"<>|]', repl, filename) | dfbd37d389da23e2837b122713b02284ad3cef38 | 650,673 |
def parse_conditional_field(field,
condition_marc_result):
"""Function takes a field and if the condition_marc_result mapping
includes X in either indicators, iterators through indicators and
returns a listing of matches.
Parameter:
Field -- MARC field
condition_marc... | aa8caac86af2c7876e58b9b66619643c9d71a002 | 650,674 |
def get_frac_moffat(r, alpha, beta):
"""
Calculate the fraction of light within radius r of a Moffat profile.
"""
frac = 1 - alpha**(2*(beta-1))*(alpha**2 + r**2)**(1-beta)
return(frac) | 9cdcdeb348cf47dde7eb81228f04603cb83872b3 | 650,675 |
def get_text_box(text, margin=0):
"""Return the coordinates of a Matplotlib Text.
`text` is a Matplotlib text obtained with ax.text().
This returns `(x1,y1, x2, y2)` where (x1,y1) is the lower left corner
and (x2, y2) is the upper right corner of the text, in data coordinates.
If a margin m is supp... | 88b986eb422f39c968db39dc401b9cd49eeb7aa3 | 650,676 |
def get_frequency_GC(reads):
""" get the ratio of GC pairs to the total number of pairs from a list of DNA strings"""
GC = []
AT = []
for read in reads:
for i in read:
if i == 'C' or i == 'G':
GC.append(1)
else:
AT.append(1)
total = s... | 22406533d5d60df39ec454feba5e665cb33bef1f | 650,677 |
import random
def create_neg_relations(entities, rels_between_entities, rel_type_count, neg_rel_count):
""" Creates negative relation samples, i.e. pairs of entities that are unrelated according to ground truth """
neg_unrelated = []
# search unrelated entity pairs
for i1, _ in enumerate(entities):
... | 4a8897b3055cf74106852b64944bb76c67674f71 | 650,678 |
def confirmation_reader(msg: str) -> bool:
"""Prints a message and asks for user confirmation.
Asks the user with a [Y/n] option for confirmation.
Args:
msg: The message to be printed before the confirmation choice.
Returns:
The users answer in form of a boolean value.
"""
ans... | e8c8822633e01ab9755516a2858128bb08db118d | 650,679 |
import re
def parse_instruction(line):
"""Parse line to instruction."""
if line.startswith('value'):
value, bot = [
int(num) for num in re.findall(r'(\d+).*?(\d+)', line)[0]]
return bot, value
bot, target_low, target_high = [
[func(value) for func, value in zip((str, in... | 34f27853dc37bab684865d2fe3b919b2e22e5522 | 650,681 |
import torch
def kld_loss(mu, log_var):
"""KL-divergence."""
return -0.5 * torch.sum(
1 + log_var - mu.pow(2) - log_var.exp(), dim=1) | 3a7718628f3f0c7ff2f068a9a71cd236bc100312 | 650,682 |
def get_unused_options(cfg_dict, options):
"""
Returns the unused keys in a configuration dictionary. An unused key
is a key that is not seen in *options*.
Parameters
----------
cfg_dict : dict
options : :py:class:`~enrich2.plugins.options.Options`
Returns
-------
`set`
... | 8f9a43f6b761fdd81450e8cad63ace47194233fe | 650,683 |
def get_hosts_ram_usage_ceilo(ceilo, hosts_ram_total):
"""Get (real) ram usage for each host from ceilometer
:param ceilo: A Ceilometer client.
:type ceilo: *
:param hosts_ram_total: A dictionary of (host, total_ram)
:type hosts_ram_total: dict(str: *)
:return: A dictionary of (host, ram_us... | 5ed34a05f29c201230ace8cf3985c86906726eb0 | 650,685 |
def calculate_correlation_lengths(semimajor, semiminor):
"""Calculate the Condon correlation length
In order to derive the error bars from Gauss fitting from the
Condon (1997, PASP 109, 116C) formulae, one needs the so called
correlation length. The Condon formulae assumes a circular area
with diam... | 8f6c0d424541e83b1fc8ee896b6252001072d4eb | 650,687 |
def split_and_fill(s, fill = 4, delim = ':'):
"""
Takes a string, a fill amount, and a delimiter and outputs an iterable,
where each index is the substring up to or after `delim`, zero-filled to `fill`.
e.g. split_and_fill("de:ad:be:ef") returns "00de", "00ad", "00be", "00ef"
"""
return (a.... | d0df948a0e5a0cd444354e7735a349886906a3da | 650,689 |
import os
def get_test_file(filename: str) -> str:
"""
Returns a file from test_data.
"""
basedir = os.path.dirname(__file__)
return os.path.join(basedir, filename) | beaeea5ca9a2c155d60b024d28fad882406cccb5 | 650,690 |
import json
def convert_to_json(value):
"""Converts the inputted object to JSON format.
Args:
value (obj): The object to be converted
Returns:
string : The JSON representation of the inputted object
"""
return json.dumps(value) | 7d73f3dfcf18dd08c5769ed00589734088f58541 | 650,691 |
import os
def exe(name: str) -> str:
"""
For distribution, once I've merged into master: look for ROSETTA in
os.environ and return exe path based on that.
"""
if os.path.exists("/home/andy"):
return "/home/andy/Rosetta/main/source/bin/" + name
else:
return "/Users/amw579/dev_u... | b9844320e95b34a9370dc0bef2edc30c563641ab | 650,692 |
import subprocess
import os
def run_local_worker(address, local_dir):
"""Run dask-worker on local."""
id = subprocess.Popen(
[
"dask-worker",
address,
'--nthreads=1',
'--nprocs=1',
'--memory-limit=0',
local_dir],
env=os.en... | bc8df1d811ae2fa5a34ed087259a2be6e4f5fdc1 | 650,693 |
def has_published(record):
"""Returns True if the record has any published record.
NOTE: the published record might be itself.
For efficiency, we don't hit the database.
"""
pid = record.get('_deposit', {}).get('pid', {})
return bool(pid.get('value')) and bool(pid.get('type')) | d0511b67ab691fd6bfdc56da7feb46c23e25946f | 650,694 |
import datetime
import numpy
def converttime(y):
"""
Converts from MET Fermi time to a python datetime tuple.
>>> convertyear(386817828)
returns datetime.datetime(2013, 4, 5, 1, 23, 48).
:param y: a float or array of floats
:returns: a datetime structure (or list) with the date corresponding to the input float... | 06ab1043f41699ef907a575017342ce5f0749965 | 650,695 |
def build_creative_name(order_name, creative_num):
"""
Returns a name for a creative.
Args:
order_name (int): the name of the order in DFP
creative_num (int): the num_creatives distinguising this creative from any
duplicates
Returns:
a string
"""
return 'HB {order_name... | a2ff9031601b09d504557dea48d021e931281b06 | 650,696 |
def simple_method_io(method, cdt, indataname, outdataname):
"""
Helper function to create inputs and outputs for a simple
Method with one input, one output, and the same CompoundDatatype
for both incoming and outgoing data.
"""
minput = method.create_input(compounddatatype=cdt,
... | 29890ecd0b582823a9e6f86021efd21abd410b60 | 650,697 |
def format_user(user_id):
"""
Formats a user id so it appears as @user in the slack
"""
return "<@" + user_id + ">" | 9fed6c29ca4a1b687c63f947a3d3b6bb5d8948d8 | 650,698 |
def f1(request):
"""
处理用户请求,并返回相应的内容
:param request: 用户请求的所有信息
:return:
"""
f = open('../resource/test03_index.html','rb')
data = f.read()
#print(type(data)) #bytes
f.close()
return data | 03c6d9c81ad1ec4cb1b31bf6acb598d3baba4b3b | 650,699 |
def scala_T(input_T):
"""
Helper function for building Inception layers. Transforms a list of numbers to a dictionary with ascending keys
and 0 appended to the front. Ignores dictionary inputs.
:param input_T: either list or dict
:return: dictionary with ascending keys and 0 appended to front... | 7ed86eb0485faa981ebbad921af676ca145a8c20 | 650,700 |
def _complete_lmax_res(lmax, res_beta, res_alpha):
"""
try to use FFT
i.e. 2 * lmax + 1 == res_alpha
"""
if res_beta is None:
res_beta = 2 * (lmax + 1) # minimum req. to go on sphere and back
if res_alpha is None:
if lmax is not None:
if res_beta is not None:
... | 754582bc44af347ddff672225b328ff22ac99aa9 | 650,701 |
def is_material_collidable(material):
"""Check whether a material has meta suggesting we need collision meshes"""
collision_filter = material.meta('collisionFilter')
return (not collision_filter) or (len(collision_filter) > 0) | 32914177162bae9753e8c2ecb3bd7d41fa5f8529 | 650,702 |
def volume(length, width, height):
""" (float, float, float) -> float
Computes the volume of a rectangular box (cuboid) defined by it's
length, width and height
"""
return length * width * height | 210f4c99c5adf1b16519a6966b440ebf4d96b555 | 650,703 |
def getClass(obj):
"""Return the class or type of object 'obj'.
Returns sensible result for oldstyle and newstyle instances and types."""
if hasattr(obj, '__class__'):
return obj.__class__
else:
return type(obj) | 0b2f7b11b946ea92a7453a232c8d43f575544fdf | 650,704 |
import random
def compute_shuffled_index(nb_lines):
"""
:param nb_lines: number of lines
:return: shuffled index of the number of lines
"""
# Create index
idx_shuffled = list(range(0,nb_lines))
# Shuffle the index
random.shuffle(idx_shuffled)
return idx_shuffled | 431b9bc8939f4752603b4996c481177d59bcfdfc | 650,705 |
def get_menu():
"""
获取菜单
:return:
"""
return (
'<帮助菜单>\n'
'注: 指令以/开头\n'
'以下为可用指令及描述信息\n{0}\n'
'开启|关闭\n'
'{1}开启|关闭自动回复\n'
'开启|关闭 人名\n'
'{1}对人名开启|关闭自动回复\n'
'开启|关闭群\n'
'{1}开启|关闭群内艾特自动回复\n'
'仅艾特 开启|关闭\n'
'{1}开启|关闭仅艾... | ab2d59d94439b2ffdb7d98e63a05fdc3afbc141b | 650,706 |
def expected_toy_predictions_gbdt_multiclass():
"""Expected prediction values."""
probabilities = [[0.0003345212, 0.0024717960, 0.9971936828],
[0.0003345212, 0.0024717960, 0.9971936828],
[0.01587624, 0.11731043, 0.86681333],
[0.01587624, 0.11731043, 0.8668133... | e9755b3210916eb19432c2ea45cd44d00b319402 | 650,707 |
def _clean_review_date_string(date_string):
"""
Cleans week_3.tweet date string.
Args:
date_string: A Review.review date string.
Returns:
A cleaned week_3.tweet date string in format
"""
date_list = date_string.split()
year = date_list[5]
month = date_list[1]
day = d... | bf23c704ba77f6fbe04a0243c23565b4fc163d22 | 650,708 |
import random
def random_book_by_genre(genre, genre_dict):
"""
given genre and a dictionary containing book-genre pairs, randomly selects a book from
genre_dict that is mapped tp the value of genre
:param genre: genre selected by user
:param genre_dict: dictionary of pairs in the format:
... | baa4e50e0dba42a8db62759d8b527b7ebb1f30ce | 650,709 |
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# stack storing right nodes
rightNodes = []
result = []
cur = root
while cur:
result.append(cur.val)
if cur.right:
rightNodes.append(cur.right)
cur = cur.left
if not cur and len(rightNodes)!= 0:
cur = rightN... | f6e23385b2caf33e5c5379bd8c80a3a659456166 | 650,710 |
import zipfile
import io
def _make_zip_file() -> zipfile.ZipFile:
"""Returns an in-memory zip file."""
data = io.BytesIO()
zf = zipfile.ZipFile(data, 'w')
zf.writestr('a.txt', b'content of a')
zf.writestr('b/c.txt', b'content of c')
zf.writestr('b/d/e.txt', b'content of e')
zf.writestr('b/f.txt', b'cont... | 5e7a71ec589c88248d9de89f83a3d72152748e20 | 650,711 |
def print_point_accuracy_info(accuracy_x_list, accuracy_y_list, boundary_index_list):
"""
print accuracy info
"""
max_edge_x = 0.0
max_edge_y = 0.0
max_center_x = 0.0
max_center_y = 0.0
for i in range(len(accuracy_x_list)):
if i in boundary_index_list:
if accuracy_... | f6420fb95d40790e7d6e2711ffe55d2e23042599 | 650,712 |
def container_name_for(image, application_id):
"""
Get a name for a service container based on image and application ID
Parameters:
image - image that the container is for
application_id - application id that the container is for
Return value:
A string
"""
return image.... | 651ad10fe0b1578f8ba79affc249199ca20b932d | 650,713 |
from datetime import datetime
def date_cleanup(date):
"""Transforms date of form YYYYMMDD to datetime object.
Args:
date (Union[str, NoneType]): Date of the form YYYYMMDD to be transformed.
Returns:
``datetime.datetime`` object if given string.
Returns None if None is given.
... | 729b085aba90d11e2105a5fc55d0a5b1a9845dc6 | 650,714 |
def does_user_wants_to_continue():
"""
This method will ask for the user input to continue or to stop
Returns :
True if user wants to continue
False otherwise
"""
choice = input('Enter n to stop and any other key to continue :')
if choice == 'n':
return False
return T... | 5e49ba3629cc99ec25af771830c6ecf8e989cfe5 | 650,715 |
def get_stat2_from_data(data):
"""Find the max number of continuous frames when position error is lager
than 30cm, 20cm and 10cm
Arguments:
data: error array
Returns:
stat: array of max number of continuous frames
"""
max_con_frame_num_10 = 0
max_con_frame_num_20 = 0
... | 03ea1e386239d1b761ab8e01fbb2b71226dbc5e3 | 650,716 |
import re
def decode(name):
"""Unescape a string encoded by the escape function defined above"""
ptrn = r'([a-yA-Y0-9]*)(?:z([0-9a-f]{2})|Z([0-9a-f]{8}))?'
if not re.fullmatch(f'({ptrn})*', name):
raise ValueError(f"not a z-encoded string: {name}")
decoded = []
for m in re.finditer(ptrn,... | 3530dd49b0015fd04ebd9507ce247a899ac577eb | 650,717 |
def comma_to_dot(comma_number: str) -> float:
"""Transform the decimal separator from comma to dot.
Args:
comma_number: number as a string with comma as a decimal separator
Return:
The dot-separated number corresponding to the given one.
"""
return float(comma_number.replace(',', '.')) | 150d5f6b3f16d68cb885e9a12116f4e4534fc4e4 | 650,718 |
import hashlib
def password_hashing(password):
"""
The function generates the SHA-1 hash of a UTF-8 encoded password given by
user
"""
sha1pass = hashlib.sha1(password.encode('utf -8')).hexdigest().upper()
# Inorder to maintain anonymity while sending password to the API,
# storing only the par... | da1fe9da65f1b37be3409f60d6ac47a33943c352 | 650,719 |
def fits_file(name, ra, my_dir):
"""Get the FITS file for a given source.
Parameters
----------
name : string
Source name.
ra : float
Right ascension.
my_dir : string
Working directory.
Returns
-------
string
Name of the FITS file of the field the so... | 633214d8fec9e5ae448b67b638d2661c3e83f0a2 | 650,720 |
def get_bytes(s):
"""Returns the byte representation of a hex- or byte-string."""
if isinstance(s, bytes):
b = s
elif isinstance(s, str):
b = bytes.fromhex(s)
else:
raise TypeError("s must be either 'bytes' or 'str'!")
return b | 99485b4beb67296bde391669d6a8c8db524f7094 | 650,721 |
def get_dates(df):
"""
given df, sort dates and get date_start and date_end
"""
df.sort('end_time', ascending=True)
date_start = df['end_time'].iloc[0]
date_end = df['end_time'].iloc[-1]
return date_start, date_end | bc22cc27ee73a42c01e4e7b8a0c3c215d5f69b2a | 650,722 |
import torch
def cRM_tanh_recover(O, K=10, C=0.1):
"""CRM tanh recover.
Args:
O (torch.Tensor): predicted compressed crm.
K (torch.Tensor): parameter to control the compression.
C (torch.Tensor): parameter to control the compression.
Returns:
M (torch.Tensor): uncompresse... | 59b1005eec4e0f13e3012ef40e0266a718a35d14 | 650,723 |
def _get_item_from_doc(doc, key):
"""
Get an item from the document given a key which might use dot notation.
e.g.
doc = {'deep': {'nested': {'list': ['a', 'b', 'c']}}}
key = 'deep.nested.list.1'
-> 'b'
:param doc dict:
:param key str:
:rtype: value
"""
if '.' in key:
... | 82a12365ff933cc88d769779c929a7f6a6b0cd66 | 650,724 |
def cmp_individual_scaled(a, b):
""" Compares two individual fitness scores, used for sorting population
Example:
>>> GPopulation.cmp_individual_scaled(a, b)
:param a: the A individual instance
:param b: the B individual instance
:rtype: 0 if the two individuals fitness score are the same,
... | 07fcbaf73621948ec8fe2c48e2e6a4f573203475 | 650,725 |
def prot_comp_composite(row):
"""Creates a composite column from the protein and compound IDs"""
composi = row["DeepAffinity Compound ID"] + "," + row["DeepAffinity Protein ID"]
return composi | c69f92a700133f03346998070d09ab0eeed349b6 | 650,726 |
import math
def num2si(x, format='%.15g', si=True, space=' '):
"""
Returns x formatted using an exponent that is a multiple of 3.
Parameters
----------
x : scalar
The number to format.
format : str
Printf-style format specification used to format the mantissa.
si : bool
... | 79fe73668736e13fe38915bbf55a1ff848b85824 | 650,727 |
from typing import List
from typing import Tuple
def process_data(data: str) -> List[Tuple[int, int, int]]:
"""Parse the raw data.
Convert raw triangle data:
1 2 3
4 5 6
Into list of tuples, where each item is a triangle with a, b, c sides
"""
triangles = []
for triangle in ... | dd82c6e8a603f185315283c48d9b571c155f2d3c | 650,728 |
def match_images(imageA, imageB):
"""Match two image objects. Return the ratio of pixels that match."""
histogramA = imageA.histogram()
histogramB = imageB.histogram()
totalMatch = 0
totalPixels = 0
if len(histogramA) != len(histogramB):
return 0
for i, hist_a in enumerate(histogr... | ddd00b6f6e9c4b2deb819396ce20697eb08aa5f8 | 650,730 |
import re
def simplify_column_name(column_name, delimiter):
"""
simplify all the columnname by removing all non-alphabetic character
except number, and converting name into snake case
:param column_name: column name (str)
:param deliemter: delimiter that detected from detect_delimiter() (str)
... | 7ac021b5c566e89c8b21061ef085f9d9bece7e59 | 650,731 |
def check_enemy_ub(time_count):
"""check enemy ub
Args
time_count (int): count up after ub
Returns
is_enemy_ub (boolean): enemy ub existence
"""
if time_count > 9:
return True
else:
return False | d0f8873e9cd5819b4e87bb7eb5851542ffb80eb3 | 650,732 |
def str2int(s):
"""Convert a byte string to an integer.
@param s: byte string representing a positive integer to convert
@return: converted integer
"""
s = bytearray(s)
r = 0
for c in s:
r = (r << 8) | c
return r | 3e36ad6f0a47b06f1d80036b990976049d56749c | 650,733 |
def flaskify_endpoint(identifier):
"""
Converts the provided identifier in a valid flask endpoint name
:type identifier: str
:rtype: str
"""
return identifier.replace('.', '_') | f0100050c4cc5e2c20bf117bd38c3e9e0ed71972 | 650,735 |
def _standardize_package_name(raw_package_name):
"""Helper to convert the arbitrary ways packages can be represented to a
common (matchable) representation
"""
return raw_package_name.strip().lower().replace("-", "_") | e052432042d0e7d21c194fe4a1a7c65e63955267 | 650,736 |
import json
def get_json(content):
"""Decode the JSON records from the response.
:param content: the content returned by the eBird API.
:type content: http.client.HTTPResponse:
:return: the records decoded from the JSON payload.
:rtype: list
"""
return json.loads(content.decode("utf-8")... | 3e2e88063ddc730170212e635e11e64aca474a47 | 650,737 |
def data_is_encrypted(tasks_backup_job):
""" Returns True if the tasks data has been encrypted.
This assumes that the worker stores the encrypted AES key in
tasks_backup_job.encrypted_aes_key_b64
when the tasks are encrypted.
This will return False for any backup ol... | 4d8727f97be709aafd21d09be54e5090faad5e73 | 650,738 |
def get_first_label(x):
"""Returns the label of the first element.
:param x: Series or DataFrame
"""
return x.index[0] | 9c2c98cca3f163a01b9ce06fa75b516e9b84a49b | 650,740 |
def remove_backslash(txt: str):
"""take string and returns it without backslashes"""
return txt.replace("\\/", "/") | b9f760386115c8d4e431682818b5b765d3d13398 | 650,741 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.