content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def teardown(teardown_method):
"""Decorator for declaring teardown methods for test cases."""
teardown_method._is_teardown_method = True
return teardown_method | 3d5465909020e55b433561479f5b00a8f3cdfe49 | 643,558 |
import os
def _is_raw(path):
"""Check if a path is a RAW file based on extension.
Args:
path (str): Path to check
Returns:
bool: True if ``path``'s extension is RAW, case insensitive.
"""
return os.path.splitext(path)[1].lower() == ".raw" | 87cb2ae026f65600a626826a647d6e54b8fce775 | 643,559 |
import subprocess
def invoke_shell(cmd_list):
""" Execute a list of hell commands. """
try:
output = subprocess.check_output(cmd_list, stderr=subprocess.STDOUT)
output = str(output, 'utf-8')
except subprocess.CalledProcessError as exc:
output = str(exc)
return output | 9fd29e4822fc511a0316340400d310ce0290e77e | 643,560 |
import math
def pi_five_decimals():
"""
030
Display pi (π) to five decimal places.
"""
return round(math.pi, 5) | 90649a0d794402c7b95b5f170a2c301bc2972f07 | 643,561 |
import re
def removeMultEspaços(string: str) -> str:
"""
Remove espaços ectras entre as palavras
Parameters
----------
string : str
string com multiplos espaços
Returns
-------
string : str
string com apenas um espaço entre palavras
"""
string_arru... | b522590855e6d2e4d1b95ca08912a2249c2dbf7b | 643,562 |
import os
def convert_file_list_to_directories(file_list: list) -> list:
"""
Takes a list of relative file paths and converts to absolute directory paths, making sure all
results are unique.
Args:
file_list (list): List of relative file paths to process.
Returns:
list: List of un... | 41941900d56e63bc7b1b8a75aa0620a96a098487 | 643,563 |
def setup_parser(parser):
"""
:param parser:
:return:
"""
return parser | fc0e39a23bfefdfd8d894e0bc1aee17b19ab3cc1 | 643,564 |
import os
def get_bpm(wav_file):
"""Gets the correct bpm based on the wav_file name. If the wav_file is not
contained in the JKU dataset, raises error.
Parameters
----------
wav_file : str
Path to the wav file to obtain its bpm.
Returns
-------
bpm : int
BPM of the pi... | 7c5ec539d3cf4ce494dcd26700dae621a8d3765b | 643,565 |
def arm_expand_prel31(address, place):
"""
address: uint32
place: uint32
return: uint64
"""
location = address & 0x7fffffff
if location & 0x04000000:
location |= 0xffffffff80000000
return location + place & 0xffffffffffffffff | cc96a94955efea001a1d18082c1799cd049a1467 | 643,566 |
import ipaddress
def check_if_valid_ipv4(pos_ip):
"""
Checks if ipv4 address is legitimate
:param pos_ip: A possible ip address
:return: Bool if the password is working or not
"""
try:
ipaddress.IPv4Network(pos_ip)
return True
except ValueError:
return False | 125669f374a98c8294e87286754a0af97994a75f | 643,567 |
import torch
def load_pretrained_embedding(words, pretrained_vocab):
"""从预训练好的vocab中提取出words对应的词向量"""
embed = torch.zeros(len(words), pretrained_vocab.vectors[0].shape[0]) # 初始化为0
oov_count = 0 # out of vocabulary
for i, word in enumerate(words):
try:
idx = pretrained_vocab.stoi[wo... | 4baa6d92ba21fb04a38f6e20373ade892cddd67e | 643,568 |
def parse_log(logfile, body, param):
""""
Parse log file for one of a body's initial conditions and return it. This
is useful for when a parameter is not outputted but one needs it later on
for bigplanet analysis.
Parameters
----------
logfile : str
path to the logfile
body : s... | ce8b7e4781175b7aa22d52f68d899b3744c04b49 | 643,569 |
import os
def ReadFile(filename):
"""Gets the contents of a file from either the app or static directory."""
directory = os.path.dirname(__file__)
try:
return open(os.path.join(directory, filename)).read()
except IOError:
try:
return open(os.path.join(directory, 'static', filename)).read()
e... | 353cc82eb7b21dae802a0d4bad2c41aaf904564c | 643,570 |
def generate_spec(key_condictions):
"""get mongo query filter by recursion
key_condictions is a list of (key, value, direction)
>>> generate_spec([
... ('a', '10', 1),
... ('b', '20', 0),
... ])
{'$or': [{'$and': [{'a': '10'}, {'b': {'$lt': '20'}}]}, {'a': {'$gt': '10'}}]}
"""
... | d6401eb4abab78f498e2a73fef1d5db8a2b0b9f6 | 643,571 |
import re
def _split_doc(doc):
"""
Split a document into a list of words.
Arguments:
doc: String which represents a document.
Returns:
words: List of words that apear in the document.
"""
doc = re.sub(r'\n', ' ', doc)
doc = re.sub(r'\{\{.*?\}\}', r'', doc)
doc = re.s... | 790d5c4b18f2bc033302408f7ef0c0e094d34457 | 643,572 |
from datetime import datetime
def convert_time_searchable(ts):
"""converts timestamps from time.time() into reasonably searchable string format"""
return datetime.fromtimestamp(ts).strftime("%Y%m%d%H%M%S") | a66402b526c897fb5a106744b7fd21d6565c5e76 | 643,573 |
import os
import random
def random_word(func=lambda w: True, wordsfile='/usr/share/dict/words'):
"""
Requires the UNIX words file in a typical location. Returns a single,
random word.
"""
if not os.path.exists(wordsfile):
raise RuntimeError('file not found: {}'.format(wordsfile))
with ... | e0ba0b3d78de3e7c8477345571b027ae4f100019 | 643,575 |
def bioconductor_tarball_url(package, pkg_version, bioc_version):
"""
Constructs a url for a package tarball
Parameters
----------
package : str
Case-sensitive Bioconductor package name
pkg_version : str
Bioconductor package version
bioc_version : str
Bioconductor ... | 78f93baa524f69efb3abf4d23a5286d42ecd5030 | 643,576 |
def unserialize_vars(sexpr):
"""Unserializing Jeeves-related variables.
"""
var_strs = sexpr[1:].split(';')
evars = {}
for var_str in var_strs:
if var_str != "":
var_val = var_str.split('=')
evars[var_val[0]] = bool(int(var_val[1]))
return evars | 57303a7f7c8296668297c919525a07820a67e0a8 | 643,577 |
import optparse
import pkg_resources
def mangle_call_args(args, argv):
"""Combine buildout and sys.argv parameters into one list."""
call_args = list(tuple(args) + tuple(argv))
parser = optparse.OptionParser(
usage="%prog [options] path utility [utility arguments]",
version=pkg_resources.... | c400d1d0ca286f6ee4f83a37f2944b4a6fcadd04 | 643,578 |
import functools
def memoize(obj):
"""Cache a function's return value each time it is called. If called later with the same arguments, the cached value is directly returned rather than reevaluated."""
# Initialize cache and obj.cache as an empty dict
cache = obj.cache = {}
# The decorator 'wraps'... | 3bd660f1bb7c594bffb8a775dac601c390bd8028 | 643,579 |
def i_hear_an_army():
"""Data fixture for Joyce's poem 'I Hear an Army'."""
return b"""I hear an army charging upon the land,
And the thunder of horses plunging, foam about their knees:
Arrogant, in black armour, behind them stand,
Disdaining the reins, with fluttering whips, the charioteers.
They cry unto... | c7725445d9a4538a7faf261ea0bca99e345fafee | 643,580 |
import os
def AdjustFilePathToBaseDirectory(filepath, base_dir):
""" Adjust filepath, `filepath` to base directory, `base_dir`.
This function for example, on inputs
filepath = '/a/b/c/d.txt', base_dir = '/a/b'
returns 'c/d.txt'
If either the filepath nor the base_dir passed in is not in its absolutized
... | f957844c746ada1cb3553e7b1462eef4a826e0ea | 643,581 |
def evaluate_using_acc(model, X_test, y_test, batch_size):
""" Evaluation function using accuracy.
# Arguments:
model: Model to be evaluated.
X_test: Inputs of the testing set.
y_test: Outputs of the testing set.
batch_size: Batch size.
# Returns:
Accuracy of the gi... | 51aa46c229ec257285263be0f72f6ec730901c27 | 643,582 |
def get_lift_location_work_list(LocationId): # noqa: E501
"""get_lift_location_work_list
Returns a list of all lift work for a specific location. # noqa: E501
:param LocationId: Specify the Location ID as a string in quotes.
:type LocationId: int
:rtype: LiftWork
"""
return 'do some magi... | 4fd47d07dc245eb597de516ce2b985a6d440876a | 643,583 |
import os
def get_filename_without_extension(pathname: str) -> str:
"""Get the filename from the pathname without the file extension.
Parameters
----------
pathname : string
The pathname which the filename will be extracted.
Returns
-------
filename : string
The filename ... | 0bd7ec1cf3af80d379e2692db6f90667150fbaee | 643,584 |
from pathlib import Path
import shutil
def data(tmp_path):
"""A temporary directory containing a copy of the files in data."""
data_dir = Path('tests/data')
for data_path in data_dir.iterdir():
shutil.copy(data_path, tmp_path)
return tmp_path | c217fdbfe6d0df0ef0bfd97b67fb1d47bd34653c | 643,585 |
def normalize(influences):
"""Normalize influences to [-1,1]"""
maximum = influences.max()
minimum = influences.min()
assert maximum > 0
if minimum < -maximum:
scale = -minimum
else:
scale = maximum
return influences / scale | 6b96a264a27073763f6860d0194101aaa2ac9545 | 643,586 |
def _calculate_mid_points(bounds):
"""
Calculate middle points based on the geometry bounds
Parameters
----------
bounds : array_like
array containing xmin, ymin, xmax, ymax
Returns
---------
x_mids : mid points of x values
y_mids : mid points of y values
"""
# Cal... | f194e03b03c81d42f9c4bd43f3044af473ad4bf7 | 643,587 |
def get_mapping_data(name, field, integral, region=None, integration='volume'):
"""
General helper function for accessing reference mapping data.
Get data attribute `name` from reference mapping corresponding to
`field` in `region` in quadrature points of the given `integral` and
`integration` type... | e029fdc6604b66f12381b966f1d89a607f3cbfc0 | 643,588 |
from datetime import datetime
import calendar
def formatted_timestamp_utc_time(timestamp_str, format_str):
"""
Converts a formatted timestamp timestamp string to UTC time
NOTE: will not handle seconds >59 correctly due to limitation in
datetime module.
:param timestamp_str: a formatted timestamp s... | c46efd70cc3a8417fbcc62c18ae551e25ebe7e53 | 643,589 |
def format_cpnet_knowledge(input_json: dict) -> str:
"""
@param input_json: dictionary representing one datapoint in the openpi dataset
@return: knowledge from conceptnet formatted as a string
"""
knowledge = input_json["knowledge"]
knowledge = knowledge if len(knowledge) <= 10 else knowledge[:... | 8a9dc598a9ec20dd8e112b108da0efe4f7db636b | 643,590 |
import socket
def get_fqdn():
"""
Get fully qualified domain name
CLI Example:
.. code-block:: bash
salt '*' network.get_fqdn
"""
return socket.getfqdn() | 06ded32e7aabb12c313d0a69e23e78186cd5867c | 643,591 |
def datetime_as_string(arr, unit=None, timezone=None, casting=None):
"""
datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
Convert an array of datetimes into an array of strings.
Parameters
----------
arr : array_like of datetime64
The array of UTC timestamps to... | cbbe6f9c779a3b5680f0fe00330f178c3432b097 | 643,592 |
def total_population():
"""
Total Population
Persons
This is just a simplification to make it easer to track how many folks
there are without having to sum up all the stocks.
"""
return 1000 | ca7b209e3dedba36fb83490fbec2e1c6bd529aaa | 643,594 |
def visualize_model_performance(model):
"""
This function creates a bar plot with score of the individual models and their labels.
Params:
reveal_best_classification_model type(function)
Output:
Barplot
"""
return model.plot(kind="bar") | e60c7c41a56e62cf2677e2e65881623d8897802a | 643,595 |
import itertools
def _get_permutations_draw(draw):
"""Helper to get all permutations of a draw (list of letters), hint:
use itertools.permutations (order of letters matters)"""
return list(it for i in range(1, 8) for it in itertools.permutations(draw, i)) | ddf34e86428d54313010d20bba77fdf3d7082113 | 643,596 |
import pkg_resources
def getGraph(paths=None):
"""Gives you a Dictionary of all the Dependencys.
The key is the name of the module wich has the dependency (could be 0
dependencies) and the value is a List of names of Distributions the key
depends on.
If the paths argument is None its uses the de... | 81a9d96f09732024364fbc1217e63bcb87cb1131 | 643,597 |
import re
def re_rsearch(pattern, text, chunk_size=1024):
"""
This function does a reverse search in a text using a regular expression
given in the attribute 'pattern'.
Since the re module does not provide this functionality, we have to find for
the expression into chunks of text extracted from th... | 054158d8a276b8f469ba01ee25e090b555d7d3bf | 643,599 |
def line_between(_x, _y, _a, _b):
"""Bresenham's line algorithm that returns a list of points."""
_points_in_line = []
_dx = abs(_a - _x)
_dy = abs(_b - _y)
_nx, _ny = _x, _y
_sx = -1 if _x > _a else 1
_sy = -1 if _y > _b else 1
... | 3f6f52313a254d9f810aa7220f5c5bc93a4c5553 | 643,600 |
def online(clients):
"""We assume all users are always online."""
return clients | 0d3401ea4e624fef46db0668b0205947fbe970e6 | 643,601 |
def calcula_dv(cpf, c):
"""Calcula e retorna dígito verificador do CPF."""
lista_validacao_dv = []
for i in range(0, c-1):
lista_validacao_dv.append(int(cpf[i]) * c)
c -= 1
soma_validacao_dv = sum(lista_validacao_dv)
calculo_dv = soma_validacao_dv % 11
return 0 if calculo_dv <... | ac30a3ac02d0237bd36fbe8fef6256e532cc6f96 | 643,602 |
def grid_stack_from_deflection_stack(grid_stack, deflection_stack):
"""For a deflection stack, comput a new grid stack but subtracting the deflections"""
if deflection_stack is not None:
def minus(grid, deflections):
return grid - deflections
return grid_stack.map_function(minus, d... | b36632633f61a58b8f388310e826aae7ed630c5e | 643,603 |
def generate_early_stop_file_path(experiment_path_prefix, net_number):
""" Given an 'experiment_path_prefix', return an early-stop-file path with 'net_number'. """
return f"{experiment_path_prefix}-early-stop{net_number}.pth" | c0b93cc62791f7f6d69a4235191497258f147325 | 643,604 |
def ver_str_to_tuple(ver_str):
"""Convert a version string into a version tuple."""
out = []
for x in ver_str.split("."):
try:
x = int(x)
except ValueError:
pass
out.append(x)
return tuple(out) | 55ec5b9fa8f0f84827ebbe827936d5c78c39249b | 643,605 |
import argparse
def parse_args():
"""
parses the arguments
:return: argparse object containing all provided arguments
"""
print("parsing args...")
parser = argparse.ArgumentParser(description="Converts gff3 files into genePred format")
parser.add_argument("gff_file", help... | a40cb8b86113ee7737cd0ea445841e880dbd1a35 | 643,606 |
import os
def torrent_filename( filename):
"""
Checks if a file is a ".torrent" file by examining its
contents and searching for the file name of the file
to be downloaded.
Returns the name of the file the ".torrent" will download
or None if no filename is found (the file is no ".torrent")... | e9cce24e269a4e3bb688e59ce448af7da4edb870 | 643,607 |
def distance(color_one: tuple, color_two: tuple) -> float:
"""Finds the distance between two rgb colors.
Colors must be given as a 3D tuple representing a point in the
cartesian rgb color space. Consequently the distance is calculated
by a simple cartesian distance formula. Returns a float representing... | 889b1d43205c1ecb076e5c6f3b5c9a6755aad64d | 643,608 |
def get_artist_ids(db_session):
"""Returns a list of all artist ID's."""
c = db_session.cursor()
c.execute("""SELECT artist_id FROM artists""")
l = []
for row in c:
l.append(row[0])
#db_session.commit()
c.close()
return l | d73cb9f5d0eac3f0421706f0f3fbb00379c2e2d7 | 643,611 |
def nearest(items, pivot):
"""
:param items: list of type datetime
:param pivot: the one pivot we are referring to
:return: return the nearest item in items to the pivot
"""
return min(items, key=lambda x: abs(x - pivot)) | 0bb79ea35fdd9c2feaf71d17bf66a6184065ba93 | 643,612 |
import re
def choose_coord_units(header):
"""Return the appropriate key code for the units value for the axes by
examining the FITS header.
"""
cunit = header['CUNIT1']
match = re.match(r'^deg\s*$', cunit)
if match:
return 'degree'
# raise WCSError("Don't understand units '%s'" % ... | 0f3476df962e8c81100033480411643b8a9fe09d | 643,613 |
def p2f(x):
"""Convert percent string to float.
"""
return float(x.strip('%')) / 100. | b49a8e1b3ca6e3167f37b3872bc24bfecb68728f | 643,614 |
def isKColRequired(config, num):
"""A quick helper function that checks whether we need to bother reading the k column.
The logic here is the same as for `isGColRequired`, but we check for output files that require
the k column rather than g1,g2.
Parameters:
config (dict): The configuration f... | 3a0be7198773b129d4a3fd5ef0cddc48ff659791 | 643,615 |
from typing import List
def generate_equally_spaced_scopes(num_envs: int, num_agents: int) -> List[int]:
"""Generate a list of equally spaced scopes for the agents
:param num_envs: Number of environments
:type num_envs: int
:param num_agents: Number of agents
:type num_agents: int
:raises Va... | f6a7d28f321818cc3178b5748151b74e69004482 | 643,616 |
def GetFieldNumber(field_tuple):
"""Get the field number from the tuple returned by `Message.ListFields`."""
return field_tuple[0].number | 054b215c83a18b6071eda5d44bd3f9ed099c1f5e | 643,617 |
import torch
def reshape(tensor, shape):
"""
Reshapes a tensor.
Parameters
----------
tensor : tensor
A Tensor.
shape : tensor
Defines the shape of the output tensor.
Returns
-------
A Tensor. Has the same type as tensor
"""
return torch.reshape(tenso... | dff861f6c32427d3710502f986ff441125af0206 | 643,618 |
def _distinct(a, b):
"""
ASSUME a != b
RETURN MINIMUM length SO THAT a[:length] != b[:length]
"""
ii = 1
for aa, bb in zip(a, b):
if aa != bb:
return ii
ii += 1
return ii | f5f4edb25683e73e6da2e52bcd978991eb2c3a9c | 643,619 |
import posixpath
def parse_proj_directory(parent_path, node):
"""Recursive helper for traversing k3b project XML"""
results = {}
for item in node:
path = posixpath.join(parent_path, item.get("name", ''))
if item.tag == 'file':
results[item.find('.//url').text] = path
el... | 15cac28b26d931a7829782526e9b602473923c0a | 643,620 |
import re
def parse_config_h(fp, g=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if g is None:
g = {}
define_rx = re.compile("... | 66b5c1987ca8b964ea37ff9173282a065f8630bf | 643,622 |
def get_roi_from_spot(refls, fdim, sdim, shoebox_sz=10):
"""
:param refls: reflection table
:param fdim: fast axis dimension
:param sdim: slow axis dimension
:param shoebox_sz: size of the shoeboxes
:return:
"""
fs_spot, ss_spot, _ = zip(*refls['xyzobs.px.value'])
rois = []
is_o... | 7f4c4ff6f4b043de3ea9394717b4958a3f219f42 | 643,624 |
import re
import io
def _get_keys_and_values_from_strings_file(strings_file_path):
"""
get keys_and_values from xcode strings file
:param strings_file_path: str. xcode strings file full path
:return:
"""
def _comment_remover(text):
def replacer(match):
s = match.group(0)... | ed5fe3d37fd86aede6da803a99bdfab0d4ebf122 | 643,625 |
def get_package_url(data):
"""Get the url from the extension data"""
# homepage, repository are optional
if "homepage" in data:
url = data["homepage"]
elif "repository" in data and isinstance(data["repository"], dict):
url = data["repository"].get("url", "")
else:
url = ""
... | a100ac87cd28a2bf0fcd9e6491ba915377e827c8 | 643,626 |
import os
import io
def long_description():
"""
Build the long description from a README file located in the same directory
as this module.
"""
base_path = os.path.dirname(os.path.realpath(__file__))
content = []
for name in ('README.rst', 'CHANGES.rst'):
with io.open(os.path.join(... | 4ae9bfac01d05776b4d7bc56e88a453be0be6cb3 | 643,629 |
import re
def stream_name_match(stream_reg: str, stream_name: str) -> bool:
"""Decide whether a stream regex matches a stream_name (fullmatch).
Currently, Zulip considers stream names to be case insensitive.
"""
return re.fullmatch(stream_reg, stream_name, flags = re.I) is not None | 0c6667937e8c5ffb35b50677a37562b775b8fed4 | 643,630 |
def CLASS_INT_ATTRS_from_string(cls, str_value, fixup_map=None):
"""
Given a class, lookup int attributes by name and return that attribute value.
:param cls: The class to search.
:param str_value: The key for the attribute in the class.
"""
friendly = {
key.upper(): value
for (... | b644af8806dd8dae2c923319fabb97a2d1d9c7c3 | 643,631 |
import re
def grep(s, pattern):
""" grep
"""
# Adapted from http://stackoverflow.com/a/25181706
return '\n'.join(
[line for line in s.split('\n') if re.search(pattern, line)]) | c82a51da345616207893b2450f5b349e8866d8c7 | 643,633 |
import os
def validate_dir(path):
""" Returns True if path is an existing directory and read access is available """
return (os.access(path, os.F_OK or os.R_OK) and os.path.isdir(path)) | fc9e4417a42351e8ea6705900ae300acb0ec0a81 | 643,634 |
def image_destroy(client, image_id):
"""Destroy the image or raise if it does not exist."""
return client.image_destroy(image_id=image_id) | 3d174b0b0857467bd4fe95a2d22abfed097f0c76 | 643,635 |
def bids_for_doc(doc_top_list, td, reviewers):
"""
Generate bids for the document for all provided reviewers
"""
bids = []
for rev in reviewers:
rev_top_dict = dict(td.rev_top[rev.name()])
score = 0
for t_id, t_prob in doc_top_list:
score += rev_top_dict.get(t_id,... | 5dbcc3246734c444147c75b0eaaf4db2c30b42d3 | 643,637 |
def diff(b: list, d: list) -> list:
"""
Sorting 2 list numbers without same numbers
>>> diff([1, 2, 3, 6, 4, 7], [1, 2, 36, 96, 78, 99])
[3, 4, 6, 7, 36, 78, 96, 99]
"""
# Making set of list
x = set(b)
y = set(d)
# Find numbers which are not same in lists
p = y.difference(x)
... | d2f892f6890f74d239487bcfe066b4ce4840c689 | 643,639 |
import logging
def get_hindered_potential(s, report=False):
"""
Rotor Hindered
Group 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Axis 2 1
Symmetry 1
Potential[kcal/mol] 12
0.00 1.52 2.20 2.14 1.83 1.58 2... | c1fe7812c0086c25d0325a63f0bd896a9473d043 | 643,640 |
import argparse
def make_list_of_values(allowed):
"""
Take a list of allowed values for an option and return a function that can be
used to typecheck a string of given values and ensure they match the allowed
values. This is required to support options that take comma separated lists
such as --ri... | bda561d99459696c0ee047e8b306bc38062ec91c | 643,641 |
import torch
def min_fde_k(y_pred, y_gt, masks, all_timestamps=False):
"""
minFDE_k loss for cases where k can vary across a batch.
Inputs
y_pred: Predicted trajectories, Tensor shape: (Batchsize, maxK, prediction horizon, 2).
Includes dummy values when K< maxK
y_gt: Ground truth trajectory,... | 3da921acf1770de69d988e23fc699ed40a05f318 | 643,642 |
import argparse
def __option_parser(doc=True):
""" Option parser for command line arguments.
"""
parser = argparse.ArgumentParser(prog='savu_profile')
parser.add_argument('file', help='Savu output log file')
parser.add_argument('-l', '--loglevel', default='INFO',
help='Set... | d241694ee10ec648e2484f466dcf450107a7c806 | 643,643 |
def urlParser(append_url, url):
"""Checking for external link and try to avoid it"""
if append_url[0:4] == 'http':
if append_url.split('.', 2)[1] == url.split('.', 2)[1]:
return append_url
else:
return -1
if append_url == "#":
return url
"""Checking to mai... | 24ca37bc9342173fb066fe9f3a7b16f06a3d9c43 | 643,644 |
def mol_removeh(molobject):
"""
Remove hydrogens from the structure
"""
print('Remove hydrogen atoms from structure: {0}'.format(molobject.title))
molobject.removeh()
return molobject | e5b11696c5f2f63a18db60c7e3013e908c4885db | 643,645 |
def _is_extended_slice(s):
"""Return whether a slice is an extended slice."""
return s.step is not None and s.step != 1 | 7e8b6f37bcd953b90a9ef445a6debe39b19dcfe4 | 643,646 |
import os
import re
def get_api_md5(path):
"""
read the api spec file, and scratch the md5sum value of every api's docstring.
Args:
path: the api spec file. ATTENTION the path relative
Returns:
api_md5(dict): key is the api's real fullname, value is the md5sum.
"""
api_md... | 8f789681a5b5f0c45b9c952415edc1c17760584e | 643,647 |
import copy
def del_list_elements(input_list, indices):
""" delete elements from a list
"""
l = copy.deepcopy(input_list)
for i in sorted(indices, reverse=True):
del l[i]
return l | e88264cdefab7a7ff291869b302ef1591620bd8f | 643,648 |
def vertical_crop(image):
"""
Remove first 50 rows from the images to discard the orizon.
Remove also the last 30 rows to discard the car's bonnet.
"""
# Horizon
upper_crop_treshold = 50
# Bonnet
lower_crop_threshold = 130
cropped_image = image[upper_crop_treshold:lower_crop_threshol... | c4dc2e2515f0d06b06d5b4a75a2b177d780d060e | 643,649 |
def _check_geo_type_suffix(x: str) -> int:
""" Checks if `geo_type` suffix contains an `int` """
try:
return int(x)
except ValueError:
raise ValueError(f"`geo_type` suffix: '{x}' cannot be parsed as `int`.") | fa6f4bdd5ba15777f08631c8dc6a327975101832 | 643,650 |
def padded_batch(dset, batch_size, sequence_length, label_shape=()):
"""Pads examples to a fixed length, and collects them into batches."""
# We assume the dataset contains inputs, labels, and an index.
padded_shapes = {
'inputs': (sequence_length,),
'labels': label_shape,
'index': (),
}
#... | 7e379e47cbdfee7426175d3b50eb86d21efe84eb | 643,651 |
import subprocess
import shlex, subprocess
def get_movie_stream(video):
"""
Get movie stream
parameters:
video : video from which stream will be extracted
"""
command = "ffmpeg -i "+video+" 2>&1 | grep \"Stream\""
output = subprocess.check_output(command, shell=True)
return output | ed19428d67a77a580e56cb0a7412b7e71a0fc0ac | 643,652 |
def security_header_tween_factory(handler, registry):
"""Add security-related headers to every response."""
def security_header_tween(request):
resp = handler(request)
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
#
# Browsers should respect the last... | be61d46595c7e542e06d9d1ae55eac38e1b4362d | 643,653 |
def CleanLine(line):
"""Converts a line from coolrunning results to a tuple of values."""
t = line.split()
if len(t) < 6:
return None
place, divtot, div, gun, net, pace = t[0:6]
if not '/' in divtot:
return None
for time in [gun, net, pace]:
if ':' not in time:
... | c59550c846e474ab5eadcc0e082feda4c04cc819 | 643,654 |
import random
def pick_random_word(seed):
"""
pick random "pre" or "post" perturb type with respective word
"""
pre_word_list = ["East", "West", "South", "North", "Eastern", "Western", "Central", "Southern",
"Northern", "Northeast", "Southwest", "Southeast", "Northwest", "NE", "SW... | a7b857c87d878932e0fec35c3f8e40fabe20b095 | 643,655 |
def pattern_molecular_weight(mzs: list, intensities: list, charge: int = 1):
"""
Calculates the molecular weight given by an isotope pattern.
:param mzs: m/z (x) values for pattern
:param intensities: intensity (y) values for the pattern
:param charge: charge for the molecule
:return: molecular... | ffc94ee9cc506919862f62d25a828ebf64511504 | 643,656 |
import operator
def filtered_join (sep, strings, pred = None) :
"""Return a string which is the concatenation of the items in the
iterable `strings` for which `pred` is true, separated by `sep`.
>>> filtered_join ("-", ["", "abc", "ced"])
'abc-ced'
>>> filtered_join ("-", [" ", "abc",... | f2062339413c5572646284112df7856039f7c35e | 643,658 |
import requests
def download_workspace(filepath, workspaceID, format=''):
"""
Args:
workspaceID (string): Service workspace received form watershed result
format (string): Download return format. Default will return ESRI
geodatabase zipfile. 'SHAPE' will return a zip ... | cfc6e6b5b1e2d7b6c37aca7d91131def2ec02a90 | 643,659 |
import os
def get_mtime(last_export_filename):
"""Returns the file mtime, or zero if last_export_filename was created.
Args:
last_export_filename: str, absolute path to last export time stamp file.
Returns:
int, 0 if the file was created, or the mtime of existing file.
Raises:
IOE... | c07e8d3921c82691fde512c02e7c9c6043a7ec2f | 643,660 |
import os
import sys
import json
def load_app_config():
"""加载应用配置"""
config_file = os.environ.get('NANOTOOLS_CONFIG_FILE')
if not config_file or not os.path.exists(os.path.realpath(config_file)):
error_message = '无法读取系统配置'
print(error_message, file=sys.stderr)
sys.exit(-1001)
t... | f0514270fb516475b8a7963d7b96338ee611cc66 | 643,661 |
def from_bits(bin_str: str):
"""
This function will convert a binary string (with or without prefix) into a integer;
:param bin_str: A binary string to convert into integer
:return: A integer representing the given binary string
"""
return int(bin_str, 2) | ee4a50f18f0c8ee7c0d0087444e1aebadf3a8ad4 | 643,662 |
def swap_order(value):
"""
Common crawl optimizes search by working back to front ("org.example.www")
This is a utility function for swapping the order back to the expected value ("www.example.org")
"""
parts = value.split(".")
new_value = ""
for part in parts:
new_value = part + ".... | 7cf789e9b97dbb55125d2928479f020bbdd75769 | 643,663 |
import os
def use_environ():
"""
In certain test environments, the necessary docker env vars are available
and those should be used. This function checks for those and returns
a boolean so that the docker client can be instantiated properly
"""
for var in ['DOCKER_CERT_PATH', 'DOCKER_HOST', 'D... | 880ca6014548e54ab6da783faa22d395c718e9ce | 643,664 |
def dtype_to_json_type(dtype) -> str:
"""Convert Pandas Dataframe types to Airbyte Types.
:param dtype: Pandas Dataframe type
:return: Corresponding Airbyte Type
"""
if dtype == object:
return "string"
elif dtype in ("int64", "float64"):
return "number"
elif dtype == "bool":
... | c97bf036cce3356bec63dc84efaa8b20b3e45872 | 643,665 |
def _logsource_display_priority(ls):
"""
Provides a score for the logsource for deciding what to display as the machine log.
A higher priority means it is a better choice.
Args:
ls (LogSource): The LogSource to score.
Returns:
int: The priority.
"""
priority = 1
# Pref... | 14395a1f9000df335b678c46c90dc13fe1f5d28c | 643,666 |
import argparse
def _define_flags():
"""Defines an `ArgumentParser` for command-line flags used by this program."""
flags = argparse.ArgumentParser(
description='Get word image labels from aligned logic analyser traces.')
flags.add_argument('label_database', type=str,
help=('CSV file... | fc04ab3e606df357ce6144d5b17e7a8f95dac4de | 643,667 |
def hsl_to_rgb(hue, saturation, lightness):
"""
:param hue: degrees
:param saturation: percentage
:param lightness: percentage
:returns: (r, g, b) as floats in the 0..1 range
"""
hue = (hue / 360) % 1
saturation = min(1, max(0, saturation / 100))
lightness = min(1, max(0, lightness /... | 3feee464c1db49ad2265c0a0d86a5eaa91ca197d | 643,668 |
def get_results():
"""
Update team win information from real_world.txt
"""
with open('real_world.txt', 'r') as rfile:
team_data = rfile.readlines()
level = 0
rounds = []
cround = []
for team in team_data:
if team == '\n':
level += 1
rounds.append(c... | c33519f6f2bff52f782c0cee62bdc1f5262b7b9f | 643,669 |
def get_string_trace_attribute_rep(trace, trace_attribute):
"""
Get a representation of the feature name associated to a string trace attribute value
Parameters
------------
trace
Trace of the log
trace_attribute
Attribute of the trace to consider
Returns
------------
... | 1e8c49e81379392b8c062c3058dc59eff2787f9d | 643,670 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.