content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remove_dul(entitylst):
"""
Remove duplicate entities in one sequence.
"""
entitylst = [tuple(entity) for entity in entitylst]
entitylst = set(entitylst)
entitylst = [list(entity) for entity in entitylst]
return entitylst | 7763ea273b9eed00d923ac1b8d631b9a24daf01a | 31,786 |
import argparse
import ast
def add_dannce_train_args(
parser: argparse.ArgumentParser,
) -> argparse.ArgumentParser:
"""Add arguments specific to dannce training.
Args:
parser (argparse.ArgumentParser): Command line argument parser.
Returns:
argparse.ArgumentParser: Parser with added... | 0d011591eb3ba7c6904c24dcf5fcb0b19137d8f8 | 31,787 |
import re
def _is_disabled(name, disabled=[]):
"""Test whether the package is disabled.
"""
for pattern in disabled:
if name == pattern:
return True
if re.compile(pattern).match(name) is not None:
return True
return False | 05f7e82a3c08411c4021f8bd695c2f6b75a636c8 | 31,788 |
def _get_elements_and_boundaries(flows):
"""filter out elements and boundaries not used in this TM"""
elements = {}
boundaries = {}
for e in flows:
elements[e] = True
elements[e.source] = True
elements[e.sink] = True
if e.source.inBoundary is not None:
boundar... | 79c2cab04b18789b473f5c922d7aa5679a62c967 | 31,789 |
def get_wind(bearing):
"""get wind direction"""
if (bearing <= 22.5) or (bearing > 337.5):
bearing = u'\u2193 N'
elif (bearing > 22.5) and (bearing <= 67.5):
bearing = u'\u2199 NE'
elif (bearing > 67.5) and (bearing <= 112.5):
bearing = u'\u2190 E'
elif (bearing > 112.5) and... | 45a7627e6ae7366b1652e54f763e0b2da1e81d75 | 31,790 |
def response(hey_bob):
"""
Get the response
"""
if not hey_bob.strip():
return "Fine. Be that way!"
chars = "".join(filter(lambda c: c.isalpha(), hey_bob))
if hey_bob.strip()[-1] == "?":
if chars.isupper():
return "Calm down, I know what I'm doing!"
return... | 55934d58fa94ee855d1295138dd68fa7590ca293 | 31,791 |
def configure(config):
"""
| [google] | example | purpose |
| -------- | ------- | ------- |
| cs_id | 00436473455324133526:ndsakghasd | Custom search ID |
| api_key | ASkdasfn3k259283askdhSAT5OADOAKjbh | Custom search API key |
"""
chunk = ''
if config.option('Configuring google search ... | afbe061817230f8e2ca101695e91427b7b39eca1 | 31,792 |
def a_source_filename(plugin_ctx, fsm_ctx):
"""send source filename."""
src_file = plugin_ctx.src_file
fsm_ctx.ctrl.sendline(src_file)
return True | 97a2d12fd2807b0dfca8d503478ccc5c514b88b6 | 31,793 |
import binascii
def givenCodeGetGPML(s, code):
"""download gpml files from wikipathways database"""
code = code.decode()
res = s.getPathwayAs(code, filetype="gpml")
# newres = unidecode(res)
newres = binascii.a2b_base64(bytes(res, "ascii")) # convert to ascii
return newres | ab6ff977b8c7194ed5b3d8574bca9aa5d76f7be0 | 31,794 |
def velocity(range, avg_range, volume, avg_volume):
"""
The average of the average of the range and volume for a period.
:param range:
:param avg_range:
:param volume:
:param avg_volume:
:return:
"""
rng_rate = range / avg_range
vol_rate = volume / avg_volume
total = sum((rng... | d63b317860d0962e1d140d962df4400ae434a011 | 31,795 |
import os
import glob
import pyclbr
import importlib
def model_finder(game_mode):
""" Returns an initialized model.
:param game_mode: str
Should be either the name of a module located in the
models folder or the name of the first class inside one of the modules
located... | 184aba7fcca7709083bc5064427e6e602293027f | 31,797 |
import re
def seperate_data(data, labels):
"""
Given a data file such as
| x11 u11 x12 other x13 |
| x21 u21 x22 other x23 |
| ..................... |
And labels for each column such as
'x' 'u' 'x' '_' 'x'
Split the data into x' and u'
"""
# Take the i... | 6dc739f55fcf6113cc45d849c256e5186e328cc0 | 31,798 |
def hr2deg(deg):
"""Convert degrees into hours."""
return (deg * (24.0 / 360.0)) | e9f268be41221cd2b17d596f859d7a7686c3b4ac | 31,799 |
import os
def is_model_dir(model_dir):
"""Checks if the given directory contains a model and can be safely removed.
specifically checks if the directory has no subdirectories and
if all files have an appropriate ending."""
allowed_extensions = {".json", ".pkl", ".dat"}
dir_tree = list(os.walk(mod... | 1797a64271053c9d1dc57a25118a97857defcfa5 | 31,800 |
import os
def create_dir_and_make_writable(directory):
"""
Creates a directory if it does not exist, and make sure it is writable by us.
@rtype: bool
@return: success
"""
if not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError:
retur... | ac5236eb8ccb8f966d947b09c115ccf2caa708b1 | 31,801 |
def main():
"""Для того, чтобы сделать на сайте «звонибельную» ссылку,
надо указать параметр href c префиксом tel:
Например, <a href="tel:+79012342452">+79012342452</a>
Напишите программу, которая «оборачивает» телефон в такие теги."""
# Code goes over here.
tel = input()
print('<a href="tel... | fbce02cfc9655059723d22894ff3c4aa99c0101f | 31,802 |
import itertools
def check_all_hats(s0, s1, s2, s3, verbose=False):
"""s0~3 = 3x3 strategy for that player"""
successes = 0
for hats in itertools.product(range(3), repeat=4):
guesses = [s0[hats[3]][hats[1]],
s1[hats[0]][hats[2]],
s2[hats[1]][hats[3]],
... | cc9814794aa584f981923acf2b4ebdb4873f8605 | 31,803 |
from typing import Union
import time
def cast_timestamp_seconds_since_epoch_to_text(seconds: Union[int, float, str],
timezone: str = "UTC",
time_in_nanoseconds: bool = False,
da... | cc675ad75bc90e3866eb737b6878c1c21d049ac4 | 31,805 |
def to_lower( tokens ):
"""Convert all tokens to lower case.
Args:
tokens (list): List of tokens generated using a tokenizer.
Returns:
list: List of all tokens converted to lowercase.
"""
return [w.lower() for w in tokens] | acef98d5e52ed03104f75d542b8f8328790a7c5f | 31,806 |
import re
def has_three_consecutive_vowels(word):
"""Returns True if word has at least 3 consecutive vowels"""
pattern = re.compile(r"[aAeEiIoOuU]{3,}")
match = pattern.search(word)
return True if match else False | 6159ccca9a132e2d2bbd28b8a867aca496ba8436 | 31,807 |
import re
def wrap_parser(namespace, parser): # pragma: no cover
"""Wraps an argument parser, putting all following options under a
namespace. """
robj = re.compile(r'^(-+)')
class _Wrapper:
def __init__(self, _parser):
self.parser = _parser
def add_argument(self, *args,... | 63f3c1ae8fd102f21d71a6fd378b379ea26ba5d2 | 31,808 |
def even_control_policy(time):
"""Policy carrying out evenly distributed disease management."""
return [0.16]*6 | 84a0087c90f6dc9dbb28adb7c97a4f6f96eaf25c | 31,810 |
def rotc(ebit, debt, equity):
"""Computes return on total capital.
Parameters
----------
ebit : int or float
Earnins before interest and taxes
debt : int or float
Short- and long-term debt
equity : int or float
Equity
Returns
-------
out : int or float
... | 4c4149d55439c0b6d91b15559fe0618dd09efac0 | 31,811 |
def is_final_option(string):
"""Whether that string means there will be no further options
>>> is_final_option('--')
True
"""
return string == '--' | 272b3300571096eb0a4931c7f699b00b7a39842c | 31,812 |
def traverse_dict(obj: dict, convert_to_string: bool = True):
"""
Traversal implementation which recursively visits each node in a dict.
We modify this function so that at the lowest hierarchy,
we convert the element to a string.
From https://nvie.com/posts/modifying-deeply-nested-structures/
"... | af323c350fc5c784362baf6aaee9a61be0d7f0ca | 31,816 |
def squash_dims(tensor, dims):
"""
Squashes dimension, given in dims into one, which equals to product of given.
Args:
tensor (Tensor): input tensor
dims: dimensions over which tensor should be squashed
"""
assert len(dims) >= 2, "Expected two or more dims to be squashed"
size... | d12ee924fabae3529aa48a90d124bbb41cc3a655 | 31,817 |
import re
def is_a_uri(uri_candidate):
"""
Validates a string as a URI
:param uri_candidate: string
:return: True or False
"""
# https://gist.github.com/dperini/729294
URL_REGEX = re.compile(
"^"
# protocol identifier
"(?:(?:https?|ftp)://)"
# user:pass aut... | c1d6eb37170011a7d46a203fce325fdfd0b0be91 | 31,818 |
def update_config(config,config_update):
"""Update config with new keys. This only
does key checking at a single layer of depth,
but can accommodate dictionary assignment
:config: Configuration
:config_update: Updates to configuration
:returns: config
"""
for key, value in config_updat... | 6265be1e72e91b1321d9742f4c543fc875acf927 | 31,819 |
def transform_post(post):
"""Transforms post data
Arguments:
post {dict} -- Post data
"""
return {
'id': post['id'],
'title': post['title'],
'url': post['url'],
'image': post['feature_image'],
'summary': post['custom_excerpt'] \
if post['c... | c765ba32ec5b00c289034e8daa2424f431678307 | 31,821 |
def int_to_unknown_bytes(num, byteorder='big'):
"""Converts an int to the least number of bytes as possible."""
return num.to_bytes((num.bit_length() + 7) // 8 or 1, byteorder) | 36865905ca7c57823c9e8a26f5c318a5597d6720 | 31,822 |
def add_color_esc_codes(text: str, c: int) -> str:
"""Surround string with escape color code and
"""
cnum = 16
base = 30 if c < cnum / 2 else 90
color_code = f'\033[0;{base + c % 8};40m'
reset_code = '\033[0m'
return f'{color_code}{text}{reset_code}' | 01fe49c570cc9f7d0483f20077e961dd94b3600c | 31,823 |
def min_operations(number):
"""
Return number of steps taken to reach a target number
number: target number (as an integer)
:returns: number of steps (as an integer)
"""
# Solution:
# 1. The number of steps to reach a target number = number of steps take to make the target number 0
# 2.... | d15d91e22aa2d552acb8308882482ffeafa9d5e3 | 31,824 |
import ipaddress
def validate_ipv4_address(ipv4_address):
"""
This function will validate if the provided string is a valid IPv4 address
:param ipv4_address: string with the IPv4 address
:return: true/false
"""
try:
ipaddress.ip_address(ipv4_address)
return True
except:
... | 51de6b7d4da2de4413217ee339147538aac4c2f5 | 31,825 |
def flatten(some_list):
"""
Flatten a list of lists.
Usage: flatten([[list a], [list b], ...])
Output: [elements of list a, elements of list b]
"""
new_list = []
for sub_list in some_list:
new_list += sub_list
return new_list | 26df175c0e119f5a872449df9fd8ea8d46393542 | 31,827 |
def flood_fill(surface, seed_point, color, pan=(0, 0)):
"""Flood fills a pygame surface, starting off at specific seed point.
Returns the original surface with that area filled in.
Thanks to wonderfully concise example of (non-recursive)
flood-fill algorithm in Python:
http://stackoverf... | 6d9bc60cbbd25ad0d1bead1fe88ff74be71d57db | 31,828 |
def bbox_to_pixel_offsets(gt, bbox):
"""Helper function for zonal_stats(). Modified from:
https://gist.github.com/perrygeo/5667173
Original code copyright 2013 Matthew Perry
"""
originX = gt[0]
originY = gt[3]
pixel_width = gt[1]
pixel_height = gt[5]
x1 = int((bbox[0] - originX) / ... | 4b7e9737db78beab3d605d0a93450b3f8259c365 | 31,829 |
def autocomplete(prefix, structure, algorithm='linear_search'):
"""Return all vocabulary entries that start with the given prefix using the
given structure and algorithm, specified as linear_search, trie, etc."""
if algorithm == 'linear_search':
# Search the list using linear search
return [... | 84494b9da63b779fd98be0a88a2382c4e6d73cb7 | 31,830 |
from typing import Any
from typing import Set
def _all_names_on_object(obj: Any) -> Set[str]:
"""Gets all names of attributes on `obj` and its classes throughout MRO.
Args:
obj: The object to get names for.
Returns:
A set of names of attributes of `obj` and its classes.
"""
nameset = set(obj.__dict... | ac635b970df640a602656af55eabb94c4d55daae | 31,831 |
import ipaddress
import re
def _validate_cidr_format(cidr):
"""Validate CIDR IP range
:param str cidr:
:return:
:rtype: bool
"""
try:
ipaddress.ip_network(cidr, strict=False)
except (ValueError, ipaddress.AddressValueError,
ipaddress.NetmaskValueError):
return F... | 5f2a667c93720909ce7b9ff3019a0c403a499222 | 31,833 |
import requests
def rx_id_from_up_id(up_id):
"""Get the Reactome Stable ID for a given Uniprot ID."""
react_search_url = 'http://www.reactome.org/ContentService/search/query'
params = {'query': up_id, 'cluster': 'true', 'species':'Homo sapiens'}
headers = {'Accept': 'application/json'}
res = reque... | 3ff9434824a348d5d77c54295765ad72680db0d1 | 31,834 |
from typing import List
from typing import Callable
from typing import Tuple
def evolve_until_stationary(layout: List[str], change_rule: Callable[[str, int], str], floor_is_empty: bool = True) -> List[str]:
"""Evolves *layout* applying *change_rule* to each position, until no more changes are made.
*floor_is... | 9a6df32d5774ee5559f09b1dcb9a9022d37d4be7 | 31,835 |
def _convert_path_to_ee_sources(path: str) -> str:
"""Get the remote module path from the 'ee-sources' GCS bucket.
Args:
path: str
Returns:
An ee-sources module url.
"""
if path.startswith("http"):
eempath = path
else:
bpath = path.replace(":", "/")
eemp... | f650736711fb8909e0e11df2165a89f06210cb53 | 31,838 |
import pytz
def convert_utc_to_localtime(utc_datetime, timezone_str):
"""
轉換 utc 時間為指定的 local 時間,如果輸入的時區有錯,則保持原來的 UTC
Args:
utc_datetime(datetime): utc 時間
timezone(str): 指定轉換的時區,採用 tz database 列表
Returns
timezone_dt(datetime): 回傳轉換好的時區時間
"""
# 取得 tzinfo 的時區
if timezone_str in pytz.common_timezones:
tz ... | 3185746161ddfd812f023bdfa74bb58bd2be9113 | 31,840 |
def get_number(char):
"""
判断字符串中,中文的个数
:param char: 字符串
:return:
"""
count = 0
for item in char:
if 0x4E00 <= ord(item) <= 0x9FA5:
count += 1
return count | d6b4cc2a3283d776d2f57ab1032b7dcb65daf3e0 | 31,841 |
import functools
import operator
def prod(iterable):
"""Product function.
Parameters
----------
iterable
"""
return functools.reduce(operator.mul, iterable, 1) | 246959f45c31e38eaab55dd1387ba00f9d569781 | 31,842 |
import subprocess
def get_git_branch():
"""Get the symbolic name for the current git branch."""
cmd = "git rev-parse --abbrev-ref HEAD".split()
try:
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return None
else:
retur... | 8bd97de3cf37e589a0be5cd7cc9c5d86bc514281 | 31,843 |
import os
def screenshot_data():
"""Loads base64-encoded screenshot data.
"""
try:
file = open(os.path.join("tests/fixtures/screenshot_base64.txt"), 'r')
data = file.read()
except FileNotFoundError:
return ''
else:
file.close()
return data | 75a846e3a5ace1b5007589387b0840c68959db65 | 31,844 |
def reverse_amount(amount, account):
"""
get counterparty amount
:param amount:
:param account:
:return: {{value: string, currency: *, issuer: *}}
"""
return {
'value': str(-float(amount['value'])),
'currency': amount['currency'],
'issuer': account
}
pass | 6b61d5a693799bbbaf5a2327a8006233e2c98da0 | 31,846 |
import collections
def list_compare(a: list, b: list) -> bool:
"""Check if two lists contain the same elements."""
return collections.Counter(a) == collections.Counter(b) | 05a15f46b5e00f6e17e81f4b67332a196154f4e7 | 31,848 |
def time_int_to_decimal(time):
"""Takes a number of the form HHMMSS or +/-DDMMSS and converts it
to a decimal."""
if time[0] == "-":
sign = -1
timestr = time[1:]
elif time[0] == "+":
sign = 1
timestr = time[1:]
else:
sign = 1
timestr = time
index = timestr.find('.')
if index > -1:
... | 405652db7cb673ad2548c5c4e7ba998b79adcfd7 | 31,849 |
def _get_map_key(wire_position):
"""
wire position, tuple of tuple
like: ((0, 0), (0, 1))
"""
if wire_position[0][0] + wire_position[0][1] > \
wire_position[1][0] + wire_position[1][1]:
return str((wire_position[1], wire_position[0]))
return str(wire_position) | 22796f1dcac78d109f078c1de04a7d7fde4348ca | 31,850 |
import collections
def find_best_kmer_diagonal(kmertoposA, kmertoposB, bandwidth, ignore_self_diagonal=False):
"""To approximate the best alignment between sequences A and B, find the
highest number of basepairs in sequence A involved in kmer matches within a single
diagonal band in an A-to-B alignment. ... | 84b7bc3055a2cba0a2878858ef66975ae568e44a | 31,852 |
def copper_heat_capacity_CRC(T):
"""
Copper specific heat capacity as a function of the temperature from [1].
References
----------
.. [1] William M. Haynes (Ed.). "CRC handbook of chemistry and physics". CRC Press
(2014).
Parameters
----------
T: :class:`pybamm.Symbol`
Dime... | 5a1aa532ea0d9eb7cb4974709963495835d608aa | 31,853 |
import re
def n_channels(s):
"""Get the number of channels from filename"""
temp = re.split("_|\.", s.lower())
if "C64" in temp:
return 64
return 32 | f7e48f0e7dc5032ea15a07a693c1b59f3965275a | 31,854 |
def getAttributeValue(Data, Attribute, IsDiscrete):
"""
统计所有离散属性的所有取值。
Args:
Data (): 数据集
Attribute (): 属性集
IsDiscrete (): 是否离散
Returns: 字典,所有离散属性的所有取值。例如:
{'色泽': {'乌黑', '青绿', '浅白'}, '根蒂': {'硬挺', '稍蜷', '蜷缩'}, '敲声': {'浊响', '沉闷', '清脆'},
'纹理': {'模糊', '清晰', '稍糊'}, '脐部': {'凹... | 686476aee803b540853e32c2b5a7ac7414d19a03 | 31,858 |
def _compute_all_mask(ds):
"""Computes a mask that is true everywhere"""
da_mask = ds.z < ds.z + 1
da_mask.attrs["long_name"] = "All data mask"
return da_mask | 93f04dde3a20c504b017d30ceb654d3c62bce798 | 31,859 |
def merge_dict(destination, source, path=None):
"""merges source into destination"""
if path is None:
path = []
for key in source:
if key in destination:
if isinstance(destination[key], dict) and isinstance(source[key], dict):
merge_dict(destination[key], source[key], path + [str(key)])
... | 6f6480b0d515eaa789ea17fa66a404b4de9817f6 | 31,860 |
def traverse_for_weight(network, parent, stop_concept, previous_concepts=None, previous_weights=None):
"""Find all the weights between two concepts in a network.
Returns a list of lists. Each inner list represents a path within the network. The items of the list are the weights
for the path.
"""
if... | 41230e99e9fda36094320b38d9b236cd0d221fbe | 31,862 |
def _convert_hab_op(lulc_array, *hab_conversion_list):
"""Convert lulc to odd value if even value of hab conversion is 1."""
result = lulc_array.copy()
hab_iter = iter(hab_conversion_list)
for mask_array, conversion in zip(hab_iter, hab_iter):
if isinstance(conversion, int):
result[m... | 6e5ba79edeb4e4c4a03f5398da12763968377799 | 31,863 |
import logging
def obr_repr(obj):
"""Return obj representation if possible."""
try:
return repr(obj)
# pylint: disable-msg=broad-except
except Exception as e:
logging.error(e)
return 'String Representation not found' | 8a95574dc0d8b18fe1c7f8c040b167654930380e | 31,865 |
def generate_playlist_url(playlist_id:str)->str:
"""Takes playlist Id and generates the playlist url
example https://www.youtube.com/playlist?list=PLGhvWnPsCr59gKqzqmUQrSNwl484NPvQY
"""
return f'https://www.youtube.com/playlist?list={playlist_id}' | f6f234e3f3eb061e37d573e35aff7c77637b0952 | 31,866 |
import time
def getNewId(Tag):
"""Build a new Id"""
t1 = time.time()
sid = str(Tag) + '_' + str(t1)
return sid | 0f6cfea36ab80d180123bad27ce820f87e6407b0 | 31,867 |
import torch
def correct_predictions(predictions, targets):
"""
:param predictions: input of predicted values. size should be WxC
:param targets: input of target values. size should be W
:return: total number pf correct predictions
"""
# calculate correct predictions over each batch
correc... | 1f680f7bc78e7bcb153e13681ffd8e8723ee76e1 | 31,869 |
from typing import Optional
import base64
import os
def make_gafaelfawr_token(username: Optional[str] = None) -> str:
"""Create a random or user Gafaelfawr token.
If a username is given, embed the username in the key portion of the token
so that we can extract it later. This means the token no longer fo... | 6eff70ada5774e52e0f145236e267adcf2ec5d84 | 31,870 |
def get_file_list(num_files):
"""
formats number of files in olympus format
:param num_files:
:return: list of file numbers
"""
file_list = []
for num in range(1, num_files+1):
num = str(num)
to_add = 4-len(num)
final = '0'*to_add+num
file_list.append(final)
... | 501fbcaec213e6319157bc728fd8fc1fab142635 | 31,871 |
def _binary_search(f, xmin, xmax, eps=1e-9):
"""Return the largest x such f(x) is True."""
middle = (xmax + xmin) / 2.
while xmax - xmin > eps:
assert xmin < xmax
middle = (xmax + xmin) / 2.
if f(xmax):
return xmax
if not f(xmin):
return xmin
i... | 980b45c220c058e66964f5a8307a639aea13d1d5 | 31,872 |
def int_check(self, value, key):
"""
Cast a value as an integer
:param value: The value to cast as int
:param key: The value name
:return: The value as an integer, otherwise an error message
"""
try:
int(value)
return int(value), ''
except:
return None, 'Error: %... | 4529cc80104dd075539f6e846dddd8814756e116 | 31,873 |
def get_organizer_emails(form):
"""Get up to 15 organizer emails from an input form."""
return form.getlist("organizer")[:15] | 129b21b7fe0e3c9d12c0c363facce2cc669baa60 | 31,875 |
def find_dependency_in_spec(spec, ref):
"""Utility to return the dict corresponding to the given ref
in a dependency build spec document fragment
"""
for item in spec:
if item['ref'] == ref:
return item | e7fa516b5d7d88ec68cdd5e5f5994f37f6ca05ce | 31,876 |
import json
def get_json_dump(data):
"""
get dump of data as JSON
"""
return json.dumps(data, indent=4, separators=(',', ': ')) | 8393e73de0c4d1ef9296cffb2b419e7fb6c147a5 | 31,877 |
def lerp(pos_x, x0, x1, fx0, fx1):
""" integer linear interpolation """
return fx0 + (fx1 - fx0) * (pos_x - x0) // (x1 - x0) | 7172b177e05831ddc38e704bde9047263f10ece2 | 31,880 |
def encoding(fields, use_original_field_names=False):
"""Convert fields structure to encoding maps for values and field names.
Expects a fields dictionary structure, returns a tuple of two dictionaries where the keys are the field names
(either original or new depending on the use_original_field_names param... | 4789733018eebbf7e9f7287359ebc6c56c5182f6 | 31,881 |
import torch
import logging
def compute_ious(gt_masks, pred_masks, gt_boxes, pred_boxes):
"""Compute Intersection over Union of ground truth and predicted masks.
Args:
gt_masks (torch.IntTensor((img_height, img_width, nb_gt_masks))):
Ground truth masks.
pred_masks (torch.FloatTens... | a1922f67041420ddefe1910296490d4356a9cef8 | 31,882 |
def getMatches(file, regex):
""" Returns a list of all passages in `file` matching `regex` """
source = open(file, "r")
return [x for x in regex.findall(source.read())] | 17a791998d9bf2f2ba8aad9e15e6a395785b78c2 | 31,884 |
def qualitytodeg(ql):
"""
Maps a string to a distance in degree between the outer points of the cylinder
=> Lower distance = more points generated
@:param ql String which represents choosen quality of the stl file
@:return int which represents the distance between outer points of the cylinder sides... | 46a4797c22d650cae62ea8569f400c65e018eb0b | 31,885 |
from typing import Tuple
def ext_gcd(a: int, b: int) -> Tuple[int, int, int]:
"""Extended Euclidean algorithm
solve ax + by = gcd(a, b)
Parameters
----------
a
b
Returns
-------
(d, x, y) s.t. ax + by = gcd(a, b)
"""
if b == 0:
return a, 1, 0
d, y, x = e... | a4c1c7f682d13ceab6bb3d06b855c61a9a88d9f8 | 31,886 |
def resolve_path(base, path):
""" Resolve (some) relative path. """
if path[0] == "/":
# Absolute path
return path
return base + path | afaa64b7d06c8140256072acc9a5c8b7aa3d94ec | 31,887 |
def parse_zone_id(full_zone_id: str) -> str:
"""Parse the returned hosted zone id and returns only the ID itself."""
return full_zone_id.split("/")[2] | 1dbcbcee8dbd09b24d22957d7e598e1f5692910f | 31,888 |
def _real_name(name, finfo):
"""Given the name of an object, return the full name (including package)
from where it is actually defined.
"""
while True:
parts = name.rsplit('.', 1)
if len(parts) > 1:
if parts[0] in finfo:
trans = finfo[parts[0]].localnames.get... | 9acb7d318d416adeddaa9e7e49371f6e2925ae9b | 31,889 |
import math
def distance(A, B):
""" Finds the distance between two points
@parameter A: point #1
@parameter B: point #2
@returns: distance between the points A and B"""
return math.sqrt((A[0] - B[0]) ** 2 + (A[1] - B[1]) ** 2) | e189723dafbb984656ae28b2824f4bbebbffa99c | 31,891 |
from collections import Counter
def CheckPermutation(string1, string2):
"""Check permutation of two string"""
counter = Counter()
if len(string1) != len(string2):
return False
for x in string1:
counter[x] += 1
for x in string2:
counter[x] -= 1
for x in counter:
if counter[x]!=0:
return False
return... | 4c14943c0978d41939e0a2b38297f1856dcbffa5 | 31,892 |
def decimalToBinaryv1(decimal):
"""assumes decimal is an int, representing a number in base 10
returns an int, representing the same number in base 2
"""
return bin(decimal) | cfd97e488d27f167551cc84ad95c339b49fa52c4 | 31,893 |
def _create_pred_input_plot(x_pred,
x_pred_error,
axes,
vline_kwargs=None,
vspan_kwargs=None):
"""Create plot for prediction input data (vertical lines)."""
if vline_kwargs is None:
vline_kwar... | 2430d0b181b401cd8188aebc091abd8a9a28b650 | 31,894 |
def get_results(soup):
"""
Gets the results div from the HTML soup
@param {BeautifulSoup} soup Google Scholar BeautifulSoup instance
@return {BeautifulSoup[]} List of Google Scholar results as
BeautifulSoup instances
"""
return soup.find_all('div', class_='gs_r gs_or gs_scl') | efdcc2a5b827a84840868e250894c8f144ae0743 | 31,895 |
def del_pre_line(text, keyword):
"""
删除上一行
:param text:
:param keyword:
:return: str: 删除行之后的结果
"""
position = text.find(keyword)
if position != -1:
pos_line_head = text.rfind('\n', 0, position)
pos_pre_line_head = text.rfind('\n', 0, pos_line_head)
return text[0:p... | 37895577e9e043d912d511dc69c9007439d156e2 | 31,897 |
import argparse
def parse_arguments():
"""
Parse user arguments
Output: list with all the user arguments
"""
# All the docstrings are very provisional and some of them are old, they would be changed in further steps!!
parser = argparse.ArgumentParser(description="""Script ... | 3bcd918b0fc687e4b95b9787e4b6cc1d096e38ea | 31,898 |
def has_ordered_sublist(lst, sublist):
"""
Determines whether the passed list contains, in the specified order, all
the elements in sublist.
"""
sub_idx = 0
max_idx = len(sublist) - 1
for x in lst:
if x == sublist[sub_idx]:
sub_idx += 1
if sub_idx > max_idx:
... | 4aa72edc8b4020bc49d266cddccd70e18c641ab0 | 31,899 |
def mock_time(dt=None, mem=[0.0]):
"""Fake time.perf_counter()."""
if dt is not None:
mem[0] += dt
return mem[0] | 772738606653f82fb67025d815fcdab0a7f3ad33 | 31,903 |
def detecttermination(logfile):
"""
Query whether or not a process with the given process id is still running
and return true or false.
"""
# Open longbow log file and detect if the final "goodbye" lines is there.
try:
fi = open(logfile)
lines = fi.readlines()
if len... | 8d60c93582b7ada1e30065c4ec198ade678e97bd | 31,904 |
import argparse
import pathlib
def parse_args():
"""Parse command line arguments.
Returns:
output (argparse.Namespace): Parsed command line arguments. See executable
help page for more information.
"""
parser = argparse.ArgumentParser()
parser.add_argument("--backgrounds",
... | c2367034f47037019a8eea5d470b8d307b401185 | 31,905 |
def filter_quote(environment, text, quote='"', escape_with='\\', newline=None):
"""
Filter to add quotes to text.
This is a naive implementation, as the specifics can vary a lot depending
on where you are writing the text.
:param str text: Text to adds quotes to.
:return: The text quoted out,... | 9a930904b78f774a759e02b2915c89bec89ac37d | 31,907 |
import struct
def f2b(f):
"""
float to 32bit int
"""
return struct.unpack('I', struct.pack('f', f))[0] | cb9133141d2e6ab26b8268412ca8d5f0ca0daeb3 | 31,908 |
import os
def default_lv2_path(conf):
"""Return the default LV2_PATH for the build target as a list"""
if conf.env.DEST_OS == 'darwin':
return ['~/Library/Audio/Plug-Ins/LV2',
'~/.lv2',
'/usr/local/lib/lv2',
'/usr/lib/lv2',
'/Library/Audi... | bc3e02bc111c9837239eee8c814a043cc0ba2ba3 | 31,910 |
def accept(potList):
"""
return True if current structure meets acceptance criteria
"""
if potList['noe'].violations()>1:
return False
if potList['CDIH'].violations()>0:
return False
if potList['BOND'].violations()>0:
return False
if potList['ANGL'].violations()>0:
... | ab7788079f2545bf67eba52a7d5d28df8bb61650 | 31,911 |
from typing import List
from typing import Tuple
from typing import Dict
def convert(day_input: List[str]) -> Tuple[Dict[str, List[range]], List[int], List[List[int]]]:
"""Converts the input into a tuple with:
1. A dictionary with the fields, where for each field the value is a list
of the valid ranges, e... | 7ef01443251595891c4adcd147dd0487b8b2fedf | 31,913 |
import requests
def refine_urn(urns, metadata=None):
"""Refine a list urns using extra information"""
if metadata is None:
metadata = {}
metadata['urns'] = urns
if not ('words' in metadata):
metadata['words'] = []
if not ('next' in metadata or 'neste' in metadata):
metadata... | e2fd29863a36f6c66b98e30ec432d3045a792155 | 31,914 |
def sample_approx(approx, draws=100, include_transformed=True):
"""Draw samples from variational posterior.
Parameters
----------
approx: :class:`Approximation`
Approximation to sample from
draws: `int`
Number of random samples.
include_transformed: `bool`
If True, trans... | 2ff6eab14a5d42f0a9b2d531bcccee1245964f72 | 31,915 |
import os
def load_cksm(sumfile, base_filename):
"""Load the checksum from a file"""
for l in open(sumfile,'r'):
if os.path.basename(base_filename) in l:
sum_cksm, name = l.strip('\n').split()
return sum_cksm
raise Exception('could not find checksum in file') | 97d2f9e9443384e90d11b557769c33260ff7e027 | 31,918 |
def find_hosts(ipa_client, pattern=None):
""" Returns list of matching hosts from IPA.
If no pattern is provided, returns all hosts.
"""
if pattern is None:
pattern = ''
return ipa_client.get_hosts(
pattern=pattern
) | 38dd7a8e499af6372c9243c0cf91fe1c7e7f3d9b | 31,921 |
import os
def dir_path(string):
"""
Determine if string is a valid directory path
"""
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
# warnings.warn(
# f"{textstyle.WARNING}{string} is not a valid directory, path will be defaulted... | 76c55267b1b2a0fff861cfa5dbb5e26e6a603e70 | 31,922 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.