content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import warnings
def plugin(version: str):
"""See `https://mypy.readthedocs.io/en/latest/extending_mypy.html`_."""
if float(version) < 0.7:
warnings.warn(
"This plugin not tested below mypy 0.710. But you can"
f" test it and let us know at {ISSUE_URL}."
)
return JSON... | 7f770cf1ae9ceeb8e55f795390f9f3f9532b213b | 3,602,300 |
def kd(*a):
"""
Dump pointers and symbols at the specified address.
"""
return pwndbg.commands.telescope.telescope(*a) | f14408c044baf7dcb378a5ee56a0650d6357cba3 | 3,602,301 |
import os
def insert_rows(fc,
features,
fields,
includeOIDField=False,
oidField=None):
""" inserts rows based on a list features object """
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
icur = None
... | 4a2b9145b2136071017141c4c0cc88b94141c1aa | 3,602,302 |
def Logout(request):
"""
List all code snippets, or create a new snippet.
"""
logout(request)
return Response({"status":"user logged out"}) | d6757df2ec17d74dc063dcda9d0f1982d36bc915 | 3,602,303 |
def copy_request_to_notice(doc_change_id):
"""
Copy all stakeholders from request to notice.
:param doc_change_id:
:return:
"""
# Get stakeholders to copy
stakeholders = Request.query \
.filter(Request.doc_change_id == doc_change_id) \
.with_entities(Request.doc_change_id,
... | fbffd158c177f40b6470b119e0d5c4e565fbfcb1 | 3,602,304 |
async def flow_id():
"""
1 -> 2 -> 3 -> 4 -> 5
\ /
7 -> 8 -> 9 -> 10
/
6
"""
t1 = prefect.Task("t1", slug="t1")
t2 = prefect.Task("t2", slug="t2")
t3 = prefect.Task("t3", slug="t3")
t4 = prefect.Task("t4", slug="t4")
t5 = prefect.... | c51e39f62b00f58be66455d04bca224f1700d756 | 3,602,305 |
def check(requirements_paths=[], metadata=[], projects=[]):
"""Return True if all of the specified dependencies have been ported to Python 3.
The requirements_paths argument takes a sequence of file paths to
requirements files. The 'metadata' argument takes a sequence of strings
representing metadata. ... | 343d5f7c5b07fdd720d904b4ac48994039085314 | 3,602,306 |
def _options_handler(request):
"""Request handler for OPTIONS requests
This is a request handler suitable for return from
_get_handler_for_request. It returns a 200 and an empty body.
Args:
request (twisted.web.http.Request):
Returns:
Tuple[int, dict]: http code, response body.
... | 319b083565551f2512a71bb671dd76cfd76063dc | 3,602,307 |
import os
def GetEbuildPathsFromSymLinkPaths(symlinks):
"""Reads the symlink(s) to get the ebuild path(s) to the package(s).
Args:
symlinks: A list of absolute path symlink/symlinks that point
to the package's ebuild.
Returns:
A dictionary where the key is the absolute path of the symlink and the ... | 22ae73b3939ec608a9392853031961f9e22c3234 | 3,602,308 |
def Smooth121(v, sdims, NSmooths= 1, perdims= []):
""" Applies [1 2 1]/4 stencil in multiple dimensions
Usage
-----
Smooth121(DataArray,list1,Nsmooths=int1,perdims=list2)
name : xarray.DataArray - e.g., ds.var
list1: list of dimensions over which to smooth - e.g., ['Y','X']
... | 9b2ccef223defe1d4caaaf9d982109907998c805 | 3,602,309 |
def kind(event):
"""
Finds the type of an event
:param event: the event
:return: the type of the event
"""
return event.type | 68f0170eac9fc06f954542769dcd0d4ef974e725 | 3,602,310 |
def get_entities_by_kind(membership_cache=None, is_active=True):
"""
Builds a dict with keys of entity kinds if and values are another dict. Each of these dicts are keyed
off of a super entity id and optional have an 'all' key for any group that has a null super entity.
Example structure:
{
... | c5307c7ac5b27bbbbb7e6ba7a78fb34e8f191cc5 | 3,602,311 |
def pontoon_js_url(request):
"""
Inserts a context variable PONTOON_JS_URL from settings
"""
return {'PONTOON_JS_URL': getattr(settings, 'PONTOON_JS_URL', None) or
"https://pontoon-dev.mozillalabs.com/en-US/static/"
"js/project/pontoon.js"} | 2ff3253c2860f327730c0a2b66f34a12fc4884c5 | 3,602,312 |
def extensions(app):
"""
Register 0 or more extensions (mutates the app passed in).
:param app: Flask application instance
:return: None
"""
# from profile.database import db, migrate
db.init_app(app)
ma.init_app(app)
migrate.init_app(app, db)
return None | f0725e7fccefd2bb5e6368829eddd80f9bf81747 | 3,602,313 |
import logging
import sys
import pickle
def wrap_to_store(key, obj, storage, objhash,
compression=False, skipcache=False):
"""
Wraps a callable object in order to execute it and store its result.
"""
def exec_store_wrapper(*args, **kwargs):
"""
Simple execute and stor... | e1aed43cec8498c153efdb2ce2531da76abf75cb | 3,602,314 |
from operator import gt
def _pad_feature(feature: gt.Field, *, padding_value: gt.Field,
target_size: int) -> gt.Field:
"""Pads a single feature to the target total number of elemenets."""
result = tensor_utils.pad_to_nrows(
feature,
target_nrows=tf.constant(target_size),
padding... | a469906b0001962e5e9dc722e3d5ef2c358cbae0 | 3,602,315 |
def YscMatrix():
"""(read-only) Complex array of Ysc matrix at bus. Column by column."""
return get_float64_array(lib.Bus_Get_YscMatrix) | 62053a6d58842a5b990c93c7bb94d726495a8566 | 3,602,316 |
def select(*_):
"""
Always return None
"""
return None | 9f29559a50440143d9e3fe46be766590516f1fc4 | 3,602,317 |
def question_resource(request):
"""
Secured question API.
Only authenticated users have access.
Don't allow suspect characters in fields - prevent injections.
Permission rules:
You can create question only for your current user.
Your question will be approved by the administrator.
... | a00f561199a4e5b14be9dd891bb95f92553269c6 | 3,602,318 |
from typing import Deque
def parse_array(tokens: Deque[Token]) -> JSONArray:
"""Parses an array out of JSON tokens"""
array: JSONArray = []
# special case:
if tokens[0].type == 'right_bracket':
tokens.popleft()
return array
while tokens:
value = _parse(tokens)
arr... | 1143b27a57fba5cdb8b5d44f30e78442644d1fc3 | 3,602,319 |
import sys
def PromptWithValidator(validator, error_message, prompt_string,
message=None):
"""Prompts the user for a string that must pass a validator.
Args:
validator: function, A validation function that accepts a string and returns
a boolean value indicating whether or not th... | 19660e548484506feb5e2a7576ea7844b700b1df | 3,602,320 |
def get_minibatch(roidb, voxelizer):
"""Given a roidb, construct a minibatch sampled from it."""
# num_images = len(roidb)
# assert(num_images % cfg.TRAIN.NUM_STEPS == 0), \
# 'num_images ({}) must be dividable by NUM_STEPS ({})'. \
# format(num_images, cfg.TRAIN.NUM_STEPS)
# Get the in... | fa1fde0f4eb164cce1f788f6132f832501380a7d | 3,602,321 |
def comfort_chart(data_frame, title, output_path, config, locator):
"""
Main function of comfort chart plot
:param data_frame: results from demand calculation
:type data_frame: pandas.DataFrame
:param title: title of plot
:type title: string
:param output_path: path to output folder
:ty... | 528450aae20b3b29030a2d4fdd7431b357fd4b5e | 3,602,322 |
def remove(ui, repo, *pats, **opts):
"""remove the specified files on the next commit
Schedule the indicated files for removal from the current branch.
This command schedules the files to be removed at the next commit.
To undo a remove before that, see :hg:`revert`. To undo added
files, see :hg:`f... | 71b2cc31ef267b42cb27259d32d57ac8c37185b3 | 3,602,323 |
def start_xtn(session, xtn_id, username, command, is_readonly, details, ignore):
""" Wrapper to log the start of a transaction (or running command).
Takes a dictionary with the transaction parameters. The keys are
command, usename, readonly, and details. The details parameter
is itself a a dictionary... | 927b6730c489bdb9696e5135b4ffba460c6896a9 | 3,602,324 |
def test_rendering(data, font_file_name, min_allowed, max_allowed, language=None):
"""Test the rendering of the input data in a given font.
The input data is first filtered for sequences supported in the font.
"""
vhb = Vharfbuzz(font_file_name)
font_characters = set(vhb.ttfont.getBestCmap().keys()... | 34e11178e755f86c585a977e8468f7eb24666632 | 3,602,325 |
def get_values():
"""
Get dictionary of values from the backend
:return:
"""
# First load a mapping between config name and default value
default_initial = ((name, options[0])
for name, options in settings.CONFIG.items())
# Then update the mapping with actually values... | a088a43018189b54f5b149cf6b2b10f319237d8a | 3,602,326 |
def rt_merge(rt_stops, intersect=0):
"""
merge and filt RTStops
filter by threshold for each replicate
Input: RTStop in DataFrame (bed6+)
"""
if len(rt_stops) == 0:
raise ValueError('rtstop file not found')
elif len(rt_stops) == 1:
m = rt_stops[0].rename(index=int, columns={... | e3b3819f15ceb29eb349bd11c2329220438654dc | 3,602,327 |
def kmedian(I,J,c,k):
"""kmedian -- minimize total cost of servicing customers from k facilities
Parameters:
- I: set of customers
- J: set of potential facilities
- c[i,j]: cost of servicing customer i from facility j
- k: number of facilities to be used
Returns a model, rea... | c66ade62fadec398ac24d60c2997d9cc866ec088 | 3,602,328 |
def totalCost():
"""
Total Cost
This method returns a dictionary of the total price paid for each asset,
which is cost_basis from the Alpaca API.
:return: dictionary
"""
totalcost = dict()
for position in portfolio:
# Strings are returned from API; convert to floating point type
... | a74d1a7aca9bb3036c20ed8e1a8279098f4b82e0 | 3,602,329 |
def absolute_vorticity(u, v, dx=None, dy=None, latitude=None, x_dim=-1, y_dim=-2):
"""Calculate the absolute vorticity of the horizontal wind.
Parameters
----------
u : (..., M, N) `xarray.DataArray` or `pint.Quantity`
x component of the wind
v : (..., M, N) `xarray.DataArray` or `pint.Quan... | 2139f83425a79be306ed5fbbab8c009412944869 | 3,602,330 |
def recipient(request, country, recipient_id, slug):
"""
View for recipient page.
- `country` ISO country, as defined in countryCodes
- `recipient_id` is actually a globalrecipientid in the date
"""
country = country.upper()
if not recipient_id.startswith(country):
raise Http404
... | c0c1f976f38c4562c893e85e63a7338abd360204 | 3,602,331 |
import array
def new_double(*args, **kwargs):
"""Creates a new double ("d") array
Args are the same as :func:`array.array` except for typecode,
which is passed by this module.
Returns:
array.array: New, initialized array
"""
return array.array(DOUBLE_TYPECODE, *args, **kwargs) | 0c31a8e154299dc4cbe06b6766ea0939709be9c4 | 3,602,332 |
def _reduction_output_shape(x, output_shape, reduced_dim):
"""Helper function to reduce_sum, etc."""
if output_shape is None:
if reduced_dim is None:
return Shape([])
else:
if reduced_dim not in x.shape.dims:
raise ValueError(
"reduced_dim=%s not in x.shape.dims=%s" % (reduce... | 2a46e878a69aaf57bd5bda3a410fd752c6c0c9cb | 3,602,333 |
def prepare_data(only_prepare_data,delete_last_row):
"""Loads the data, pivots it and if needed aggregates columns
Args:
only_prepare_data (Boolean): True if ohnly prepares data (aggregates ages and saves data)
delete_last_row (Boolean): Deletes last row (because info is not complete)
Ret... | 17180061c84fe73bc16bb919470c16d71f0845b0 | 3,602,334 |
def connect(user, password, db, host=HOSTNAME, port=PORT):
"""
Returns a connection and a metadata object
:param user: the database username
:param password: the database password
:param db: the database we'd like to connect to
:param host: the database adress/hostname
:p... | d0670cce6bc3aac2b03a5fd82e1bba186f1a861e | 3,602,335 |
def gene_pvalue_sel_nb(df_model):
""" Calculate dNdS selection p-values using a conservative NB model
(NB model integrates over uncertainty in the rate estimate)
"""
PVAL_SYN, PVAL_MIS, PVAL_TRUNC, PVAL_NONSYN = [], [], [], []
for i, row in df_model.iterrows():
p_syn, p_mis, p_trunc, p_n... | 639d53ed13a2514c84d7fb5a5a122d016394f7e4 | 3,602,336 |
import struct
import os
def genSerial():
"""
Generate a (hopefully) unique integer usable as an SSL certificate serial.
"""
return abs(struct.unpack('!l', os.urandom(4))[0]) | bafc3d8145ff876816bbd224fee0850934ab4c31 | 3,602,337 |
def parse_repo_origin_url(repo_url) -> dict:
"""
parse a repository clone url and return a dict containing three keys: owner, repo, domain
:param repo_url: clone url such as # https://github.com/owner/repo/
:return: dictionary
"""
url_details = dict()
try:
if repo_url.startswith(... | 82de5b5144504d53f6c1fd92d6473d8e34047e88 | 3,602,338 |
def modular_power(a, n, p):
"""
计算a^ n % p
if n == 0:
return 1
elif n == 1:
return a % p
temp = a * a % p
if n & 1:
return a % p * modular_power(temp, n // 2, p) % p
else:
return (modular_power(temp, n // 2, p)) % p
原文:https://blog.csdn.net/qq_36921652/art... | f9f234ec6532e13fcd9d393163933967ae6e7da7 | 3,602,339 |
def is_correct_type(item, expected_type):
"""Function for check if a given item has the excpected type.
returns True if the expected type matches the item, False if not
Parameters:
-item: the piece of data we are going to check.
-expected_type: the expected data type for item.
"""
... | 37d23e2c7dc1e630d8ead99fde09250196bd664e | 3,602,340 |
import os
def get_results(exp_name):
"""
Method to see if the results are present,
if not, process said experiment and store it.
"""
results_path = '{}/results'.format(pipeline_dir)
file = "{}/{}.csv".format(results_path, exp_name)
# Make the results directory
if not os.path.isdir(res... | 415bcb128266e7a00334391dc1102adfa1717c05 | 3,602,341 |
import six
def _get_column_indices(X, key):
"""
Get feature column indices for input data X and key.
For accepted values of `key`, see the docstring of _get_column
"""
n_columns = X.shape[1]
if callable(key):
key = key(X)
if _check_key_type(key, int):
if isinstance(key,... | 492b49fd1291f309ae038289307834736579ee10 | 3,602,342 |
import re
def summary(node, opt):
"""
Backend for creating summary of the node tree.
See :py:func:`~matlab2cpp.qtree` for behavior.
Args:
node (Node): Relative root of the tree
Returns:
str: string representation of the node
See also:
:py:func:`~matlab2cpp.qtree`
"""
nodes = flatten(no... | 9f6508496bd2ddeb23f9129707740364ce88e049 | 3,602,343 |
def is_printable(seq):
"""Returns true is seq consists solely of printable ASCII characters"""
printable, total = count_printable(seq)
return printable == total | 516ef8b906a88a9f6c8b8c539c64822fd8594aac | 3,602,344 |
def is_person(possible_person:dict):
"""Helper for getting party ID"""
return not possible_person.get('value',{}).get('entityRepresentation',{}).get('value',{}).get('personOtherIdentification') is None | 66a193cc491296fc94840c684a7066d5f1541e54 | 3,602,345 |
from sys import version
async def index(request: Request):
"""Root path"""
return templates.TemplateResponse(
"index.html", {"request": request, "title": title, "version": version}
) | d9905664962131d3b454d643f03b531c0e981de6 | 3,602,346 |
def scorer_cut_trie_v6(data, trie_offset=None):
"""
Cut scorer file from Mozilla DeepSpeech v0.7.x/v0.8.x into kenlm and trie sections.
"""
if trie_offset is None:
trie_offset = find_trie_v6_offset(data)
kenlm_data, trie_data = data[:trie_offset], data[trie_offset:]
return kenlm_data, tr... | dc65f71d2d9df6d1a13ea1a59fefdc2f76664ae7 | 3,602,347 |
import os
import json
def save_the_best_predictions(best_predictions, predictions_dict, year, model_name):
"""
Saves the best predictions-perplexities on prediction dict that holds all the predictions of the experiments
:param best_predictions: Dictionary that contains the best perplexities of (doc_id - p... | 4075a2b1f6be0bbf653791d5e9d3491506699357 | 3,602,348 |
from mne.forward._field_interpolation import _map_meg_channels
import matplotlib.pyplot as plt
import copy
def plot_reconstruction(evoked, origin=(0., 0., 0.04)):
"""Plot the reconstructed data for Evoked
Currently only works for MEG data.
Parameters
----------
evoked : instance of Evoked
... | cb5f21e63c8a1a49763dbf19a81f77eeb56c4dc6 | 3,602,349 |
def powmod(x, k, m):
""" fast exponentiation x^k % m """
if k < 0:
x = mulinv(x, m)
k = -k
p = 1
if k == 0:
return p
if k == 1:
return x
while k != 0:
if k % 2 == 1:
p = (p * x) % m
x = (x * x) % m
k //= 2
return p | 7ffc5b742ecc867ba4153410c7720141bf88cb9c | 3,602,350 |
def select_feature(x_train, x_test, y_train):
"""
This function reduces the number of features from the existing
g.t 10,000 to something manageable.
Based on experience with feature selection in homework 1, we do
not expect the selection to result in improved performance. But
we expect a reduction in run-time.
... | 9c27b96beeed0e71326be069a701104871b36fcf | 3,602,351 |
def failure() -> Parser:
"""Parser that always fails.
:return:
A new parser that always fails, consuming nothing.
"""
return Failure() | d05b991b1a7d94b9ffc9a1325ea9ab395a7e0dd9 | 3,602,352 |
def rxb_to_rgb(values, magic):
"""
Take values on some (arbitrarily-defined) color wheel and spit them out as
RGB values. The input values are assumed to be between 0 and 1. The final
RGB values are also been 0 and 1.
Magic defines the coordinate transformation. It should be an 8x3 matrix
(... | 44b1dd1b42dd1319954bd0809e503c8793aa5df2 | 3,602,353 |
import os
def get_nyiso_area(crs, nydir=get_full_filename("nyiso")):
"""
Load the NYISO map from the kml files and the geojson file into a geo dataframe.
:param pyproj.CRS crs: coordinate reference system
:param str nydir: NYISO map folder
:return: (*geopandas.GeoDataFrame*) -- NYISO geoDataFra... | e9400e35ae6bd6cf55b15e47e4ba0cf2ae340002 | 3,602,354 |
import functools
def minimize_main_file(test_runner, testcase_file_path, data):
"""Minimize the main test case file."""
if not can_minimize_file(testcase_file_path):
return data
get_random_file = functools.partial(get_temporary_file, testcase_file_path)
data = (
minimize_file(testcase_file_path, te... | 344dffb85ae3cbf7560ba140041650a519c3300d | 3,602,355 |
import sys
def python_lt(major, minor=None, micro=None):
"""Returns true if the python version is less than the given major.minor.patch version."""
if sys.version_info.major < major:
return True
elif sys.version_info.major == major:
if minor is not None:
if sys.version_info.min... | 24634c7565078a5fc4aa1f0e8f27ecb650e1dccb | 3,602,356 |
from typing import Callable
from typing import Any
from typing import Dict
import typing_extensions
from typing import Annotated
def args_to_matchers(
function: Callable[..., Any],
) -> Dict[str, libcst_typing.Matcher]:
"""Extract node matchers from the function arguments.
Untyped arguments will get a `D... | 2ee267f731e392ef4087242d4c71a5356f4b1117 | 3,602,357 |
def cells_number(rc):
"""
Calculates number of cells in each frame.
Intedend for use on 'cells' or subsets of 'cells' tables.
"""
return rc[['frame', 'cell_id']].groupby('frame').agg(len).reset_index().sort('frame')['cell_id'].values | 91725cc352de6a1aa31cf4f82301ed8de6e11bb4 | 3,602,358 |
def decode_qr(image):
"""
Returns dictionary with key, value pair
Parameters
----------
image: qrcode image
Return
------
dict: key value pair
"""
d = decode(Image.open(image))
data = d[0].data.decode('ascii')
data = data.replace(':', '').split()
dict = {da... | 338ea32c4001be683a0d6db5629b49a3e1737540 | 3,602,359 |
def to_cuda(data):
"""
Move an object to CUDA.
This function works recursively on lists and dicts, moving the values
inside to cuda.
Args:
data (list, tuple, dict, torch.Tensor, torch.nn.Module):
The data you'd like to move to the GPU. If there's a pytorch tensor or
... | 28186b60bd7509d3df76646fbf41babe1a4f76e4 | 3,602,360 |
def __update(self, condition, values):
"""
Returns an updated version of this column.
All entries for which the corresponding **condition** is True,
are updated using the corresponding entry in **values**.
Args:
condition (Boolean column): Condition according to which the update is done
... | 38ed8712249b1cd89c5d740f3b2a5f2e8fae04e6 | 3,602,361 |
import os
def find_package_dirs(root_path):
""" Find python package directories in directory `root_path`
Parameters
----------
root_path : str
Directory to search for package subdirectories
Returns
-------
package_sdirs : set
Set of strings where each is a subdirectory of... | e25c355c0d1938a560332085d5276df9d1ad9ec1 | 3,602,362 |
import os
def main(msa_a, msa_b, results_dir, gap_threshold=0.5, contact_mtx=None,
aa_table=globalvars.AA_TABLE):
"""
Convenience function to preprocess multiple sequence alignments
and write them to disk.
Arguments
---------
msa_a: TabularMSA object
msa_b: Tabula... | a1f5d0d49051bdb61decc9c4a1a2ec00772a1c66 | 3,602,363 |
import glob
def _ExtractBundleFile(target_dir, bundle_extension):
"""Extract single bundle file with given extension.
Args:
target_dir: string, the direcotry to be fetched bundle file.
bundle_extension: string, the extension of the extracted bundle.
Returns:
string, the path of extracted bundle wh... | 703e3a0d415d1b3578853351241dbe3abcb99cb2 | 3,602,364 |
import random
def vc_crop(image_array: np.ndarray):
# Function to crop an image.
# Pad image by n_pixels on each size, then take random crop of same original size.
"""
image_array: The image to apply transformation on.
"""
n_pixels = 40
pad_mode = random.choice(
[
"... | 3caddb644d69b19f3f9f2c565710266123b0f639 | 3,602,365 |
def get_best_synset_pair(word_1, word_2):
"""
Choose the pair with highest path similarity among all pairs.
Mimics pattern-seeking behavior of humans.
"""
max_sim = -1.0
synsets_1 = wn.synsets(word_1)
synsets_2 = wn.synsets(word_2)
if len(synsets_1) == 0 or len(synsets_2) == 0:
r... | 7568eba4c8e9216569c364257bd5ff352aefdc56 | 3,602,366 |
def all_keys_are_have_numbers(d) -> bool:
"""`has_common_prefix() catches most instances of this, but sometimes hash tables have sets of keys like:
{'00', '01', '02', ...}. This function identifies those"""
for k in d.keys():
m = _td_re.search(k)
if not m:
# This key does not end... | 538bb401510db5602b3ff8440b310538d9582422 | 3,602,367 |
import logging
import time
def CreateTarball(target, cwd, sudo=False, compression=COMP_XZ, chroot=None,
inputs=None, timeout=300, extra_args=None, **kwargs):
"""Create a tarball. Executes 'tar' on the commandline.
Args:
target: The path of the tar file to generate.
cwd: The directory t... | 6985ca093cd33c9d7320c460bc90d3c97601b68b | 3,602,368 |
def get_dependency_graph_of(symbol, call_graph):
"""Return a sub-graph of the call graph with symbol as the root element.
"""
dependees = get_dependees(symbol, call_graph)
dependees.add(symbol) # Also include the symbol itself
return {sym : call_graph[sym] for sym in dependees} | cb1d28664867bc7badf5a3b1a1de6b01ceebfa3e | 3,602,369 |
def cpuid(apicid, eax, ecx=0):
"""Run CPUID on the specified CPU. Return a namedtuple containing eax, ebx, ecx, and edx."""
return cpuid_result(*_smp._cpuid(apicid, eax, ecx)) | 06e2bc0fadf7fbee494a9eb1f5e1b67d5df9cc58 | 3,602,370 |
def generate_items(data):
"""Generates a dictionary of Item objects
With the key being the item name.
"""
item_flat_dict = defaultdict(list)
item_dict = defaultdict(Item)
for enchantment in data:
for item in data[enchantment].items:
item_flat_dict[item].append(data[... | dae0be5e429ca04822d29e12d70bc16131e74191 | 3,602,371 |
import numpy
def coordinates(n):
"""
Generate a 1D array with length n,
which spans [-0.5,0.5] with 0 at position n/2.
See also docs for numpy.mgrid.
:param n: length of array to be generated
:return: 1D numpy array
"""
n2 = n // 2
if n % 2 == 0:
return numpy.mgrid[-n2:n2]... | 1371601f991432f1bad0a82fb741f050d9346d4e | 3,602,372 |
import fractions
import decimal
def ensure_expr(value_or_expression: ValueOrExpression) -> Expression:
"""
Takes a Python value or expression and returns an expression.
Implicitly converts floats, integers, and booleans to constant expressions.
Raises :class:`~momba.model.expressions.ConversionError... | e5175985c1e57087883c9d2432762f6e89b03649 | 3,602,373 |
def max_wkend_patterns_init(M):
"""
Compute maximum number of weekend worked patterns
:param M:
:return:
"""
max_patterns = 2 ** (2 * M.n_weeks.value)
return max_patterns | bc3cc554c858d80bbe5f33c3deaf87465ddfe657 | 3,602,374 |
def load_fol(s):
"""
Temporarily duplicated from ``nltk.sem.util``.
Convert a file of first order formulas into a list of ``Expression`` objects.
:param s: the contents of the file
:type s: str
:return: a list of parsed formulas.
:rtype: list(Expression)
"""
statements = []
for... | 89da1c9bae084cc69d3dbcec78d19d6571be2c8e | 3,602,375 |
import os
def upload_file(file_object, bucket, object_name):
"""Upload a file to an S3 bucket
Args:
- file_object: File to upload
- bucket: Bucket to upload to
- object_name: S3 object name. If not specified then file_name is used
Returns:
- True if file was uploaded, else... | 8363321a2e5f08c9e99b7583612a99d9bf26f06f | 3,602,376 |
def convert_to_quint8(arr, q):
"""
Quantize a float NumPy ndarray into a quint8 one with specified params.
:param arr: Input ndarray.
:type arr: :class:`np.ndarray`
:param q: Target data type, should be a quint8.
:type q: :class:`np.dtype`
"""
assert isinstance(arr, np.ndarray)
asse... | a7079c5fd7a5a24fbc368ad237f27be1e18577bd | 3,602,377 |
import tqdm
def build_windowed_nn_graph(
recording,
peaks,
time_window_s=60 * 5,
margin_ms=100,
ms_before=1,
ms_after=1,
n_channel_neighbors=8,
n_neighbors=5,
knn_verbose=True,
low_memory=False,
n_jobs=-1,
suppress_tqdm=False,
):
"""_summary_
Args:
reco... | 1da6386422066bafbe34af270fbf8047cf054369 | 3,602,378 |
from typing import List
from typing import IO
import warnings
def get_from_files(fhs: List[IO[str]]) -> List[Package]:
"""
Read packages from a list of file handles.
The version specifier(s) for a package can be written in a number of
ways:
pkg
pkg == 0.1
pkg > 1, <= 3
... | 0012fa19d082952cb17bac956783ec61882c9c9d | 3,602,379 |
def load(textfile, vocab, max_value, max_utterance):
""" Load a dialog text corpus as word Id sequences
Args:
textfile (str): filename of a dialog corpus
vocab (dict): word-id mapping
Return:
list of dialogue : dialogue is (input_id_list,output_id_list)
"""
... | 3c43ce1b6f8c4153d9a4e4bf30d00926ca63cb9b | 3,602,380 |
def main(system, logger):
"""
Returns the IP address of the current Redis Master
"""
sentinel = Sentinel(
[(config.SENTINEL_IP, config.PORT)], socket_timeout=0.1)
master = sentinel.discover_master(config.REDIS_MASTER)
if master[0] == config.REDIS_MASTER_IP:
return 1
else:
... | 388523eb7b3a011f4f23eb03e9b6b73b705bdc51 | 3,602,381 |
def __bond_type_to_sdf(bond):
"""Get bond type in sdf language. Based on:
http://www.nonlinear.com/progenesis/sdf-studio/v0.9/faq/sdf-file-format-guidance.aspx
Args:
bond_type (rdkit.Chem.rdchem.Bond): Bond to be processed
Returns:
str: String representation of the bond type.
"""
... | 7714006c36fd0fd8514a8ba6051bd13637da5484 | 3,602,382 |
import ipaddress
def get_id_addr_port(peer_len):
"""Ask the user for peer, IP address and port to modify as gateway
"""
to_modify = input("Enter 'id' (number) of the REMOTE lightning channel to proxy "
"(any other key to skip): ")
try:
if int(to_modify) <= peer_len:
... | 31ec3aadd11b917d095b063d2075044968db98fd | 3,602,383 |
def filter_files_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False) -> OsWalk:
"""
Filters a walk's file collection using the given predicate.
If a predicate was not provided, the original walk is returned.
:param walk: The walk 'object' to filter
:param predicate: The co... | b131ba292b24cc6d276d080b703ad2cf2c972cec | 3,602,384 |
def cross_check_sanity(flow0, ids0, ids1, corresp0, corresp1, occlusions0, row0, col0,
verbose=False, output_sanity_type=False):
"""
Cross checks that flow and correspondeces agree, or that the pixel is marked as occluded.
If we follow flow for a non-occluded pixel, then the new locat... | 746549f14c3c703c50e0bd89ef0fc8d5103821f1 | 3,602,385 |
def coo_todense(*args):
"""
coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, signed char Ax,
signed char Bx, int fortran)
coo_todense(int n_row, int n_col, int nnz, int Ai, int Aj, unsigned char Ax,
unsigned char Bx, int fortran)
coo_todense(int n_row, int n_col, int nnz, int A... | 470959f9fa6bfe2fb35d6e850acc8aa9e0d4e4e6 | 3,602,386 |
def make_saint_s(num_heads, embed_dim, num_layers, d_ff, dropout, dropout_ff=0.1):
"""
Make the Saint-t model by stacking mutlihead attention
and feed forward into the encoder layer
-----------
Paramaters
-----------
num_heads: (int) number of attention heads
embed_dim: (int) size of... | 71640289ed5185d6dd95f6d14302498127161932 | 3,602,387 |
def lnlstm(input_tensor, mask_tensor, cell_state, scope, n_hidden, init_scale=1.0):
"""
Creates a LSTM with Layer Normalization (lnlstm) cell for TensorFlow
:param input_tensor: (TensorFlow Tensor) The input tensor for the LSTM cell
:param mask_tensor: (TensorFlow Tensor) The mask tensor for the LSTM c... | 50f77df8a19518beac5bad015e59254e6a926bf4 | 3,602,388 |
def _get_dump(cls):
"""Internal ABC helper for cache and registry debugging
Return shallow copies of registry, of both caches, and
negative cache version. Don't call this function directly,
instead use ABC._dump_registry() for a nice repr."""
return (cls._abc_registry.data,
cls._abc_cac... | 3f21d6527b2ee009d369970bbbac1691ab997f87 | 3,602,389 |
def ReadFemPreg(dct_file='2002FemPreg.dct',
dat_file='2002FemPreg.dat.gz'):
"""Reads the NSFG pregnancy data.
dct_file: string file name
dat_file: string file name
returns: DataFrame
"""
dct = thinkstats2.ReadStataDct(dct_file)
preg = dct.ReadFixedWidth(dat_file, compressio... | 73ef50c677925ba9ef29fd11367873f7b4d5541e | 3,602,390 |
def _download(dest_file, file_id):
"""
returns a function that downloads file from Google Drive
Parameters
------
dest_file : pathlib Path
destination to save the file
file_id : str
file_id for Google Drive file
"""
def download():
gdd.download_file_from_google_... | 6bf21009c83e51e8a6c0c7c94a08a0294f2d52c1 | 3,602,391 |
def indent(s, shift=1, width=4):
"""Indent a block of text. The indentation is applied to each line."""
indented = '\n'.join(' ' * (width * shift) + l if l else ''
for l in s.splitlines())
if s[-1] == '\n':
indented += '\n'
return indented | 34ab969f133429959463903fe7e86e18ee644f20 | 3,602,392 |
import functools
def mutating_storage_method(f):
"""Wrap a method and fail if the instance is readonly."""
@functools.wraps(f)
async def inner(self, *args, **kwargs):
if self.read_only:
raise exceptions.ReadOnlyError("This storage is read-only.")
return await f(self, *args, **... | 451c867fd970b9916e258a7076d8d21275992063 | 3,602,393 |
def parse(tokenQueue):
"""
This function creates the abstract syntax tree by calling the story function.
If the story is parsed successfully, then ast evaluates to True and the ast
is returned. Otherwise, parse returns False.
"""
ast = story(tokenQueue)
if ast != False:
print("Parsing complete")
return ast
... | 4b8947c253c99cff5ffa6beb1682fd6c030e5156 | 3,602,394 |
def graph_append_discounted_rewards(destination, rewards, discount_rate):
"""Discounts episode rewards and appends them to destination."""
ag.set_element_type(rewards, tf.float32)
cdr = 0.0
reverse_discounted = []
ag.set_element_type(reverse_discounted, tf.float32)
for i in range(len(rewards) - 1, -1, -1)... | 52618523a71d3578d60f223bcfd624ca6c04bfdd | 3,602,395 |
def issue_pending_alpha(repo):
"""Create "Alpha Release [pending]" issue
This should be created after the current alpha completes.
"""
r, a = _alpha_pending(repo, assert_exists=False)
if a:
return '#{a.number} {a.title} already exists'
i = r.create_issue(title=_release_title('Alpha', pe... | 80ee19c4060379e781a2ed366c7bbdab1d1bb336 | 3,602,396 |
from typing import Literal
from typing import List
from typing import Tuple
def get_letter_index_pairs(key: str, lang: Literal["EN", "TR"]) -> List[ Tuple[str, str] ]:
"""
Returns a list of tuples where the first element in each tuple is a letter from the given key
and the second element is the position o... | 72e6480b72dac92daaf9c3f0c9134e355bdec533 | 3,602,397 |
from typing import Optional
def get_clusters(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetClustersResult:
"""
Retrieve EKS Clusters list
"""
__args__ = dict()
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_ve... | 7dcf91824e28c6992fbfe5f3c2579d3ba32d8819 | 3,602,398 |
def fembed(link: str) -> str:
""" Fembed direct link generator
Based on https://github.com/zevtyardt/lk21
"""
dl_url= Bypass().bypass_fembed(link)
count = len(dl_url)
lst_link = [dl_url[i] for i in dl_url]
return lst_link[count-1] | 4b3c43fe0e6e55f9dd7f0ffe35b89b9cf504390e | 3,602,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.