content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def GetRanking(fname):
"""Get the ranking for this run"""
lines = [i[:-1] for i in open(fname)]
lines = lines[3:]
ranks = []
for line in lines:
try:
ranks.append(line.split()[-1])
except:
pass
return ranks | 128bbb5a7975ade5a7aa7c1dbcc2a45e2d6e3ad3 | 627,059 |
import subprocess
import sys
import os
import signal
def run_and_echo(command):
"""
this just calls the command, and returns its return code,
allowing stdout and stderr to work as normal. it is used
as a fallback when environment variables or python
dependencies cannot be configured, or when the l... | 814fbc84cf4d1e943247ab81e69c9a14ec2dc0eb | 627,060 |
def has_prefix(words, sub_s):
"""
:param sub_s:
:return:
"""
for word in words:
if word.startswith(sub_s):
return True | f7e2642321701249150213159626dfc817292d2c | 627,061 |
import re
def partition_quote(quote,words):
"""
Divide quote in 2 parts if it will not fit in 1 tweet.
:param words: The minimum number of words for 1st part.
See https://regex101.com/r/uZeBmC/1 for regex details.
"""
pattern_string = r"^(.{"+str(words)+r"}[^\.\,\;\:\-\_\n\#\!\@\$\%\^\&\*\(\)\... | 96bb4fbd002e4c15e63649abf5942548fcf50de0 | 627,062 |
def convert_numeric_list(str_list):
"""
try to convert list of string to list of integer(preferred) or float
:param str_list: list of string
:return: list of integer or float or string
"""
assert isinstance(str_list, list)
if not str_list:
return str_list
try:
return l... | 3eefde31b1e9ac2758efa3f4111d2c1b70df50eb | 627,063 |
def sort_box(box):
"""
对box进行排序
"""
box = sorted(box, key=lambda x: sum([x[1], x[3], x[5], x[7]]))
return box | f9475c881df14feb45e476f67225bd480471526e | 627,064 |
def hashstring(s):
"""Compute a string hash based on the function "djb2".
Use at most 64 characters.
"""
h = 5381
s = s[0:64]
for c in s:
h = ((h << 5) + h + ord(c)) & 0xffffffff
return h | a0803a38c52c12346c5b362e1db9be9d6ddc8fcf | 627,066 |
import math
def comb(n, k):
"""We use this custom function to avoid pytest warnings for Scipy
built against wrong libraries that sometimes comes up."""
return math.factorial(n) // math.factorial(k) // math.factorial(n - k) | 155f6b5d2145af9de69bb94da7b450088a6ee110 | 627,067 |
def eiffel_activity_triggered_event():
"""Eiffel activity triggered event."""
return {
"meta": {
"version": "3.0.0",
"source": {"name": "eiffel-graphql-api-tests"},
"type": "EiffelActivityTriggeredEvent",
"id": "6a1abb6e-2c13-4a82-8fe2-012f8fe7c541",
... | dff95353a38b8435bb2161fbc3ebe0beed1e2ad0 | 627,068 |
def get_programming_language(repo_info):
"""Return programming language used for repository"""
try:
return repo_info.find('span', {'itemprop': 'programmingLanguage'}).text.strip()
except AttributeError:
return | 5e0b76599ed023088de62ac4625b60fe3339d981 | 627,069 |
def find_missing(*args):
"""
If True then missing value is there
"""
for value in args:
if value == None or value == '':
return True
else:
return False | c3110b52d1c2277299c1c90c6e7267b19b5e4249 | 627,070 |
def find_python_in_context(context):
"""Find Python executable within the given context.
Args:
context (ResolvedContext): Resolved context with Python and pip.
name (str): Name of the package for Python instead of "python".
default (str): Force a particular fallback path for Python exec... | 92f88310f3eb134b4ba7caa4c1044b1397c4cf91 | 627,071 |
import click
def email_option(help_message, long="--email", short="-e", name="email", required=True):
"""
Email option standard definition.
Use as decorator for commands.
"""
return click.option(
long,
short,
name,
required=required,
type=str,
help=... | 7fecba302ebf1a81cba08a54cb52774348152427 | 627,072 |
def shellescapespace(s):
"""Escape spaces for shell."""
return s.replace(" ", "\\ ") | 4f3d9a1c43c1894759216662d8ee1ba37ff26438 | 627,073 |
def find_level_sections(alts):
"""
Find pairs of start/finish indicies of consecutive altitudes with the same
value. I.e. where an aircraft was in level flight.
Parameters
----------
alts: float array
An array of altitudes[feet]
Returns
-------
level_indicies: a list of ind... | ed80b0fe8c9e9debaf3959a19a49a7d14d6ddf52 | 627,074 |
def anscombes_quartet_p(anscombes_quartet, anscombes_pval):
"""Anscombe's quartet and its p-values"""
return zip(anscombes_quartet, anscombes_pval) | a84e15fa2f3717b176f8efee5f7851932dbd0c83 | 627,075 |
def make_links(line):
"""Split a line into parts, return a dictionary of chain links."""
link_parts = line.split(";")
chain_dict = {
k: v for k, v in tuple([x.split('-') for x in link_parts])
}
return chain_dict | 1bc521e5e792c9f880f96704bc1846fca520b3fe | 627,076 |
import torch
def one_hot_encoding(input_tensor, num_labels):
""" One-hot encode labels from input """
xview = input_tensor.view(-1, 1).to(torch.long)
onehot = torch.zeros(xview.size(0), num_labels, device=input_tensor.device, dtype=torch.float)
onehot.scatter_(1, xview, 1)
return onehot.view(list... | dbcb5e06e31f8ad43b740f78ddb87a4c7b665dcb | 627,078 |
import os
import re
def n_available_gpus() -> int:
"""
Return the number of NVIDIA GPU devices available to this process.
.. note::
This method attempts to parse (in-order) ``CUDA_VISIBLE_DEVICES`` env variable (bare sheep) and
``NVIDIA_VISIBLE_DEVICES`` env variable (docker sheep).
... | e34f31289fdd7c0e38e636eb1f7787d8dae94c10 | 627,079 |
def comment_tokenizer(data):
"""Tokenizes across single and multi-line comments."""
tokens = []
start_index = 0
size = len(data)
in_singleline_comment = False
in_multiline_comment = False
for index in range(size):
if index == size - 1:
# Reached end of string, append whatever we have left.
... | e7347480b47072fc27ff0456dcb65f321f34b11c | 627,080 |
def clean_text(text):
"""
Remove most punctuation from string and make it lowercase
:param text: String
:return: String with cleaned up text
"""
text = text.lower()
text = text.replace("!", " ")
text = text.replace("?", " ")
text = text.replace(";", " ")
text = text.replace('"', ... | bb08ce63485bc77ef7f082f9f916c543e12301fd | 627,081 |
def learn(model,cfg,encoder_input_data, decoder_input_data, decoder_target_data):
"""
## Train the model
"""
#model.summary()
history=model.fit(
[encoder_input_data, decoder_input_data],
decoder_target_data,
batch_size=cfg['batch_size'],
epochs=cfg['epochs'],
validati... | a613e2d30013d707df9bd78345903bc8469a1d32 | 627,082 |
def maybe_combinatorics():
"""
From 'A Pythonic Card Deck' by Luciano Ramalho (https://github.com/fluentpython/example-code-2e)
"""
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
rank_suit_tuples = [(rank, suit) for suit in suits for rank in ... | 438e2aa97aed49194488f444159160b5a3f504fa | 627,084 |
import math
def convert_outline(pts, origin):
"""
Convert 2d points fiducial curve from list of points into proper OCP format
"""
xow = list()
yow = list()
xiw = list()
yiw = list()
thickness = 2.0
rprev = 111111.0
for pt in pts:
y = pt.x
r = pt.y
if r... | ed2833ece6333a85f96ab8a17eb35122029e7386 | 627,085 |
def read_hex(field: str) -> int:
"""Read a hexadecimal integer."""
return int(field, 16) if field != "" else 0 | 59c3f1c39647b3186f4f4efa1bded53f0a6ed788 | 627,086 |
def bwtc_scaling_factor(order):
"""Return the appropriate scaling factor for bandwidth to timeconstant
converstion for the provided demodulator order.
"""
scale = 0.0
if order == 1:
scale = 1.0
elif order == 2:
scale = 0.643594
elif order == 3:
scale = 0.509825
e... | 8b88eccfa37df1c8e49fe82c0f1a87b0e26ef101 | 627,088 |
import argparse
def parse_args():
"""
:description: Parse command line arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-f', dest='feature_set', default='all',
help="""{'all', 'hist', 'gist'}""")
parser.add_argument('-l', dest='loss', default='hinge',
... | f51e7da0e834067b99e76f515dc0d909265564d8 | 627,089 |
import re
def config_read(filename, delim='=', doValueSplit=True):
"""
Read a configuration file and output a 'KEY=VALUE' dictionary.
"""
configTable = {}
CONFIGFILE = open(filename, "r")
# Compile a few useful regular expressions
spaces = re.compile('\s+')
commaAndSpaces = re.co... | 55348d77866704a437181529a86110c442aed6c1 | 627,092 |
def sum_pairs_hm(ints, s):
"""using dict for memoization"""
find_pair = {}
for val in ints:
pair = s - val
if pair in find_pair:
return [pair, val]
else:
find_pair[val] = pair | 7cd7054f92a92064508a265a8d0e6651d56f6985 | 627,093 |
from typing import Any
def get_category(parameter_meta: Any, input_name: str,
category_key: str = "category",
fallback_category: str = "other") -> str:
"""
:param parameter_meta: A dictionary containing the parameter_meta
information.
:param input_name: The name of th... | 6eba16b078f0bf5ae5fabf0e46621d2fe3aadc9b | 627,095 |
def remove_start(s: str, start: str):
"""
Helper function to remove the beginning of a string.
:param s: the string to remove the prefix from.
:param start: the prefix of the string to remove.
:return: s with the start of the string removed.
"""
assert s.startswith(start)
return s[len(st... | ab831976fa0e56ae91544f1a635805eb1d928970 | 627,096 |
from typing import OrderedDict
import platform
def get_info_python():
"""Python information."""
info_py = OrderedDict.fromkeys(["version", "implementation", "compiler"])
for k in info_py:
func = getattr(platform, "python_" + k)
info_py[k] = func()
return info_py | 43b16cb5fc5fd29a32a5ec544bf6c0020905a6a7 | 627,097 |
def projects_q(project):
"""Return the gerrit query selecting all the project in the given list
:param project: List of gerrit project name.
:type project: list of str
:return:
gerrit query according to `Searching Changes`_ section of gerrit
documentation.
:rtype: str
.. _Searc... | 98c93c289c6e084d29c50690ddfdd85ad0650a07 | 627,098 |
import pickle
def pickle_bridge(A,B):
"""
If you want to save the output,
The following can be set to False
"""
if True:
return A,B
info = A['info']
with open(f"info.pickle", "wb") as f:
pickle.dump(A, f)
return A,B | eda299820a5919b9c5ffa76b1c5f732155e2bd4e | 627,099 |
import argparse
def ParseCommandTransformix():
"""Function for parsing command line arguments for input to transformix
"""
#if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--in_im')
parser.add_argument('--out_dir')
parser.add_argument('--tps', nargs='*')
parser... | 15d1b09129e35ebb9ced5231fd07f1aad1a4a305 | 627,100 |
def DataMarkedCB(gamedata, cb, columnname='iscb'):
"""Game data with constant steps: it marks steps of game with "it's CB of the player i" or not. V.1.2"""
df = gamedata.copy()
res = []
for row in gamedata.itertuples(False):
#t = cb[(cb['game']==row.Game)]
#t = t[t['subject']==row.GrSubj... | f83f250a3f63c8dedbcf562f0235fb0f329ebbff | 627,101 |
from typing import List
def array_manipulation(n: int, queries: List[List[int]]) -> int:
"""
>>> array_manipulation(5, [[1, 2, 100], [2, 5, 100], [3, 4, 100]])
200
>>> array_manipulation(4, [[2, 3, 603], [1, 1, 286], [4, 4, 882]])
882
>>> array_manipulation(10, [[1, 5, 3], [4, 8, 7], [6, 9, 1]... | a0def0a36b1764bf5ea7d0ee48f0bae175a0a0b8 | 627,102 |
def square_to_condensed(i: int, j: int, n: int):
"""Convert a square matrix position (i, j) to a condensed distance matrix index.
Args:
i: Index i.
j: Index j.
n: The dimension of the matrix.
See Also:
https://stackoverflow.com/questions/13079563/how-does-condensed-distance... | d940df40d91c2ba943c3131a53acb00b1bd50f9f | 627,103 |
import textwrap
def sample_project_path(tmp_path):
"""Create a sample project to be cleaned."""
source = """
import pytask
@pytask.mark.depends_on("in.txt")
@pytask.mark.produces("out.txt")
def task_dummy(produces):
produces.write_text("a")
"""
tmp_path.joinpath("task_dummy.py... | 3c77d277114810a0f5ca8dc6ce6ec09f9ce57f11 | 627,104 |
import os
def _build_bundleitems_get_request(player_id, bundle_name, bundle_item_key):
"""
Build the Bundle Items query request.
"""
player_id_bundle = f'{player_id}_{bundle_name}'
return {
'Key': {
'player_id_bundle': {'S': player_id_bundle},
'bundle_item_key': {'... | 770ba9dd652cbdea2cbceab0771533413ee9426b | 627,105 |
def timespan_lte_timespan(ts1, ts2):
""":yaql:operator <=
Returns true if left timespan is less or equal to right timespan,
false otherwise.
:signature: left <= right
:arg left: left timespan object
:argType left: timespan object
:arg right: right timespan object
:argType right: timesp... | b58b4b1c1fd4669da3d3fb3a44d488bde2250dd8 | 627,106 |
def str_to_bool(val):
"""
Convert a string representation of truth to True or False
True values are 'y', 'yes', or ''; case-insensitive
False values are 'n', or 'no'; case-insensitive
Raises ValueError if 'val' is anything else.
"""
true_vals = ['yes', 'y', '']
false_vals = ['no', 'n']
... | 9764fed734a48e6ec7c434d827feebccd5f0c137 | 627,107 |
def transform(subject: int, loop_size: int) -> int:
"""Transform the ``subject`` in ``loop_size`` steps of a hard-coded algorithm."""
value = 1
for _ in range(loop_size):
value *= subject
value %= 20201227
return value | a5bf5a85eccc26d0dde4afea36a4e0db7153dda3 | 627,109 |
import asyncio
import functools
import sys
async def sync_to_async(function, *args, **kwargs):
"""Convert synchronous method to async, using threads.
Credit for this function goes to https://github.com/django/asgiref
and their SyncToAsync class.
:param function: Function or method to call.
:type... | 6022b49d1f370d5fdd5c367149d1eb671c0c16d1 | 627,110 |
def solidsFluxPembWake(rhop, emf, umf, us):
"""
Calculates the solids entrainment flux for the surface of a bubbling bed
with the bubble wake ejection model of Pemberton and Davidsion (Chem. Eng.
Sci., 1986, 41, pp. 243-251). This model is suitable if multiple bubbles
coalesce at the surface before ... | 75f37822587b788234dd39ea546482f4ce6b509c | 627,111 |
from pathlib import Path
def get_test_script() -> Path:
"""
Returns the full path to a testing script that lives inside of the test suite.
:return:
"""
current = Path(__file__).parent
script = current / "script_for_tests.py"
assert script.is_file(), f"File {script} not found"
return sc... | ea0fb2a7c60fe8089090b48cf90f47a7c457c78b | 627,113 |
def add(x, y):
"""
Binary Adddition bing carried out
"""
carry = ""
result = ""
carry = "0"
for i in range(len(x) - 1, -1, -1):
a = carry[0]
b = x[i]
c = y[i]
if a == b and b == c and c == '0':
result = "0" + result
carry = "0"
... | 98244752a91f436726347aa78258f115d2e39466 | 627,114 |
def solution(A): # O(N)
"""
Write a function to find the most common number.
>>> solution([4, 4, -5, 3, 2, 3, 7, 7, 8, 8])
[4, 3, 7, 8]
>>> solution([-1, -2, -15, -1, -2, -1, -2])
[-1, -2]
>>> solution([1, 1, 1, 1])
[1]
"""
freq... | 3960e012d4e785ca18fc9e1059736e040508fa71 | 627,115 |
def get_table_b_1_b():
"""表 B.1 居住人数 4 人における照明設備の使用時間率 (b) 休日在宅
Args:
Returns:
list: 表 B.1 居住人数 4 人における照明設備の使用時間率 (b) 休日在宅
"""
table_b_1_b = [
(0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00),
(0.00, 0.00, 0.0... | 98865c18f75cccc18fc26e5c051585ed9acf2d99 | 627,116 |
def load_words(filename):
"""
Load word list from the file named filename.
Returns a list of strings.
"""
return [] | 6f139abcadaf7344ad2632217bba9b40c05421dc | 627,117 |
import subprocess
import json
def projects():
"""
Lists available projects
See: https://docs.aws.amazon.com/cli/latest/reference/devicefarm/list-projects.html
"""
try:
response = subprocess.check_output(['aws', 'devicefarm', 'list-projects',
'--n... | 477a81568e760ba280391b50080caaca1127f57e | 627,118 |
def get_email_txt_signature():
"""
Get email signature.
Args:
None
Returns:
String: Email signature.
"""
ret = '\n'+\
'SmartAlpha Team'+\
'\n'+\
'Taatu Ltd.'+\
'\n'+\
'27 Old Gloucester Street, London, WC1N 3AX, UK'+\
'\n'
return ret | 554556de1d3497c2394cd913a310ccc7413b8b24 | 627,119 |
def simpson_index(data: list):
"""考虑了 variety/balance,Simpson(1949),有关Simpson Index的名称(叫法),
在不同的地方有不同的形式,请参考链接 http://www.countrysideinfo.co.uk/simpsons.htm。
Simpson Index 衡量个体被分类时的集中程度,描述从一个群落中连续两次抽样所得到的个体属于同一种的概率
SI 的值域为[0, 1],0意味着无限多样性,1意味着没有多样性,即值越大,多样性越小。
由于该形式的定义通常成反比,因此,通常使用 Inverse Simpson ... | 99f0ec2c79a20ba81f5012fe276329c3af56ca39 | 627,120 |
import torch
def axis_angle_into_quaternion(normalized_axis, angle, device=torch.device("cpu"), dtype=torch.float32):
"""
Takes an axis-angle rotation and converts into quaternion rotation.
https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
:param normalized_axis: Axis of rotation ... | 1defb1f5410cb97ffe29b4e6a94e334088f94d18 | 627,121 |
def constraint_subset(c1, c2):
"""Determin whether c1 is a subset of c2.
"""
min_bn1 = c1.min_bn
max_bn1 = c1.max_bn
min_bn2 = c2.min_bn
max_bn2 = c2.max_bn
if min_bn1 >= min_bn2 and max_bn1 <= max_bn2:
return True
else:
return False | 40d6c610acbcdc72e1ea0992942fb88eacff7f2a | 627,122 |
def get_original_caps(modelinfo):
"""
Reforms the capacity pd.Dataframe to be used consistently.
Returns pd.Series that is reformed.
"""
e_cap = modelinfo['e_cap'].transpose()
original_cap_frame = e_cap.unstack()
return original_cap_frame | d8afad0af9a71db8d59dfcbddd06635af89f2970 | 627,124 |
def for_entities_in(container):
""" Receives messages sent to a target inside the specified container.
:param container: A container whose entities' messages will be received.
"""
def filter(target):
if target.container == container: return True
if target == container: re... | 9d9538a6b1cc15b71ba4a287189e485c6efbbd45 | 627,125 |
import subprocess
def get_contigs(vcfpath):
"""Get list of contigs"""
chrs = subprocess.check_output('tabix --list-chroms '+vcfpath, shell=True, executable='/bin/bash')
return chrs.decode().strip().split() | 53515aeb9f2215c6de65c847e6851028e3583e50 | 627,126 |
def execution_time(result):
"""Return the execution time of a query."""
avail = result.summary().result_available_after
cons = result.summary().result_consumed_after
return avail + cons | d91a237962a45c1d2a128dddd07d7770a3c4b736 | 627,127 |
def _map_to_github_url(source):
"""
Returns a path to a downloaded GitHub archive.
:param source: GitHub repo: ``org/repo[:tag/branch]``
:type source: basestring
:return: URL to the archive file for the given repo in GitHub
:rtype: basestring
"""
source_parts = source.split(':', 1)
... | f887567ccb1d2d17cedb80a61d5da1cd0b0ee3eb | 627,129 |
def determinant(matrix):
"""
Calculates the determinant of a matrix.
matrix is a list of lists whose determinant should be calculated
If matrix is not a list of lists, raise a TypeError with the message
matrix must be a list of lists
If matrix is not square, raise a ValueError with the message ... | c02378da8f9cf8ae00cea4ee8c58ee7dad87ecde | 627,130 |
import operator
def find_lowest_pq(df):
"""
This is an auto-ARIMA function that iterates through parameters pdq and finds the best
based on aan eval metric sent in as input.
This finds the row and column numbers of the lowest or highest value in a dataframe. All it needs is numeric values.
It wil... | db85da7a242fb03d695e61318e379ec3bed7351e | 627,131 |
def get_memory_scratch():
""" Returns largest ramdisk available on this machine to this user."""
# ugly
return '/dev/shm' | 04d8b772eb86f6a0b8f1dbc9cb0f37616791f714 | 627,133 |
def locking_depth_manager(segment, command):
"""
This function assigns the locking depths given in the command file to any
segment that has the same locking depth flag. Segments with flag =
0, 1 are untouched.
"""
segment = segment.copy(deep=True)
segment.locking_depth.values[
segme... | 2965736b41f1ca801cd3ed36fc25f45b60ea0c9f | 627,134 |
def make_args(opts):
"""
Converts a dict to a helm-style --set and --set-string arguments.
Helm allows you to set one property at a time, which is desirable because
it's effectively a merge.
The drawback is the redundancy and readability.
This function allows a dict to represent all of the optio... | 1eed4952eaf8758c64f9f10b17ffc3c4242184a2 | 627,135 |
def validate_cli(cli_string, expect=None, reject=None, ignore=None, possible_expect=None, retval=0):
"""
Used to mock os.system with the assumption that it is making a call to 'conda-build'.
Args:
cli_string: The placeholder argument for the system command.
expect: A list of strings that mu... | 194e46f96a2bc5472ae56a0f407d9f327e87e8e6 | 627,136 |
def get_substitute_lines(text):
"""Helper functionality to split on filter."""
substitute_lines = []
for line in text.splitlines():
regex_replacement, regex_search = line.split("|||")
substitute_lines.append({"regex_replacement": regex_replacement, "regex_search": regex_search})
return s... | 809643dabe78f375ce8250b71097ede892d9bc85 | 627,137 |
def do_files_to_copy_contain_entry_with_src(files_to_copy, src):
"""Searches the files to be copied for an entry with src field that matches the given src."""
is_present = False
for file_to_copy in files_to_copy:
if file_to_copy.src == src:
is_present = True
break
return ... | a46ab3e264ddd6d3014faaf730ec393117c989cf | 627,138 |
from typing import Dict
from typing import Tuple
def parse_header_and_separator(
header: str, separator: str
) -> Dict[str, Tuple[int, int]]:
"""Parse header and separator and return {field: (start, end)}"""
headers = header.split()
separators = separator.split()
field_to_start_end = {} # type: D... | 22f8da1cda2210a4e1f22f3b1a3722278449c9f4 | 627,139 |
def openTypeNamePreferredSubfamilyNameFallback(info):
"""
Fallback to *styleName*.
"""
return info.styleName | a69b1c0d2f33e8908d8d49a8cf604e7370916696 | 627,140 |
import csv
def get_entities_sentence_expert(dataset_file, sentence):
"""
:param dataset_file:
:param sentence:
:return: sentence : [[entity1, id, char1, char2], [entity2, id, char3, char4],
relation], [[entity1, id, char1, char2], [entity2, id, char3, char4],
... | 043a6e29fa538cfbbd3ba99ad2f8c19d227e85b7 | 627,141 |
def parse_performance(f_element):
"""
helper function to the constructor, parses xml entries
@param f_element: element to parse
"""
# inicia o dicionário de dados
ldct_tmp = {}
# handle descrição
if "descricao" == f_element.tagName():
ldct_tmp["descricao"] = f_element.text()
... | ebacbea7c21ecc60719354c7396445159a745f1b | 627,142 |
import wave
def extract_start_end(audio_file):
"""
Extracts the first and last two minutes of an audio file. Two temporary
files are returned that contain the start and end clips.
"""
wav = wave.open(audio_file, "rb")
clip_frames = 120 * wav.getframerate()
frames = wav.readframes(clip_fra... | 5f2e1af6e9f8a667e4b3ee11d3f282cad6b80de7 | 627,143 |
import hashlib
def get_hash(string, length=8):
""" Shortcut for generating short hash strings """
return hashlib.sha1(string.encode("utf-8")).hexdigest()[:length] | 869b699b39cea700adebc9e233f6b0bf8fd59f95 | 627,145 |
def get_filenames_in_release(manifestdict):
"""
<Purpose>
Get the list of files in a manifest
<Arguments>
manifestdict: the manifest for the release
<Exceptions>
TypeError, IndexError, or KeyError if the manifestdict is corrupt
<Side Effects>
None
<Returns>
A list of file names
"""
filenamelist =... | 5c1fea416f8e08cd9ec735036e69cee8845de497 | 627,146 |
def zero_matrix(matrix):
"""
Make INPLACE row and column of a matrix 0 iff that row contains a 0
"""
position_of_zeros = []
row = len(matrix)
col = len(matrix[0])
for i in range(0, row):
for j in range(0, col):
if matrix[i][j] == 0:
position_of_zeros.appen... | 07b6b5f52b1a44fb128a720f44262c5986720a27 | 627,148 |
import re
def parse_function_definition(deftxt: str) -> tuple[str, str]:
"""Parse a function definition"""
# Connect multiple lines if so
deftxt = re.sub(r'\n\s*', ' ', deftxt, flags=re.M)
# Split the definition line to the function name and the variables definition
function_name, variables, _ ... | 317a17692fadfc2c54e92b0fd6f2f26da632906e | 627,149 |
import sys
def flow_to_iter(flow):
"""Convert *flow* to support both ``__iter__`` and ``next``.
*flow* must be iterable.
If that doesn't support ``next`` (for example, a list),
it will be converted to *iter(flow)*.
Works for Python versions 2 and 3 (where next is different).
"""
if (... | 8c9953788d4d0b6bd7e33e130f276a067fe8f6c2 | 627,150 |
def set_linebreaks_and_tabs(instring):
"""
Sets line breaks and tabs around SQL reserved words
"""
# Step 1: initialize ignoreflag to False
ignoreflag = False
# Step 2: force multi-word SQL special syntax to behave like a single word
instring = instring.replace('INNER JOIN', 'INNER JOI... | 4c3aa06c96af27ce303d2cbdb4d8f450cb158bb8 | 627,152 |
def _mirrorpod_filter(pod):
"""Check if a pod contains the mirror K8s annotation.
Args:
- pod: kubernetes pod object
Returns: (False, "") if the pod has the mirror annotation,
(True, "") if not
"""
mirror_annotation = "kubernetes.io/config.mirror"
annotations = pod["metadata... | a07a6ff924a44e57d1ffc8af1e40b0b80d1307e8 | 627,153 |
def _find_clusters(mst_graph, vertices):
"""Find the cluster class for each vertex of the MST graph.
It uses the DFS-like algorithm to find clusters.
Args:
mst_graph (dict): A non-empty graph representing the MST.
vertices (list): A list of unique vertices.
Returns:
A l... | 9ff6e4f3a15bf3c855622e5d80731d9c578d55e9 | 627,154 |
def flat_suite(suite):
"""Convert a suite object into flat testcase list."""
tests = []
countSuite = 0
def flat_subSuite(rootSuite, suiteName = []):
# count suites
nonlocal countSuite
countSuite += 1
if rootSuite.sub_suites:
for suite in rootSuite.sub_suites:
... | 3905722fd462481b4163a90d2f98799c466dfb2f | 627,155 |
import collections
import six
def _get_final_text(pred_text, orig_text, tokenizer):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# no... | 7c725e47b4c1ade93ba383c528fd662ee1829eef | 627,156 |
def atoi(v):
"""Convert v to an integer, or return 0 on error, like C's atoi()."""
try:
return int(v or 0)
except ValueError:
return 0 | bea39b0b9a41c9f48e653cc835aad05e0378f3bf | 627,157 |
import time
import random
def rand_wait_for_element(browser, xpath, additional_max=0):
""" Waits for xpath and adds random wait of 1 to additional_max sec
"""
present = browser.is_element_present_by_xpath(xpath)
if present:
time.sleep(random.random() * additional_max)
return True
e... | 300fb85e11b145aa010a02e176002600994bab55 | 627,158 |
import os
def _free_disk_space_for(path):
"""Get free disk space on a drive where path is located."""
stat = os.statvfs(path)
return stat.f_frsize * stat.f_bavail | 1d99663733ec0bed3c855a44e6df8484f81abc31 | 627,159 |
def get_control_latex(model):
"""
Get the labels for each Hamiltonian.
It is used in the method method :meth:`.Processor.plot_pulses`.
It is a 2-d nested list, in the plot,
a different color will be used for each sublist.
"""
num_qubits = model.num_qubits
num_coupling = model._get_num_co... | 2e2c003c0ee3d1b0424d092ed9c1a48280b46ccf | 627,160 |
def filterGridCircle(points, n, radius):
"""Returns points inside circle. Points outside are set to NaN."""
# Code ported from
# https://github.com/Smoothieware/Smoothieware/blob/c398f3aa9d2bd6ac2c9328ef0bc08429788d6203/src/modules/tools/zprobe/DeltaGridStrategy.cpp
res = points.copy()
d = ((radius... | 96b9a92b13839a5662703aa22e8953cc7226b4c4 | 627,161 |
def lr_poly(base_lr, curr_iter, max_iter, warmup_iter=0, power=0.9):
"""Polynomial-decay learning rate policy.
Args:
base_lr: A scalar indicates initial learning rate.
curr_iter: A scalar indicates current iteration.
max_iter: A scalar indicates maximum iteration.
warmup_iter: A scalar indicates th... | 47cea1789b6cc7c32c8e99fb9b5eb0f8c1083791 | 627,162 |
def periodic(t, T):
"""
Returns equivalent time of the first period if more than one period is simulated.
:param t: Time.
:param T: Period length.
"""
while t/T > 1.0:
t = t - T
return t | 0e3a5788ae795e00cb9962181774829947142a1b | 627,163 |
import tempfile
import subprocess
def do_screenshot(url):
"""
Screenshot an `url` (fullscreen) and return a path to an image.
:param url: A previously validated URL of a webpage to capture.
:return: A Path-like object representing a screenshot.
"""
_, path = tempfile.mkstemp(suffix='.png')
... | 545395b83edeb332fb43651ea5e77f4ea3d9a4bd | 627,164 |
from typing import Mapping
def has_node(g: Mapping, node, check_adjacencies=True):
"""Returns True if the graph has given node
>>> g = {
... 0: [1, 2],
... 1: [2]
... }
>>> has_node(g, 0)
True
>>> has_node(g, 2)
True
Note that 2 was found, though it's not a key of ``g... | f8dcb4ea41904f5e836fb44df83b2acf88f12de2 | 627,165 |
from typing import Optional
def next_batch(limit: int, offset: int, total: Optional[int]) -> bool:
"""Is there a next batch of resources?"""
if total is None:
return True
return (total - offset) > 0 | 51febba2c3732bf9c1896b3fd31d4b9d5503c8e2 | 627,166 |
def ParseMaterial(st):
"""
"""
st = st.replace('material', '')
st = st.replace('Material', '')
st = st.replace('{', '')
dst = st.split(',')
d = {}
for s in dst:
# print s
u = s.split(' ')
# print u
sp1 = st.split('diffuseColor')
t = sp1[1]
ts = t.spli... | 0cea4fe17326afd74a64c95cf0b6b1ac4e03e66f | 627,167 |
import os
def relpath(path, start=os.curdir):
"""Return a relative version of a path
copied from python 2.6 posixpath (unavailable in 2.5)
"""
if not path:
raise ValueError("no path specified")
start_list = os.path.abspath(start).split(os.sep)
path_list = os.path.abspath(path).split(... | bcb6b725f33120c325ba44bf3af4b63b81fa15c3 | 627,168 |
def score(word_list, lm):
"""
Use LM to calculate a log10-based probability for a given sentence (as a list of words)
:param word_list:
:return:
"""
return lm.score(' '.join(word_list), bos=False, eos=False) | 1b9430077460279cad4a429b723c9e7b8d2fd555 | 627,169 |
def check_get_child_flows(function_list, xml_flow_list, new_flow_list=None):
"""Get flow_list associated with function_list and xml_flow_list"""
if new_flow_list is None:
new_flow_list = []
for f in function_list:
for xml_flow, xml_function in xml_flow_list:
if f == xml_function:... | da176f80ce360166d982557a892df49f52705669 | 627,170 |
def same_type_and_id(first, second):
"""Same type and ID"""
return type(first) is type(second) and first.id == second.id | 32f92bc28b7bdef8a5c48a4250fda032742c4bde | 627,171 |
def process_datasets(datasets):
"""Return a list of datasets provided as a string
in GUI input or None if default 'All' is provided.
Args:
datasets (str): a string with coma-separated datasets names
Example:
>>> process_datasets("Data1,Data2")
['Data1', 'Data2']
"""
... | 2ddd14a4b05e22861849ff3fc0d519802d315d2b | 627,172 |
import math
def solar_declination(doy):
"""
Calculate the solar declination for a given day of the year
(Allen et al. 1998).
Parameters
----------
doy : int
Julian day of the year (-).
Returns
-------
float
Solar declination (rad).
"""
return 0.409 * math... | db1b6bbf38c69ffbb0b5f5ba47283cdf2cd7a4dd | 627,173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.