content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def select_user(query_message, mydb):
"""
Prompt the user to select from a list of all database users.
Args:
query_message - The messages to display in the prompt
mydb - A connected MySQL connection
"""
questions = [
inquirer.List('u',
message=query_messa... | 8ab2adb27f73b5581bc48c8cc4cbc2888a21753f | 3,655,921 |
from typing import Optional
import hashlib
def generate_abl_contract_for_lateral_stage(
lateral_stage: LateralProgressionStage,
parent_blinding_xkey: CCoinExtKey,
start_block_num: int,
creditor_control_asset: CreditorAsset,
debtor_control_asset: DebtorAsset,
bitcoin_asset: BitcoinAsset,
fi... | 2c9b47666c3fb5abf78b8a7d007d1258930f1068 | 3,655,923 |
def force_norm():
"""perform normalization simulation"""
norm = meep.Simulation(cell_size=cell,
boundary_layers=[pml],
geometry=[],
resolution=resolution)
norm.init_fields()
source(norm)
flux_inc = meep_ext.add_flux_plane(norm,... | e5c9e6255568e52d0cb30504cd22f610b6f6e5d9 | 3,655,925 |
def search(coordinates):
"""Search for closest known locations to these coordinates
"""
gd = GeocodeData()
return gd.query(coordinates) | c9191a06b085c61b547136166cb43a24789d95cb | 3,655,926 |
from pathlib import Path
def get_all_apis_router(_type: str, root_path: str) -> (Path, Path):
"""Return api files and definition files just put the file on folder swagger."""
swagger_path = Path(root_path)
all_files = list(x.name for x in swagger_path.glob("**/*.yaml"))
schemas_files = [x for x in al... | eab89c870447e3f1abd72529de37d645de3be612 | 3,655,927 |
def get_cached_patches(dataset_dir=None):
"""
Finds the cached patches (stored as images) from disk and returns their paths as a list of tuples
:param dataset_dir: Path to the dataset folder
:return: List of paths to patches as tuples (path_to_left, path_to_middle, path_to_right)
"""
if dataset... | 7990b592ddc9b93e04b11c4ae65f410c6afc15d7 | 3,655,928 |
def complex_mse(y_true: tf.Tensor, y_pred: tf.Tensor):
"""
Args:
y_true: The true labels, :math:`V \in \mathbb{C}^{B \\times N}`
y_pred: The true labels, :math:`\\widehat{V} \in \mathbb{C}^{B \\times N}`
Returns:
The complex mean squared error :math:`\\boldsymbol{e} \in \mathbb{R}^... | 9dc8699312926b379619e56a29529fe2762d68a9 | 3,655,929 |
def expand_not(tweets):
"""
DESCRIPTION:
In informal speech, which is widely used in social media, it is common to use contractions of words
(e.g., don't instead of do not).
This may result in misinterpreting the meaning of a phrase especially in the case of negations.
This f... | 66f4ed5c7321fe7bf5ea0d350980394a235d99e6 | 3,655,930 |
def parse_filter_kw(filter_kw):
"""
Return a parsed filter keyword and boolean indicating if filter is a hashtag
Args:
:filter_kw: (str) filter keyword
Returns:
:is_hashtag: (bool) True, if 'filter_kw' is hashtag
:parsed_kw: (str) parsed 'filter_kw' (lowercase, without '#', ...... | 253d7d5f1aaf6ab3838e7fb3ba395a919f29b70e | 3,655,931 |
def get_branch_index(BRANCHES, branch_name):
"""
Get the place of the branch name in the array of BRANCHES so will know into which next branch to merge - the next one in array.
"""
i = 0
for branch in BRANCHES:
if branch_name == branch:
return i
else:
i = i + ... | c983bab67b3aa0cd1468c39f19732395c7e376f9 | 3,655,932 |
from bs4 import BeautifulSoup
def prettify_save(soup_objects_list, output_file_name):
"""
Saves the results of get_soup() function to a text file.
Parameters:
-----------
soup_object_list:
list of BeautifulSoup objects to be saved to the text file
output_file_name:
ente... | 3de5b7df49837c24e89d2ded286c0098069945fd | 3,655,933 |
def determine_required_bytes_signed_integer(value: int) -> int:
"""
Determines the number of bytes that are required to store value
:param value: a SIGNED integer
:return: 1, 2, 4, or 8
"""
value = ensure_int(value)
if value < 0:
value *= -1
value -= 1
if (value >> 7) == ... | 231e6f1fc239da5afe7f7600740ace846125e7f5 | 3,655,934 |
from bs4 import BeautifulSoup
def scrape_cvs():
"""Scrape and return CVS data."""
page_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
"accept": "text/html,application/xhtml+xml,applicatio... | 2f2f59b3477297f475d1749ff2a35c2682361cfd | 3,655,935 |
def _to_original(sequence, result):
""" Cast result into the same type
>>> _to_original([], ())
[]
>>> _to_original((), [])
()
"""
if isinstance(sequence, tuple):
return tuple(result)
if isinstance(sequence, list):
return list(result)
return result | 7b9d8d1d2b119d61b43dde253d8d3c48bd0e45b8 | 3,655,936 |
def get_B_R(Rdot):
"""Get B_R from Q, Qdot"""
return Rdot | 696932b9bf423289bdcf91287b0d789007322852 | 3,655,939 |
def run_coroutine_with_span(span, coro, *args, **kwargs):
"""Wrap the execution of a Tornado coroutine func in a tracing span.
This makes the span available through the get_current_span() function.
:param span: The tracing span to expose.
:param coro: Co-routine to execute in the scope of tracing span... | 95672b0a1ecf7b8b86dff09835fa9b3c10f7fad2 | 3,655,940 |
def calc_bin_centre(bin_edges):
"""
Calculates the centre of a histogram bin from the bin edges.
"""
return bin_edges[:-1] + np.diff(bin_edges) / 2 | 780a02dc9372670ae53fb4d85e216458e7d83975 | 3,655,941 |
def to_matrix(dG, tG, d_mat, t_mat, label_mat, bridges):
"""
Parameters:
tG: target graph
dG: drug graph
d_mat: drug feature matrix
t_mat: target feature matrix
label_mat: label matrix
bridges: known links between drugs and targets
Return:
... | 54a8ad910f78eca383eba90bd5f6bf6088145630 | 3,655,942 |
def ensureList(obj):
""" ensures that object is list """
if isinstance(obj, list):
return obj # returns original lis
elif hasattr(obj, '__iter__'): # for python 2.x check if obj is iterablet
return list(obj) # converts to list
else:
return [obj] | f845658fda36a583ac54caed1e6493d331c910fa | 3,655,943 |
import torch
def gelu_impl(x):
"""OpenAI's gelu implementation."""
return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x * (1.0 + 0.044715 * x * x))) | 15ced02b61d6e8c526bc60d2a5214f83183946c2 | 3,655,944 |
def get_shape(kind='line', x=None, y=None, x0=None, y0=None, x1=None, y1=None, span=0, color='red', dash='solid',
width=1,
fillcolor=None, fill=False, opacity=1, xref='x', yref='y'):
"""
Returns a plotly shape
Parameters:
-----------
kind : string
Shape k... | b639869eca941d2c91d44549aa751c51e033fe00 | 3,655,945 |
from typing import List
def clean_row(elements: List[Tag]) -> List[Tag]:
"""
Clean MathML row, removing children that should not be considered tokens or child symbols.
One example of cleaning that should take place here is removing 'd' and 'δ' signs that are
used as derivatives, instead of as identifi... | 527cb06ddb19d9fb25e5805c49f903254813c4e8 | 3,655,946 |
def models(estimators, cv_search, transform_search):
"""
Grid search prediction workflows. Used by bll6_models, test_models, and product_models.
Args:
estimators: collection of steps, each of which constructs an estimator
cv_search: dictionary of arguments to LeadCrossValidate to search over... | 2a3044a9cc994f18e37337a7e58e9fb9e5ef05d1 | 3,655,947 |
from datetime import datetime
import pytz
def xml_timestamp(location='Europe/Prague'):
"""Method creates timestamp including time zone
Args:
location (str): time zone location
Returns:
str: timestamp
"""
return datetime.datetime.now(pytz.timezone(location)).isoformat() | a2883e269c8f9ae8ffd723b7b0205d931453e358 | 3,655,948 |
def transform_postorder(comp, func):
"""Traverses `comp` recursively postorder and replaces its constituents.
For each element of `comp` viewed as an expression tree, the transformation
`func` is applied first to building blocks it is parameterized by, then the
element itself. The transformation `func` should ... | 964e55dc33acf978cae3f058397c9b355cae9af7 | 3,655,949 |
def bytes_to_unicode_records(byte_string, delimiter, encoding):
""" Convert a byte string to a tuple containing an array of unicode
records and any remainder to be used as a prefix next time. """
string = byte_string.decode(encoding)
records = string.split(delimiter)
return (records[:-1], records[-1... | ccc3591551a6b316843cc8eafb33e45627eac752 | 3,655,950 |
def administrator():
"""Returns a :class:`t_system.administration.Administrator` instance."""
return Administrator() | e473ee2e86f66f96a5cf3e09ac4a052e32a279b9 | 3,655,951 |
import numpy
def ocr(path, lang='eng'):
"""Optical Character Recognition function.
Parameters
----------
path : str
Image path.
lang : str, optional
Decoding language. Default english.
Returns
-------
"""
image = Image.open(path)
vectorized_image = numpy.asa... | 9b484779a34d65bb25e57baeaa371205c65d2dc6 | 3,655,952 |
def is_solution(system, point):
"""
Checks whether the point is the solution for a given constraints system.
"""
a = np.array(system)
# get the left part
left = a[:, :-1] * point
left = sum(left.T)
# get the right part
right = (-1) * a[:, -1]
return np.all(left <= right) | 774987f22a57f3a6d68b5d51f7b3a42d945a1eff | 3,655,956 |
def git_config_bool(option: str) -> bool:
"""
Return a boolean git config value, defaulting to False.
"""
return git_config(option) == "true" | 1ed48faa3c6de43fc8a732aed2fde1a81bc75949 | 3,655,957 |
def read_configs(paths):
"""
Read yaml files and merged dict.
"""
eths = dict()
vlans = dict()
bonds = dict()
for path in paths:
cfg = read_config(path)
ifaces = cfg.get("network", dict())
if "ethernets" in ifaces:
eths.update(ifaces["ethernets"])
... | 998c75b9d75e4d6404c265a67c31bb88b9b7d435 | 3,655,958 |
import json
def get_client():
""" generates API client with personalized API key """
with open("api_key.json") as json_file:
apikey_data = json.load(json_file)
api_key = apikey_data['perspective_key']
# Generates API client object dynamically based on service name and version.
perspective = discovery.bu... | be68eeeedf9c3dcf3f3991b70db18cd3032d2218 | 3,655,959 |
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
settings['route_patterns'] = {
'villages': '/geography.cfm',
'parameters': '/thesaurus.cfm',
'sources': '/bibliography.cfm',
'languages': '/languages.cfm',
'florafauna': '/f... | 52779856e4eeecb9673707b707d51322decda729 | 3,655,960 |
def overrides(pattern, norminput):
"""Split a date subfield into beginning date and ending date. Needed for fields with
multiple hyphens.
Args:
pattern: date pattern
norminput: normalized date string
Returns:
start date portion of pattern
start date portion of norminput
... | 5e005b0537d123607225ed82163cac07f578a755 | 3,655,961 |
def defaultPolynomialLoad():
"""
pytest fixture that returns a default PolynomialLoad object
:return: PolynomialLoad object initialized with default values
"""
return PolynomialStaticLoad() | 75b989dc80e7ccf4e9a091de2dcdeb8758b465b3 | 3,655,962 |
def calc_pi(iteration_count, cores_usage):
"""
We calculate pi using Ulam's Monte Carlo method. See the module
documentation. The calculated value of pi is returned.
We use a process pool to offer the option of spreading the
calculation across more then one core.
iteration_count is the num... | 7b4db8f0936995f46a42fedb4d5539cd3057eb01 | 3,655,963 |
def pair_range_from_to(x): # cpdef pair_range(np.ndarray[long,ndim=1] x):
"""
Returns a list of half-cycle-amplitudes
x: Peak-Trough sequence (integer list of local minima and maxima)
This routine is implemented according to
"Recommended Practices for Wind Turbine Testing - 3. Fatigue Loads", 2. ... | 96d86079b971bda58fd2d0af440feecc8fa4c1fd | 3,655,965 |
def serialize_action(
action: RetroReaction, molecule_store: MoleculeSerializer
) -> StrDict:
"""
Serialize a retrosynthesis action
:param action: the (re)action to serialize
:param molecule_store: the molecule serialization object
:return: the action as a dictionary
"""
dict_ = action.... | f35c0a34cc6778a39c991edafdda6bd30aea4886 | 3,655,966 |
import string
def complement(s):
"""
Return complement of 's'.
"""
c = string.translate(s, __complementTranslation)
return c | 7dab43db51bc5a3bb7321deebdb8122792f08d86 | 3,655,968 |
import copy
def get_state_transitions(actions):
"""
get the next state
@param actions:
@return: tuple (current_state, action, nextstate)
"""
state_transition_pairs = []
for action in actions:
current_state = action[0]
id = action[1][0]
next_path = action[1][1]
... | bbed37ed6469f5635fbc65fa07195114b4bb3dac | 3,655,969 |
import struct
def parse_pascal_string(characterset, data):
"""
Read a Pascal string from a byte array using the given character set.
:param characterset: Character set to use to decode the string
:param data: binary data
:return: tuple containing string and number of bytes consumed
"""
str... | eabdfe1f6fb864eead1345016495f64c5457727e | 3,655,970 |
def folder(initial=None, title='Select Folder'):
"""Request to select an existing folder or to create a new folder.
Parameters
----------
initial : :class:`str`, optional
The initial directory to start in.
title : :class:`str`, optional
The text to display in the title bar of the di... | 60331e1a89241595e09e746901fff656f8d4365a | 3,655,971 |
import tqdm
from typing import Any
from typing import Optional
def tqdm_hook(t: tqdm) -> Any:
"""Progressbar to visualisation downloading progress."""
last_b = [0]
def update_to(b: int = 1, bsize: int = 1, t_size: Optional[int] = None) -> None:
if t_size is not None:
t.total = t_s... | ff075a946ea9cf2d124d9d5e93fb83d31f2e0623 | 3,655,973 |
def check_regular_timestamps(
time_series: TimeSeries, time_tolerance_decimals: int = 9, gb_severity_threshold: float = 1.0
):
"""If the TimeSeries uses timestamps, check if they are regular (i.e., they have a constant rate)."""
if (
time_series.timestamps is not None
and len(time_series.tim... | 0c44f2b26a71e76b658180e1817cc3dfbeb375e0 | 3,655,974 |
def test_device_bypass(monkeypatch):
"""Test setting the bypass status of a device."""
_was_called = False
def _call_bypass(url, body, **kwargs):
nonlocal _was_called
assert url == "/appservices/v6/orgs/Z100/device_actions"
assert body == {"action_type": "BYPASS", "device_id": [6023... | 17e2a2f1f7c8ef1a7ef32e8aacb40f8f7fe16c53 | 3,655,975 |
import re
import importlib
def import_config_module( cfg_file ):
""" Returns valid imported config module.
"""
cfg_file = re.sub( r'\.py$', '', cfg_file )
cfg_file = re.sub( r'-', '_', cfg_file )
mod_name = 'config.' + cfg_file
cfg_mod = importlib.import_module( mod_name )
if not hasattr(... | 4cb25a56df0f26f0f3c4917aad2ca4cd40e4797f | 3,655,976 |
import multiprocessing
def process_batches(args, batches):
"""Runs a set of batches, and merges the resulting output files if more
than one batch is included.
"""
nbatches = min(args.nbatches, len(batches))
pool = multiprocessing.Pool(nbatches, init_worker_thread)
try:
batches = pool.... | dbd893773e6a5fed1d68a48c875741e4ce963ae6 | 3,655,977 |
def tripledes_cbc_pkcs5_decrypt(key, data, iv):
"""
Decrypts 3DES ciphertext in CBC mode using either the 2 or 3 key variant
(16 or 24 byte long key) and PKCS#5 padding.
:param key:
The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode)
:param data:
The ciphertext... | bf6d7efaade2cb7ce2f6abf7cea89a04fdbb3897 | 3,655,978 |
def kruskal_chi2_test(data=None, alpha=0.05, precision=4):
"""
col = 要比較的 target
row = data for each target
"""
if type(data) == pd.DataFrame:
data = data.copy().to_numpy()
alldata = np.concatenate(data.copy())
else:
alldata = np.concatenate(data.copy())
k = data.sha... | 3b89e14e7072cbb6375b0c1ead8320c5643aacd1 | 3,655,979 |
def add_new_action(action, object_types, preferred, analyst):
"""
Add a new action to CRITs.
:param action: The action to add to CRITs.
:type action: str
:param object_types: The TLOs this is for.
:type object_types: list
:param preferred: The TLOs this is preferred for.
:type preferred... | 2b54c3766d9793a1c6598402bf7a5b1103bb324b | 3,655,980 |
import multiprocessing
import asyncio
def test_PipeJsonRpcSendAsync_5():
"""
Specia test case.
Two messages: the first message times out, the second message is send before the response
from the first message is received. Verify that the result returned in response to the
second message is received... | a1939e03f4c9992d84ac52a35b975f20077a2161 | 3,655,981 |
import re
def tpc(fastas, **kw):
"""
Function to generate tpc encoding for protein sequences
:param fastas:
:param kw:
:return:
"""
AA = kw['order'] if kw['order'] is not None else 'ACDEFGHIKLMNPQRSTVWY'
encodings = []
triPeptides = [aa1 + aa2 + aa3 for aa1 in AA for aa2 in AA for ... | b8017356980b266d78d85a867aee97c0d79ec5e5 | 3,655,983 |
def _uninstall_flocker_centos7():
"""
Return an ``Effect`` for uninstalling the Flocker package from a CentOS 7
machine.
"""
return sequence([
run_from_args([
b"yum", b"erase", b"-y", b"clusterhq-python-flocker",
]),
run_from_args([
b"yum", b"erase", b... | 0d8f068857cbc25743b644d067fe70efffb644f0 | 3,655,984 |
import requests
def authenticate(username, password):
"""Authenticate with the API and get a token."""
API_AUTH = "https://api2.xlink.cn/v2/user_auth"
auth_data = {'corp_id': "1007d2ad150c4000", 'email': username,
'password': password}
r = requests.post(API_AUTH, json=auth_data, timeo... | 9675227b5ff4f58d79bafffc0407366a26d638bd | 3,655,986 |
def filter_hashtags_users(DATAPATH, th, city):
"""
cleans target_hashtags by removing hashtags that are used by less than 2 users
replaces hahstags by ht_id and saves to idhashtags.csv
creates entropy for each ht_id and saves to hashtag_id_entropies.csv
prints std output
:param DATAPATH:
:pa... | 60e0b02f9bbdccae32958717fd8608aa1932386e | 3,655,987 |
def cluster_set_state(connection: 'Connection', state: int, query_id=None) -> 'APIResult':
"""
Set cluster state.
:param connection: Connection to use,
:param state: State to set,
:param query_id: (optional) a value generated by client and returned as-is
in response.query_id. When the paramete... | 88b05a617e17574961e44d5a88bec1ac4da0be95 | 3,655,988 |
def get_all(data, path):
"""Returns a list with all values in data matching the given JsonPath."""
return [x for x in iterate(data, path)] | 592fee87b3b4be171d4e4a19b013b99551768f75 | 3,655,989 |
def extract_information_from_blomap(oneLetterCodes):
"""
extracts isoelectric point (iep) and
hydrophobicity from blomap for each aminoacid
Parameters
----------
oneLetterCodes : list of Strings/Chars
contains oneLetterCode for each aminoacid
Returns
-------
float, float
... | d36e16a0e35d744f1001752c98d09035b3e581c6 | 3,655,990 |
def partitions(n):
"""
Return a sequence of lists
Each element is a list of integers which sum to n -
a partition n.
The elements of each partition are in descending order
and the sequence of partitions is in descending lex order.
>>> list(partitions(4))
[[3,... | 042759c97031baee7c958d59b3a432b52111a696 | 3,655,991 |
def create_request_element(channel_id, file_info, data_id, annotation):
"""
create dataset item from datalake file
:param channel_id:
:param file_id:
:param file_info:
:param label_metadata_key:
:return:
"""
data_uri = 'datalake://{}/{}'.format(channel_id, file_info.file_id)
da... | 9fad37428e2608d47b2d0d57d075c0fbd9292b46 | 3,655,992 |
from typing import Mapping
from typing import Iterable
def _categorise(obj, _regex_adapter=RegexAdapter):
"""
Check type of the object
"""
if obj is Absent:
return Category.ABSENT
obj_t = type(obj)
if issubclass(obj_t, NATIVE_TYPES):
return Category.VALUE
elif callable(ob... | 549f21bee43f619fea7c2a09940cda1ce03e4e8c | 3,655,993 |
def remove_key(d, key):
"""Safely remove the `key` from the dictionary.
Safely remove the `key` from the dictionary `d` by first
making a copy of dictionary. Return the new dictionary together
with the value stored for the `key`.
Parameters
----------
d : dict
The dictionary from w... | 5695b18675b52f4ca8bc3cba1ed0104425e7a04f | 3,655,994 |
import csv
import six
def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util,
output_file_param_util):
"""Parses task parameters from a TSV.
Args:
tasks: Dict containing the path to a TSV file and task numbers to run
variables, input, and output parame... | 7c195e8c09b439d39fca105fa3303f74c43538c1 | 3,655,995 |
def spreadplayers(self: Client, x: RelativeFloat, y: RelativeFloat,
spread_distance: float, max_range: float,
victim: str) -> str:
"""Spreads players."""
return self.run('spreadplayers', x, y, spread_distance, max_range, victim) | 6577d7209d19a142ae9e02804b84af921df3224c | 3,655,997 |
def get_version():
"""Returns single integer number with the serialization version"""
return 2 | f25ad858441fcbb3b5353202a53f6ebaa8874e4d | 3,655,998 |
def format_result(func):
"""包装结果格式返回给调用者"""
@wraps(func)
def wrapper(*args, **kwargs):
ret = {}
try:
data = func(*args, **kwargs)
if type(data) is Response:
return data
ret['data'] = data
ret['success'] = True
ret['m... | 53109217a9fe6fbc00250a7b8dfd6b295e47e12b | 3,655,999 |
def writeData(filename, data):
"""
MBARBIER: Taken/adapted from https://github.com/ChristophKirst/ClearMap/blob/master/ClearMap/IO/TIF.py
Write image data to tif file
Arguments:
filename (str): file name
data (array): image data
Returns:
str: tif file name
... | cc4414b9f52413bebc422032f796cd242ecc8ef4 | 3,656,000 |
def get_trigger_function(trigger_message, waiter):
"""Función auxiliar que genera un activador
Args:
trigger_message: mensaje o instruccion para continuar.
waiter: función que pausa el flujo de instrucciones.
"""
def trigger_function():
# Se imprime la instrucción par... | b389dd93631ae396c65d5653da6cea3ec91b3556 | 3,656,001 |
def find_peaks(amplitude):
"""
A value is considered to be a peak if it is higher than its four closest
neighbours.
"""
# Pad the array with -1 at the beginning and the end to avoid overflows.
padded = np.concatenate((-np.ones(2), amplitude, -np.ones(2)))
# Shift the array by one/two value... | 192f25bbc491c7e880ff5363098b0ced29f37567 | 3,656,002 |
from typing import Optional
def sync(
*,
client: Client,
json_body: CustomFieldOptionsCreateRequestBody,
) -> Optional[CustomFieldOptionsCreateResponseBody]:
"""Create Custom Field Options
Create a custom field option. If the sort key is not supplied, it'll default to 1000, so the option
app... | 6215e704be4bbc32e52fb03817e00d7fd5338365 | 3,656,003 |
def decrypt_with_private_key(data, private_key):
"""Decrypts the PKCS#1 padded shared secret using the private RSA key"""
return _pkcs1_unpad(private_key.decrypt(data)) | f1dac9113fb97f62afab524239e38c6cb196c989 | 3,656,004 |
import warnings
def deprecated (func):
"""
This is a decorator which can be used to mark functions as deprecated. It
will result in a warning being emitted when the function is used.
:param func: original function
:type func: :any:`collections.Callable`
:return: decorated func
:rtype: :any:`collections... | ba237c30d97013080bd84569af1817685023dab6 | 3,656,006 |
import re
def prediction():
"""
A function that takes a JSON with two fields: "text" and "maxlen"
Returns: the summarized text of the paragraphs.
"""
print(request.form.values())
paragraphs = request.form.get("paragraphs")
paragraphs = re.sub("\d+", "", paragraphs)
maxlen = int(request... | a1bdf996908e65e3087ed4ffe27402c9763b4d69 | 3,656,007 |
def is_reviewer(user):
"""Return True if this user is a financial aid reviewer"""
# no need to cache here, all the DB lookups used during has_perm
# are already cached
return user.has_perm("finaid.review_financial_aid") | e3c599f78eb51c33ab48e3760c0f2965ba305916 | 3,656,008 |
def getLogMessage(commitSHA):
"""Get the log message for a given commit hash"""
output = check_output(["git","log","--format=%B","-n","1",commitSHA])
return output.strip() | 2d42e587da57faff5366fc656e8d45a8fa797208 | 3,656,009 |
def sup(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", translat... | dff8635d98f68e5b024fe23cbeaa6a1a9884222f | 3,656,011 |
def isnonempty(value):
"""
Return whether the value is not empty
Examples::
>>> isnonempty('a')
True
>>> isnonempty('')
False
:param value: string to validate whether value is not empty
"""
return value != '' | 0250cb455d8f77027d5cde9101a24683950bbdb2 | 3,656,012 |
def InstallSystem(config, deployment, options):
"""Install the local host from the sysync deployment configuration files."""
installed = {}
# Create fresh temporary directory
Log('Clearing temporary deployment path: %s' % config['deploy_temp_path'])
run.Run('/bin/rm -rf %s' % config['deploy_temp_path'])
... | 642eda86228e5575bc7267d9b3a5c3ddc055daf4 | 3,656,013 |
def preprocess_input(x):
"""前処理。"""
return tf.keras.applications.imagenet_utils.preprocess_input(x, mode="torch") | 6795c5e571d67a7908edbe3c3ca0ed5e3412d2f0 | 3,656,014 |
def attribute_to_partner_strict(partner, partner_string_or_spec, amount):
"""Return the amount attributable to the given partner."""
spec = (
partner_string_or_spec
if isinstance(partner_string_or_spec, dict)
else parse_partner_string(partner_string_or_spec)
)
if partner not in s... | d7e00b50e8be010d7896b6c51e1e3fcfe73438d2 | 3,656,015 |
import math
def drawLines(img, lines, color=(255,0,0)):
"""
Draw lines on an image
"""
centroids = list()
r_xs = list()
r_ys = list()
for line_ in lines:
for rho,theta in line_:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0... | 5918bb1a81d8efae2874f294d927f7b01527d1d1 | 3,656,016 |
import numpy
def moments_of_inertia(geo, amu=True):
""" principal inertial axes (atomic units if amu=False)
"""
ine = inertia_tensor(geo, amu=amu)
moms, _ = numpy.linalg.eigh(ine)
moms = tuple(moms)
return moms | 34153dba5ea49d457ee97d4024a103b0d05c6bd0 | 3,656,017 |
def greenblatt_earnings_yield(stock, date=None, lookback_period=timedelta(days=0), period='FY'):
"""
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ['AAPL', 'BA']).
:param date: Can be a datetime (i.e. datetime(2019, 1, 1)) or list of datetimes. The most recen... | 333b12b609523ab16eeb1402d0219264a3a159e3 | 3,656,018 |
import shutil
def remove_directory(dir_path):
"""Delete a directory"""
if isdir(dir_path):
try:
shutil.rmtree(dir_path)
return ok_resp(f'Directory removed {dir_path}')
except TypeError as err_obj:
return err_resp(f'Failed to remove directory. {err_obj}')
... | c174568c024cff1948bdf78206e49c2ca40c6b25 | 3,656,019 |
def set_route_queue(path_list,user_position,sudden_id,sudden_xy,pi):
"""
最後の患者が一番近い医師が行くようにする
"""
minimum_dis = 100
minimum_idx = 0
for i in range(len(path_list)):
dis = np.sqrt((user_position[path_list[i][-2]][0] - sudden_xy[0])**2 + (user_position[path_list[i][-2]][1] - sudden_xy[1])**... | 0425c3edf2d488680ccb54661e79698a506e4fe4 | 3,656,023 |
def add(x, y):
"""Add two numbers together."""
return x+y | 92015156eac5bc9cc0be3b1812f9c0766f23020c | 3,656,024 |
import requests
def retry_session(tries=2,
backoff_factor=0.1,
status_forcelist=(500, 502, 504),
session=None):
"""
Parameters
----------
tries : int, number of retires.
backoff_factor : A backoff factor to apply between attempts after the
... | 5766c4623e0e53f4353de1e58080c1ad5c9b4080 | 3,656,026 |
def vc(t, delta, beta):
"""velocity correlation of locus on rouse polymer. beta = alpha/2."""
return ( np.power(np.abs(t - delta), beta)
+ np.power(np.abs(t + delta), beta)
- 2*np.power(np.abs(t), beta)
)/( 2*np.power(delta, beta) ) | 89eff8a8cdb0e84a69e7990ebf0c128ca27ecea8 | 3,656,027 |
def algorithm(name):
"""
A function decorator that is used to add an algorithm's Python class to the
algorithm_table.
Args:
A human readable label for the algorithm that is used to identify it in
the GUI
"""
def decorator(class_):
algorithm_table[name] = class_
r... | 8f67fec3f1933dc0ea041322fcf041f2247bc638 | 3,656,028 |
def comp_easy():
"""Get easy components."""
return Components(ewlaps, gi_setting.DEFAULT_EASY) | d15093dce67657b05665d7a9373d1328b4171f91 | 3,656,029 |
def play(player1, player2, rounds=1, verbose=False, symdict=None):
"""Play a number of `rounds` matches between the two players and return
the score $S = sum_j a_j$, where
a_j = 1 if player1 wone --or-- -1 if player2 wone --or-- 0 otherwise.
"""
if player1 is player2:
raise AttributeEr... | 28e0cc41d664a6681b4af1216d0de6f1a2871f04 | 3,656,030 |
def calc_deltabin_3bpavg(seq, files, bin_freqs, seqtype = "fastq"):
"""
At each position (starting at i), count number of sequences where
region (i):(i+3) is mutated. This is sort of a rolling average and not critical
to the result. It just ends up a bit cleaner than if we looked at a single
base pa... | 5ea614e7280d6ed288ea03e63e86e3129d4e4994 | 3,656,031 |
def make_right_handed(l_csl_p1, l_p_po):
"""
The function makes l_csl_p1 right handed.
Parameters
----------------
l_csl_p1: numpy.array
The CSL basis vectors in the primitive reference frame of crystal 1.
l_p_po: numpy.array
The primitive basis vectors of the underlying lattic... | 3b5e3f21e6da5292fb84eb632ddcfa2ec52507ee | 3,656,032 |
def company(anon, obj, field, val):
"""
Generates a random company name
"""
return anon.faker.company(field=field) | 95580147817a37542f75e2c728941a159cd30bd3 | 3,656,034 |
def delete_schedule():
"""
При GET запросе возвращает страницу для удаления расписания.
При POST запросе, удаляет выбранное расписани
(Запрос на удаление идэт с главной страницы(func index), шаблона(template) функция не имеет).
"""
if not check_admin_status():
flash(f'У вас нет прав для ... | 1e73c757956d4bd78f3a093e2a2ddfde894aeac5 | 3,656,035 |
def map_datapoint(data_point: DATAPOINT_TYPE) -> SFX_OUTPUT_TYPE:
"""
Create dict value to send to SFX.
:param data_point: Dict with values to send
:type data_point: dict
:return: SignalFx data
:rtype: dict
"""
return {
"metric": data_point["metric"],
"value": data_point[... | cf5d7eb1bded092adb2b002ee93ad168e696230a | 3,656,038 |
def write_obs(mdict, obslist, flag=0):
"""
"""
# Print epoch
epoch = mdict['epoch']
res = epoch.strftime("> %Y %m %d %H %M %S.") + '{0:06d}0'.format(int(epoch.microsecond))
# Epoch flag
res += " {0:2d}".format(flag)
# Num sats
res += " {0:2d}".format(len(mdict)-1)
res += '\n'
... | 5a91b02fce07f455f4442fe6fbf76d3609f5a74e | 3,656,039 |
from typing import Optional
from typing import Union
import fsspec
def open_view(
path: str,
*,
filesystem: Optional[Union[fsspec.AbstractFileSystem, str]] = None,
synchronizer: Optional[sync.Sync] = None,
) -> view.View:
"""Open an existing view.
Args:
path: View storage directory.
... | b12471f59ef78e444a43c0e766cb6b4237e65338 | 3,656,040 |
def smi2xyz(smi, forcefield="mmff94", steps=50):
"""
Example:
utils.smi2xyz("CNC(C(C)(C)F)C(C)(F)F")
returns:
C 1.17813 0.06150 -0.07575
N 0.63662 0.20405 1.27030
C -0.86241 0.13667 1.33270
C -1.46928 -1.21234 ... | 083bbc1a242a3f5f247fc6f7066e099dab654b7a | 3,656,041 |
from typing import Optional
from typing import Tuple
from typing import List
def pgm_to_pointcloud(
depth_image: np.ndarray, color_image: Optional[np.ndarray],
intrinsics: Tuple[float, float, float, float],
distortion: List[float]) -> Tuple[np.ndarray, Optional[np.ndarray]]:
"""Fast conversion of opencv... | 574d514c216f0db1f90bf277dc78a5b5dcc2535a | 3,656,042 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.