content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def handle_django_file_upload(f, group):
"""
Handles the uploading of a file from a django form fileField
"""
f_obj = open(get_inbox_file_path(f.name, group), "wb")
for chunk in f.chunks():
f_obj.write(chunk)
f_obj.close()
return f.name | abc9936a78014fd2a8cc1be22177acaf4528cbd1 | 71,470 |
def test_rejects_funcs():
"""#SPC-asts.tst-rejects_funcs"""
def dummy_func(x):
return x
with raises(MacroError):
inrange(dummy_func) | cfae551daef77ee682372313ae76d30c6608102f | 71,471 |
def filter_entry(line, min_obs, min_indiv):
"""
Check the samples and filter
returns a bit flag with
0 - pass
1 - too-few observations
2 - too-few individuals
"""
data = line.strip().split('\t')
fmt = data[8].split(':')
dp_idx = fmt.index("PAD")
obs = 0
n_indivs = 0
f... | 5e8e98b256c8f07aa106dbf7a33df21a797d4bab | 71,472 |
import logging
def get_tile(year, z, x, y, map_object=None):
"""Get tile Endpoint"""
logging.info(f"[ROUTER]: Getting url for tiles for year {year}")
return analyze(year, z, x, y, map_object) | b2da36f4fa3e8b52196e4b4890a86b448bb7d17e | 71,473 |
def imread(f, flatten=False, dtype='float32'):
"""
Read image from file, backend=scipy
f : str or file object -> The file name or file object to be read.
flatten : bool, optional -> If True, flattens the color channels into a single gray-scale channel.
Returns ndarray
"""
# return sp.... | b2c828d3d982492383ef7a726455e40a74e64141 | 71,477 |
def relative_speeds(group_speeds):
"""
Calculates the ratio of a each track's speed to the mean of all other
tracks using leave-one-out loop.
Parameters
----------
group_speeds: iterable
A list of track speeds from all tracks in an experiment
Returns
-------
features: list ... | a82713a601e330c166d8583d1bb96e3f8e81d108 | 71,478 |
def create_orthogonal_projection(
left,
right,
bottom,
top,
near,
far,
dtype=None
):
"""Creates an orthogonal projection matrix.
:param float left: The left of the near plane relative to the plane's centre.
:param float right: The right of the near pla... | c9a213f528dac55781539d1dfd6f5fa3e56fe0f7 | 71,479 |
import numpy
def plot_image_and_mask(img, mask, alpha=0.6, deprocess_func=None,
reference_mask=None,
show_original_image=True,
small=False):
"""Plot an image and overlays a transparent segmentation mask.
Args:
img (arr): the imag... | 516c357ccd1af41c3770edb13b3a26a3d0d8776d | 71,480 |
import math
def sample_size(population_size, confidence_level, confidence_interval):
"""
Get a sample number of the whole population
:param population_size:
:param confidence_level:
:param confidence_interval:
:return:
"""
z = 0.0
p = 0.5
e = confidence_interval / 100.0
n =... | ad3c412b8adc91147a76f192347e4488bd41c8a1 | 71,481 |
def strip_inputs(c):
"""
Converts inputs to buffers for easy
instantiation.
Parameters
----------
c : Circuit
Input circuit.
Returns
-------
Circuit
Circuit with removed io
"""
g = c.graph.copy()
for i in c.inputs():
g.nodes[i]["type"] = ... | bed0032478094f0784116eeb13052d96f4f53540 | 71,482 |
def st_webscrap_tool(html, key=None):
"""Create a new instance of "streamlit_webscrap_tool".
Parameters
----------
html: list
List of html strings.
key: str or None
An optional key that uniquely identifies this component. If this is
None, and the component's arguments are ch... | a7479b5ae7f425af0ed13191f9d1b531288ce56f | 71,484 |
def get_uv_index(zipcode='', city_name='', state_code=''):
"""Returns ultra violet index for a given city, state, or zipcode."""
if not zipcode and not (city_name and state_code):
raise TypeError('Pass a zipcode or a city and state')
url = 'http://oaspub.epa.gov/enviro/uv_search?'+ urlencode(
... | 1809759b572dabdba4c71e5f89e3157fef237835 | 71,485 |
import math
def data_to_sorted_xy(data, logx):
"""
Return a list of (x, y) pairs with distinct x values and sorted by x value.
Enter: data: a list of (x, y) or [x, y] values.
logx: True to return (log10(x), y) for each entry.
Exit: data: the sorted list with unique x values.
"""
i... | 7e84a3f684dc9a82bf5fd48256e5f5c18a5eedb6 | 71,490 |
def is_catalog_record_owner(catalog_record, user_id):
"""
Does user_id own catalog_record.
:param catalog_record:
:param user_id:
:return:
"""
if user_id and catalog_record.get('metadata_provider_user') == user_id:
return True
return False | bb5e649b4cfd38ee17f3ab83199b4736b374d312 | 71,491 |
import requests
def get_transmem_from_uniprot(uniprot_id):
"""
Retains transmembrane regions from Uniprot (first and last residue each).
This function requires internet access.
Parameters
----------
uniprot_id : str
The UNIPROT ID of the protein.
Returns
-... | 3fb8b5061d3ce051d108784a0b9e8d83c875feb3 | 71,492 |
import glob
def load_onezone_data(data_path = './'):
"""
Grab and load all of the summary outputs that exist
"""
dfiles = glob.glob(data_path + 'run????_summary_output.txt')
dfiles = np.sort(dfiles)
all_data = [None]*len(dfiles)
for i in np.arange(len(dfiles)):
all_data[i] = np.... | a7ef49658b9d3322a2131702febe391b63fd6170 | 71,493 |
def odoo_maybe(value, *functions):
"""Like maybe, but treats False as a null value too, so suitable
for dealing with values from Odoo models.
Bear in mind that False can also be a valid value for a boolean
field, so use with care.
>>> from .mappings import lookup
>>> from operator import metho... | 711fa143d3fe408b3403482226f22945a7c3df6a | 71,494 |
def find_latest_tag_version(tag):
""" Find the latest version for the given tag. Returns an integer. """
r = Repo()
version = 1
while make_versioned_tag(tag, version+1) in r.tags:
version += 1
status_update(
'Latest version for tag %s is %d: %s' % \
(tag, version, make... | d39b110483d88c253d913a36dcbc21ea02578c56 | 71,495 |
import joblib
def load_model(filename):
"""
Loads a Scikit-learn model saved with joblib.dump.
This is just an example, you can write your own function to load the model.
Some examples can be found in src/utils.py.
:param filename: string, path to the file storing the model.
:return: the mode... | ad7d165c4ba48fd803e13cc872840e968aa651f5 | 71,497 |
def groupfinder(userid, request):
"""
find the user attached to the current user
"""
# result = None
# user = request.user
# if user is not None :
# result = GROUPS.get(user.email,['group:editors'])
# whatever every body is an editor
return ['group:editors'] | f23bab45b4170a2897bbd34a1068564b53e10a67 | 71,498 |
from ethereum.frontier.vm.interpreter import (
STACK_DEPTH_LIMIT,
process_message,
)
def call(evm: Evm) -> None:
"""
Message-call into an account.
Parameters
----------
evm :
The current EVM frame.
"""
gas = pop(evm.stack)
to = to_address(pop(evm.stack))
v... | 677515debe68863fc9aed896ffcd66de2f51f9d4 | 71,499 |
import random
def init(size):
"""Creates a randomly ordered dataset."""
# use system time as seed
random.seed(None)
# set random order as accessor
order = [a for a in range(0, size)]
random.shuffle(order)
# init array with random data
data = [random.random() for a in order]
return (order, data) | 975ab66f4e759973d55a0c519609b6df7086d747 | 71,500 |
from datetime import datetime
def get_json_raw_data(mdate=None):
"""
使用json返回指定日期的raw_data,为空为当天
:param: mdate, 'YYYY-MM-DD'
:return: dict{raw_data}
"""
today = datetime.datetime.today()
zero_today = datetime.datetime(today.year, today.month, today.day, 0, 0, 0)
zero_today = datetime.d... | defc1c8d33c646ffe4afc1e4ed6f5a424c05a611 | 71,501 |
async def get_password(email):
"""Getting user password. """
user = await User.query.where(User.email == email).gino.all()
if not user:
return False
return user[0].password | 71819dab9a94b49b7583c22077ae2ca9e02d3282 | 71,503 |
def _form_is_rejected(action_name, tracker):
"""Check if the form got rejected with the most recent action name."""
return (
tracker.get("active_form", {}).get("name")
and action_name != tracker["active_form"]["name"]
and action_name != ACTION_LISTEN_NAME
) | 32945962b23a9eb58ab274d5e826419646d09148 | 71,504 |
def kl_divergence(mu, log_var, mu_p=0.0, log_var_p=0.0):
"""KL divergence of diagonal gaussian N(mu,exp(log_var)) and N(0,1).
Args:
mu: mu parameter of the distribution.
log_var: log(var) parameter of the distribution.
mu_p: optional mu from a learned prior distribution
log_var_p: optional log(var)... | 3464a3f66cd2d35a05b887eceddcbf69b21360c7 | 71,505 |
from typing import List
import tqdm
import torch
def convert_examples_to_features(
examples,
tokenizer,
max_seq_length,
doc_stride,
max_query_length,
labels_available,
symbol_based_hypothesis: bool,
padding_strategy="max_length",
threads=None,
tqdm_enabled=True,
):
"""
... | 0eb1c986e2ccbe46f7314e62da3b0180636afd83 | 71,506 |
def saliency_map(connection, image, mode='heatmap', sigma=8,
ax=None, show=True, **kwargs):
"""
Saliency Map plot.
Parameters
----------
connection : network, connection
Network based on which will be computed saliency map.
image : 3D array-like tensor
Image ba... | 9d7d8c46908f273bcc7941dc23e9a7833879c831 | 71,507 |
import hashlib
def getB64FileSha256Hash(file: str) -> str:
"""
Calculate the sha256 hash of a given file and return it in base64 format
:param file: The full path to the file
:return: base64 string representing the file hash in sha256
"""
sha256Hash = hashlib.sha256()
with open(file, "rb"... | e0a10e80bc177f81d21353f80d1572785c86a61e | 71,509 |
def format_permissions(permission_bound_field):
"""
Given a bound field with a queryset of Permission objects, constructs a
list of dictionaries for 'objects':
'objects': [
{
'object': name_of_some_content_object,
'add': (add_permission_for_object... | 6b4b6f3488af1c5b47d8ae23e0e87d53ac1a925f | 71,510 |
def ADFileTimeToUnix(ad_time):
"""Converts AD double-wide int format to seconds since the epoch format.
Args:
ad_time: a 64-bit integer time format used by AD with the number of 100ns
intervals since January 1, 1601.
Note: cribbed from filetimes.py at http://reliablybroken.com/b/2009/09/
Ret... | dffd259c165ad132b4e3a45f98f37fb053a1fbb5 | 71,511 |
def U1Gate(theta):
"""Auxiliary function for the ``U1Gate``."""
return ex.PhaseGate(theta) | 05f35468906375146a354b2fa44b58c3901aa2a2 | 71,512 |
from typing import Dict
def parser(api_data: Dict, country_codes_translator: CountryCodesTranslator):
"""
DESCRIPTION:
This function paste out daily updates of govtrack data from JSON into DataFrame format.
:param api_data: [JSON] non-parsed data.
:param country_codes_translator: [CountryCodesTran... | a5688ffdb521e8840f28010e0be30eb902809b10 | 71,514 |
def to_bytes(string_to_convert, encoding=None, errors='strict'):
"""
Given bytes, bytearray, str, or unicode, return bytes
"""
if encoding is None:
# Try utf-8 first, and fall back to detected encoding
encoding = ('utf-8', __salt_system_encoding__)
if not isinstance(encoding, (tuple,... | 224565ba02d0bbbbddf11ddf5f15c9d4b3402271 | 71,515 |
def download_song(folder: str, url: str, requester: Member) -> Song:
"""
Download a video from youtube
Return a Song class with the music data
"""
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f'{folder}/%(id)s.%(ext)s',
# 'ratelimit': 10240, #limit download rat... | c6bca404a027dd163727ec1db84204445d4760fc | 71,516 |
def captured_sensor():
"""Create a captured today ArloSensor."""
data = _get_named_tuple({"captured_today": [0, 0, 0, 0, 0]})
return _get_sensor("Captured Today", "captured_today", data) | 9c65386dc10a1e7466aeae1169e9bc3d44723968 | 71,517 |
def get_client(fallback=False, fallback_cores=None, fallback_threaded=False, **specs):
"""Try to connect to an existing Dask scheduler with the supplied specs.
Args:
specs: Worker resource specifications, eg. cores=10, memory="8GB". The
scheduler's cluster will have access to a certain numb... | 6b8276be742c31f0c2b480912a3c859b75994a55 | 71,518 |
def Unzip(iterable, container=None):
"""
iterable >> Unzip(container=None)
Same as izip(*iterable) but returns iterators for container=None
>>> [(1, 2, 3), (4, 5, 6)] >> Unzip(tuple) >> Collect()
[(1, 4), (2, 5), (3, 6)]
:param iterable iterable: Any iterable, e.g. list, range, ...
:para... | 86a05b353f5fa27aa17282c79e0441166c856f17 | 71,519 |
def get_scores(session, submission_id):
"""Get the scores for each fold of a submission.
Parameters
----------
session : :class:`sqlalchemy.orm.Session`
The session to directly perform the operation on the database.
submission_id : int
The id of the submission.
Returns
----... | 972774dc572cfd190245329acdff708f7356af26 | 71,520 |
def load_npy(npy_fn):
"""
:param npy_fn:
:return: (numpy) raw signal array
"""
return np.load(npy_fn)[0] | e31567890f515c2bfa36b97859ad85bba205673f | 71,521 |
def samples():
"""
Create collection of Samples, useful for mocking a Project.
:return Iterable[Sample]: collection of bare bones Sample objects, with
only name and protocol defined
"""
return [
Sample({SAMPLE_NAME_COLNAME: sn, "protocol": p})
for sn, p in PROTOCOL_BY_SAMPLE... | a05de6cdf420a4a456893fb73baa487f4f544b4d | 71,522 |
def build_unet_generator():
"""
Create the U-Net Generator using the hyperparameter values defined below
"""
kernel_size = 4
strides = 2
leakyrelu_alpha = 0.2
upsampling_size = 2
dropout = 0.5
output_channels = 1
input_shape = (256, 256, 1)
input_layer = Input(shape=input_sh... | b245cf900554d172f9dc150dab06820c5babdbc3 | 71,523 |
def v(n):
"""compute u value of the lhs matrix"""
return ((n ** 2) * (n + 1)) / 2 | 897f905b04812711841f06599565343d65af013e | 71,524 |
import re
def decodeAsOpenSearch(url):
"""
Decode data hidden inside a url format for searches
Parameters: url- the url to decode
Returns: a string with the decoded data
"""
# pattern = 'http://www.baidu.com/s\?wd=(?P<englishText>[a-zA-Z0-9+]+)'
pattern = 'http://'+ domain + '/s\?wd=(?P<englishText>[... | 4812441bad3496b624a24d1a71117831ce4ba1d8 | 71,525 |
def create_fnet(widths, orthoinit, llbias, bnidx=-1):
""" Creates feature-generating network, a multi-layer perceptron.
Parameters:
widths: list of widths of layers (including input and output widths)
orthoinit: whether to use orthogonal weight initialization
llbias: whether to use bias in the last ... | 9ee85e2042fe2d652cb3a73947404ea8b553e2ba | 71,527 |
import torch
from typing import OrderedDict
def restore_network(net, pt_model, only_backbone=False):
"""
Restore weight. Full or partial depending on `only_backbone`.
"""
strict = False if only_backbone else True
state_dict = torch.load(pt_model)
# create new OrderedDict that does not contain ... | c354a4e7f73586c24195cc05b2e1307ae6022568 | 71,528 |
def convert_dottable(natural_dict: dict) -> DottableDict:
"""Convert a dictionary to DottableDict.
Args:
natural_dict (dict): Dictionary to convert to DottableDict.
Returns:
DottableDict: Dottable object.
"""
dottable_dict = DottableDict(natural_dict)
for k, v in natural_dict.i... | be3b3ef2be845f149c7820348dc87d20fb9fbdd5 | 71,531 |
def create_experiment(args):
"""
Create a single experiment from arguments.
:param args: The parsed arguments.
:return: A new experiment with its own trainer.
"""
experiment_name = get_experiment_name(args)
config = build_experiment_config_dict(args)
trainer = get_trainer(args=args, conf... | fd0c48f10a6bcb17c12a9f73ede45751c4ed339d | 71,532 |
def _get_song_index(song_id: str) -> int:
"""
Given a MSD-format song ID, return the corresponding integer index
from `msdutils.song_ids`.
Can be used to create a vector of the songs each user has and has not
listened to -- see `create_user_vector()`.
"""
return song_ids[song_ids['song... | b121ef3cb7bfd67283a9ab0ba9ba46824b0450a6 | 71,533 |
from typing import Tuple
from typing import List
def make_gear_triangles(height: float, **kwargs) -> Tuple[List[float], List[int]]:
"""
歯車の立体形状を生成し、三角形のリストを返す
height以外の引数はmake_gear_figureと同じ
デフォルトでY軸が歯車の高さに対応するが、height_axisオプション(値はx,y,zから選択)で変更可能
:param height: 歯車の高さ
:return: (vertices, indice... | dfabfe9da1e0074e9214605ced4afd0f5550fa84 | 71,534 |
def multivariate_normal(mean, cov, size=None, check_valid='ignore', tol=1e-8,
dtype=float):
"""(experimental) Multivariate normal distribution.
Returns an array of samples drawn from the multivariate normal
distribution. Its probability density function is defined as
.. math::
... | efa1f8593777b308a5ef6ae7c1c0ddcb72d8b06b | 71,535 |
def white_tophat(input, size = None, footprint = None, structure = None,
output = None, mode = "reflect", cval = 0.0, origin = 0):
"""Multi-dimensional white tophat filter.
Either a size or a footprint, or the structure must be provided. An
output array can optionally be provided. The orig... | aebabf9819d32e3f9b324f9ecdaf47adc2bcf13c | 71,536 |
def svn_wc_create_conflict_result(*args):
"""
svn_wc_create_conflict_result(svn_wc_conflict_choice_t choice, char merged_file,
apr_pool_t pool) -> svn_wc_conflict_result_t
"""
return apply(_wc.svn_wc_create_conflict_result, args) | 4220a1e1109fbb2658f655305816df8343e74e40 | 71,537 |
import math
def is_prime(num):
"""
check whether a number is a prime
:param num:
:return:
"""
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num % i == 0:
return False
return True | ee2d52833a8f4f3ce29ff64be4ad94ba8b119214 | 71,538 |
def create_many_particle_state(imsize=None, N=None, phi=None, radius=5.0,
polydispersity=0.0, seed=None, **kwargs):
"""
Creates a random packing of spheres and generates the state. In order to
specify the state, either (phi, imsize) or (N, phi) or (N, imsize) must be
given. Any more than that an... | 245c4a770a6ca0f2452413fa08c167ad7b1ed5fa | 71,539 |
def sxc2(plot, *args, **kwargs):
"""scale_x_continuous(trans='log2',...)"""
if not "trans" in kwargs:
kwargs["trans"] = "log2"
return plot + p9.scale_x_continuous(*args, **kwargs) | 1983d88d45487e40459309d2c7480ae157930581 | 71,540 |
def ratio_cap_letters(email):
#def ratio_cap_letters(sent_list): # for testing
"""
calculates the ratio of upper case letters except for at the beginning of the sentence
# percentage = a/(b-c)
# a: total contiguously capitalized letters NOT at the beginning of sentence
# b: total letters
# c: ca... | 3342c0106f69d201d707299eb76e0f37eab02f9e | 71,541 |
def pick_highest(board):
"""
:param board: The current gamestate
:return: The move with the highest rating
"""
options = get_possibilities(board, Player.COMPUTER.value)
scores = [evaluate(x[0]) for x in options]
return options[scores.index(max(scores))][1] | 3b904ec461b6ab70dd0a189e579a352b24b3878e | 71,542 |
from typing import Callable
from typing import Optional
def forced_exit_message(callback: Callable[[HWND], Optional[bool]]) -> MessageEntry:
"""Listens for a window that should be forced to exit."""
return True, windows_constants.HSHELL_ENDTASK, _window_handle_callback(callback), | 2fa398f9b690979c1d63fe77981b4b9d37b8191c | 71,543 |
import sqlite3
def import_sqlite3(sql_file, separator):
"""Read sqlite db"""
conn = sqlite3.connect(sql_file)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
data = []
for row in cursor.execute('SELECT * FROM items'):
row = import_data(row, separator)
if row != None:
... | 95f74e4a67704227a349d91dadada33c24691aed | 71,544 |
from typing import Optional
def is_boolean_type(property_schema: dict) -> Optional[bool]:
"""Return true if the JSON Schema type is a boolean or None if detection fails."""
if "anyOf" not in property_schema and "type" not in property_schema:
return None # Could not detect data type
for property_t... | c092ab064139bf8bb92e59afae9829eb9bf5e6c2 | 71,545 |
def change_angle_origin(angles, max_positive_angle):
"""
Angles in DICOM are all positive values, but there is typically no mechanical continuity in across 180 degrees
:param angles: angles to be converted
:type angles list
:param max_positive_angle: the maximum positive angle, angles greater than t... | 4a8b7d14719034cec659deaa257b53f9a7a79bb5 | 71,546 |
def greedy_set_cover(universe, subsets, costs):
"""Approximate greedy algorithm for set-covering. Can be used on large
inputs - though not an optimal solution.
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of e... | aef8aa0b345d5ba01db841bdfb6485661d245d5d | 71,547 |
def get_classmap(samples):
"""Get {location: classIdx} mapping"""
def parser(info, networks):
return info['__location']
locations = list(parse_samples(samples, parser))
return {location: i for i, location in enumerate(sorted(set(locations)))} | 2d79d37dceba0502cd6d13f274bd3984336a1d1d | 71,548 |
def tokenize_guitarset_example(
ds: tf.data.Dataset, spectrogram_config: spectrograms.SpectrogramConfig,
codec: event_codec.Codec, is_training_data: bool,
onsets_only: bool, include_ties: bool
) -> tf.data.Dataset:
"""Tokenize a GuitarSet transcription example."""
def _preprocess_example(ex, name):
... | e140fc47069cda39614905299ba49e064b363cd6 | 71,549 |
def _pascal_triangle_map(size: int) -> np.ndarray:
"""Array representation of pascal's triangle, centered
Args:
size (int): width and height of the triangle
Returns:
Numpy array containing centered pascal's triangle. The numbers
are repeated four times in squares and the squares ar... | a48bf9a9eee6982acbce520b0269abed0fcfb529 | 71,550 |
def relabel(labels):
"""Relabel the cluster labels so that they appear in order
"""
labels = labels.copy()
d = {}
k = 0
for i in range(len(labels)):
j = labels[i]
if j not in d:
d[j] = k
k += 1
labels[i] = d[j]
return labels | 8407d569252af82d112edfb1391ec323903cd457 | 71,551 |
def dumps():
"""Convert to a Json string everything we have in this system."""
return json_lib.dumps(dump(), separators=(',', ':')) | 7b66245f71268e5a094d0b6cb8696f095d3d00b4 | 71,552 |
def dict_to_ions(idict):
""" Manipulate dict into an ion astropy Table
Will likely be deprecated
Parameters
----------
idict : dict
Returns
-------
table : astropy.Table
"""
# Could probably use add_row or dict instantiation
table = None
for ion in idict.keys():
... | e262f3601e1a80689cbaaed3ada257f571b9f438 | 71,553 |
def hunderline(*content, sep=" "):
"""
Make underlined text (HTML)
:param content:
:param sep:
:return:
"""
return html_decoration.underline(value=html_decoration.quote(_join(*content, sep=sep))) | 44f286ebd7eebab94eea0db5d4178ad6599ccad4 | 71,554 |
def encoded_jwt_expired(claims, kid, rsa_private_key):
"""
Return an example JWT that has already expired.
Args:
claims (dict): fixture
kid (str): fixture
rsa_private_key (str): fixture
Return:
str: JWT containing claims encoded with private key
"""
headers = {... | f495d66f0c29c824a378fcae3d14be71fc64916a | 71,555 |
import typing
def get_required_intents_for(event_type: typing.Type[Event]) -> typing.Collection[intents.Intents]:
"""Retrieve the intents that are required to listen to an event type.
Parameters
----------
event_type : typing.Type[Event]
The event type to get required intents for.
Return... | beeffe5425f0190c986ee870e23b6c2efe4d548f | 71,556 |
def transform_dictQPV(Dinit, index_param, percent=0, index=0, global_test=False):
"""
Transform a specific value of Threshold dictionary. A sorting condition should be respected : q < p < v.
:param Dinit: Dictionary containing the dictionary which should be modified. In form of a list of dictionarie... | 3935ca58e0f030820319af3df48a9c0ebb0f81bd | 71,557 |
import re
def setup_controls(joystick):
"""
Joystick wrapper.
"""
if re.search('playstation', joystick.get_name(), re.I):
return Ps3Controller(joystick)
elif re.search('X-box', joystick.get_name(), re.I):
return XboxController(joystick)
elif re.search('Saitek', joystick.get_name(), re.I):
return MySaite... | e172df6a46ab833468431eba6d54d539dbe56db9 | 71,559 |
def read_homography_calibrator_params():
"""
Reads the homography calibrator parameters file
"""
return read_yaml_file(homography_calibrator_params_file) | 35db1223aa596d63c444893aa249b297e79681a9 | 71,560 |
from pathlib import Path
import re
def get_vara_status(llvm_folder: Path) -> GitStatus:
"""Retrieve the git status of VaRA."""
try:
with local.cwd(llvm_folder / LLVMProjects.vara.path):
fetch_remote('origin')
git_status = git['status']
stdout = git_status('-sb')
... | 06d7e653e9b9676101fd8934977a5cdfcbfb5b75 | 71,561 |
def get_chunks():
"""
Get the hosts of the content and index chunks assigned to an index server
:return: List of dictionary of hosts, empty list if no chunks assigned
"""
# requester = request.remote_addr
requester = request.get_json()['host']
# Get all index servers for requester
resul... | 78887610bc796a3e0ae6cb5d1e220d592b33d019 | 71,562 |
from typing import List
from typing import Dict
from typing import Any
def create_service_color_instances(tasks: List[EcsTask], port: int) -> List[Dict[str, Any]]:
"""Create the instances for the service-colors"""
return [
{
'ipv4': task.host_ipv4,
'port': port,
}
... | 5aded8db5716796a55b75b82cbffd4ffaf189c12 | 71,563 |
from typing import List
from typing import Optional
def find_story_conflicts(
trackers: List[TrackerWithCachedStates],
domain: Domain,
max_history: Optional[int] = None,
) -> List[StoryConflict]:
"""Generates `StoryConflict` objects, describing conflicts in the given trackers.
Args:
track... | d0ca7385dd4d407e1a0c485a4ae2d72d3c75db61 | 71,564 |
def scan_markdown_content_for_all_paths(content: str):
"""
Search a markdown formatted content string for links and return a set of file links
Search for all links and build set of those links where the link is not a link to a 'https:\\' address,
and then return the set of local file links. The return... | dc5a51a4a66e0bbc08516882891271ed24fa293e | 71,565 |
def _is_sparse_variable(x):
"""
Returns
-------
boolean
True iff x is a L{SparseVariable} (and not a L{TensorType},
for instance).
"""
if not isinstance(x, Variable):
raise NotImplementedError(
"this function should only be called on "
"*variable... | fea0729919b21769c32138b11bb0ae2688435c63 | 71,566 |
def recon(W, v, proj, mask, bounds, iters, stop, fp):
"""
Intermediate function that checks whether or not CUDA is present before
calling the main reconstruction routine. If CUDA is not present then
pre-computed results are loaded. I would recommend to use recon_iter()
if you want to implement this ... | 59a1b2abb1be6ba47a4688f8880e9f2ce0791725 | 71,567 |
def test_function_arbitrary_arguments():
"""
Arbitrary Argument Lists
@see: https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists
Functions can be called with an arbitrary number of arguments. These arguments will be wrapped up in
a tuple. Before the variable number of argum... | 45394f82a40ae1e42b9b5cf31bee9346de06e28e | 71,568 |
def from_ecdf(diff_data, n, seed=1):
"""
Parameters
----------
diff_data : netcdf4
dataset containing waiting times as peak differences.
n : int
number of nodes.
Returns
-------
array of waiting times with lentgh n.
"""
inter_diffs = diff_data['diffs_v2'][2... | 916c820a821fc95a5b588a8ed3a1d6de208e4ff1 | 71,569 |
def load(export_dir, obj_template):
"""Load a nested structure from export_dir.
Args:
export_dir: The directory to load from.
obj_template: An object that provides the nested structure to mimic.
Returns:
Loaded nested structure.
Raises:
FileNotFoundError: No such file or directory.
"""
i... | e227da8c858beec570792fe68a9f604a2e6fda64 | 71,570 |
def load_CIFAR10_small_data(cifar10_dir, save_folder = 'data', classes=None):
""" loads a subset of CIFAR10 classes """
if classes is None:
classes = np.array([0,1,2])
classes_string = ''
#else:
classes_string = '_' + '_'.join([str(x) for x in np.sort(classes).tolist()])
# create ... | f0f64a6d15ff4ed9c7c84e8a8687b708da51b1f7 | 71,571 |
def TempC500mb(tempc, pres):
"""Temperature in Celsius at 500 mb
INPUTS:
Temperature profile from sounding - tempc (C)
Pressure profile from sounding pres (hPa)
OUTPUTS: Temp(C)
Source: http://weather.uwyo.edu/upperair/indices.html
Prints a warning if a pressure value below 2000 Pa input... | 3f7487bf92ee15d05addc996e44b1ff55b57d5fc | 71,572 |
import numpy
def transform_to_p1(points_abc, sym_elems, shift, centrosymmetry, indexes_xyz,
densities):
"""Transoform indexes_xyz and densities to P1 space group.
Parameters
----------
points_abc : numpy.int [6]
DESCRIPTION.
sym_elems : numpy.int [13, n_sym_elems]... | 387ef51b2bc798a583b3665e12a3be38edb5e285 | 71,573 |
def _pilot_state_progress(pid, current, target):
"""
See documentation of 'unit_state_progress' below.
"""
# first handle final state corrections
if current == CANCELED:
if target in [DONE, FAILED, CANCELED]:
return[target, []]
# allow to transition from FAILED to DONE (don... | 0535490ac15eae6e9250884d1566885a2f13ae92 | 71,574 |
def bounding_rect(mask, pad=0):
"""Returns (r, b, l, r) boundaries so that all nonzero pixels in mask
have locations (i, j) with t <= i < b, and l <= j < r."""
nz = mask.nonzero()
if len(nz[0]) == 0:
# print('no pixels')
return (0, mask.shape[0], 0, mask.shape[1])
(t, b), (l, r) = [... | 850db378abb0a8e1675e0937b66dfb4061ced50b | 71,575 |
def block_diagonal(dirichl_space, neumann_space, A):
"""
Compute the block-diagonal preconditioner for system matrix A.
Suitable for direct formulation.
"""
ep_in = PARAMS.ep_in
ep_ex = PARAMS.ep_ex
kappa = PARAMS.kappa
identity = sparse.identity(dirichl_space, dirichl_space, dirichl_sp... | 1838df20aed14c38ecb2e1f157683137a6a3a409 | 71,576 |
import torch
def process_pair(data, global_labels):
"""
:param path: graph pair data.
:return data: Dictionary with data, also containing processed DGL graphs.
"""
edges_1 = data["graph_1"] + [[y, x] for x, y in data["graph_1"]]
edges_2 = data["graph_2"] + [[y, x] for x, y in data["graph_2"]]... | a4547e0fb772a9eeb9d40572176d95f8a9342f74 | 71,578 |
def chat():
"""Chat room. The user's name and room must be stored in
the session."""
name = session.get('name', '')
log('/chat request', request)
if name == '':
return redirect(url_for('.index'))
return render_template('chat.html') | 6128a51554e6c363fa44d5ae084c2951066f0ee6 | 71,579 |
from .__temp_model_builder import build_fn as temp_build_fn
def keras_prep_workflow(model_initializer, build_fn, extra_params, source_script):
"""Conduct preparation steps necessary before hyperparameter optimization on a `Keras` model. Such steps include parsing and
modifying `build_fn` to be of the form use... | 78e9ef5778a132f0c713dd04b3cc6eda97d5d183 | 71,580 |
def telemetry(fn):
"""Decorate CLI and other functions that need special Sentry client handling.
This decorator is only required on functions that:
1) Specifically catch and re-raise exceptions.
2) Call sys.exit() directly.
"""
@wraps(fn)
def telemetry_wrapper(*args, **kwargs):
... | d1bc298c02a4b8d096c3af8826065e9b247d680c | 71,581 |
from typing import Tuple
def _get_average_buy_units_sold(
operations_by_type: OperationsByType
) -> Tuple[OperationIterable, OperationIterable]:
"""Gets list of operations that were sold using average method.
Args:
operations_by_type: Operations by type.
Raises:
ValueError: sold more units than we... | 97210ea3bf842ff657ff3d0749ebf8196a2a130d | 71,582 |
import csv
def get_return_fields(filepath):
"""Extract the returnable fields for results from the file with
description of filters in ENA as a dictionary with the key being the field
id and the value a list of returnable fields
filepath: path with csv with filter description
"""
returnable_fi... | d70efe68de8cbd100b66cee58baf6ca542cb81a8 | 71,584 |
import json
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(namespace) or config(dictionary)
"""
# parse the configuration file
with open(json_file, "r") as config_file:
config_dict = json.load(config_file)
# convert t... | 5a2e22a4edfd8411500ee1a381bc2682df71fd40 | 71,585 |
def create_headers(type, code, length, conn):
"""
This function creates the headers needed to send a correct HTTP response
to the client. The content of the headers depends on the generated output
code, the type and length of the content we send back and whether or not
we close the TCP connection.
... | 68b54bea8417cd875f40568cf2743fc5c58e9dae | 71,586 |
def filter_convergence(x, zx, lens_efficiency, cosmology):
"""Filter for convergence.
This function computes the filter for the convergenge power spectra,
described in [1]_.
Parameters
----------
x: (nx,) array_like
Array of comoving distances at which evaluate the lensing
effic... | 0d00135d49e59eeadbffaf7be6056238b10fa455 | 71,587 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.