content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def train_save_tfidf(filein, target):
"""input is a bow corpus saved as a tfidf file. The output is
a saved tfidf corpus"""
try:
corpus = corpora.MmCorpus(filein)
except:
raise NameError('HRMMPH. The file does not seem to exist. Create a file'+
'first by runni... | e4d41443d27f8b55f9fd6ba4b8c13a42d381a980 | 16,749 |
def ScrewTrajectoryList(Xstart, Xend, Tf, N, method, gripper_state, traj_list):
""" Modified from the modern_robotics library ScrewTrajectory
Computes a trajectory as a list of SE(3) matrices with a gripper value and
converts into a list of lists
Args:
Xstart : The initial end-effector con... | 146f4f7b96207c74bbe0ed08e162c3ba656d7a43 | 16,750 |
def calculate_phase(time, period):
"""Calculates phase based on period.
Parameters
----------
time : type
Description of parameter `time`.
period : type
Description of parameter `period`.
Returns
-------
list
Orbital phase of the object orbiting the star.
"... | a537810a7705b5d8b0144318469b249f64a01456 | 16,751 |
def perspective_transform(img):
"""
Do a perspective transform over an image.
Points are hardcoded and depend on the camera and it's positioning
:param img:
:return:
"""
pts1 = np.float32([[250, 686], [1040, 680], [740, 490], [523, 492]])
pts2 = np.float32([[295, 724], [980, 724], [988, ... | 51411c1fc73e897a657e2e89c44275796b16a1b6 | 16,753 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username"... | ffa2152cffdbfd161f3e8aa23aefa3c49993e630 | 16,754 |
def value_iteration(P, nS, nA, gamma=0.9, tol=1e-3):
"""
Learn value function and policy by using value iteration method for a given
gamma and environment.
Parameters:
----------
P, nS, nA, gamma:
defined at beginning of file
tol: float
Terminate value iteration when
max |value(s) - prev_value(s)| < tol
... | 7362b95cd453f0983e6b82acf73d0350eae2734c | 16,755 |
def get_clients():
"""
Determine if the current user has a connected client.
"""
return jsonify(g.user.user_id in clients) | 602d77b25b6608db24fca66d5bc55bc83a0530e8 | 16,756 |
def get_split_indices(word, curr_tokens, include_joiner_token, joiner):
"""Gets indices for valid substrings of word, for iterations > 0.
For iterations > 0, rather than considering every possible substring, we only
want to consider starting points corresponding to the start of wordpieces in
the curren... | 495d924716cfd0e14430d225e50b313fea305dbb | 16,757 |
def perspective(
vlist: list[list[Number,
Number,
Number]],
rotvec: list[list[float, float],
list[float, float],
list[float, float]],
dispvec: list[Number,
Number,
... | daece49851ecca55ba30d4f6f82fe59d5deb5497 | 16,758 |
def actor_is_contact(api_user, nick, potential_contact):
"""Determine if one is a contact.
PARAMETERS:
potential_contact - stalkee.
RETURNS: boolean
"""
nick = clean.user(nick)
potential_contact = clean.user(potential_contact)
key_name = Relation.key_from(relation='contact',
... | 93a3bfd0a52b2acb043c162428f0fa45754702bf | 16,760 |
def compute_mem(w, n_ring=1, spectrum='nonzero', tol=1e-10):
"""Compute Moran eigenvectors map.
Parameters
----------
w : BSPolyData, ndarray or sparse matrix, shape = (n_vertices, n_vertices)
Spatial weight matrix or surface. If surface, the weight matrix is
built based on the inverse ... | fe622d75816629aaf5fce34405eb7a3021393d7d | 16,761 |
def eval_BenchmarkModel(x, a, y, model, loss):
"""
Given a dataset (x, a, y) along with predictions,
loss function name
evaluate the following:
- average loss on the dataset
- DP disp
"""
pred = model(x) # apply model to get predictions
n = len(y)
if loss == "square":
er... | cdb4e82004d94c7b25a705d33f716ac3d81e38de | 16,762 |
def parse_sgf_game(s):
"""Read a single SGF game from a string, returning the parse tree.
s -- 8-bit string
Returns a Coarse_game_tree.
Applies the rules for FF[4].
Raises ValueError if can't parse the string.
If a property appears more than once in a node (which is not permitted by
the... | 4315277a91f732f92c3001cf570221ab6aa657a7 | 16,763 |
import re
def retrieve(
framework,
region,
version=None,
py_version=None,
instance_type=None,
accelerator_type=None,
image_scope=None,
container_version=None,
distribution=None,
base_framework_version=None,
):
"""Retrieves the ECR URI for the Docker image matching the given... | eeee1aec620de5b29650b9605c7fb2b13aed76e5 | 16,764 |
def deconstruct_DMC(G, alpha, beta):
"""Deconstruct a DMC graph over a single step."""
# reverse complementation
if G.has_edge(alpha, beta):
G.remove_edge(alpha, beta)
w = 1
else:
w = 0
# reverse mutation
alpha_neighbors = set(G.neighbors(alpha))
beta_neighbors = set... | fa32a325fd49435e3191a20b908ac0e9c3b992f8 | 16,765 |
def new_followers_view(request):
"""
View to show new followers.
:param request:
:return:
"""
current_author = request.user.user
followers_new = FollowRequest.objects.all().filter(friend=current_author).filter(acknowledged=False)
for follow in followers_new:
follow.acknowledged... | 88277967b8185c47b9bb955dabf6fcd79ea3a530 | 16,766 |
def inv(a, p):
"""Inverse of a in :math:`{mathbb Z}_p`
:param a,p: non-negative integers
:complexity: O(log a + log p)
"""
return bezout(a, p)[0] % p | d2caab3a564d5f58d1be345900382e762350a2ea | 16,767 |
def metadata_columns(request, metadata_column_headers):
"""Make a metadata column header and column value dictionary."""
template = 'val{}'
columns = {}
for header in metadata_column_headers:
columns[header] = []
for i in range(0, request.param):
columns[header].append(templa... | ca1f89935260e9d55d57df5fe5fbb0946b5948ac | 16,769 |
def all_done_tasks_for_person(person, client=default):
"""
Returns:
list: Tasks that are done for given person (only for open projects).
"""
person = normalize_model_parameter(person)
return raw.fetch_all("persons/%s/done-tasks" % person["id"], client=client) | 68883d7ac9c1e0cd009ff02ae4944782ae6fc637 | 16,770 |
def transform_cfg_to_wcnf(cfg: CFG) -> CFG:
"""
Transform given cfg into Weakened Normal Chomsky Form (WNCF)
Parameters
----------
cfg: CFG
CFG object to transform to WNCF
Returns
-------
wncf: CFG
CFG in Weakened Normal Chomsky Form (WNCF)
"""
wncf = (
c... | 55d72634b02feab7150d290619b40fc2976ffae3 | 16,771 |
def insert_scope_name(urls):
"""
given a tuple of URLs for webpy with '%s' as a placeholder for
SCOPE_NAME_REGEXP, return a finalised tuple of URLs that will work for all
SCOPE_NAME_REGEXPs in all schemas
"""
regexps = get_scope_name_regexps()
result = []
for i in range(0, len(urls), 2)... | 28cda0956f232adf176666c776b39463caca9847 | 16,773 |
def fit_cochrane_orcutt(ts, regressors, maxIter=10, sc=None):
"""
Fit linear regression model with AR(1) errors , for references on Cochrane Orcutt model:
See [[https://onlinecourses.science.psu.edu/stat501/node/357]]
See : Applied Linear Statistical Models - Fifth Edition - Michael H. Kutner , page 492... | 958ca88e6ac37ebd58c7f1ff88c191d801e4cb87 | 16,774 |
def get_nodeweight(obj):
"""
utility function that returns a
node class and it's weight
can be used for statistics
to get some stats when NO Advanced Nodes are available
"""
k = obj.__class__.__name__
if k in ('Text',):
return k, len(obj.caption)
elif k == 'ImageLink' and obj... | 1ab88f73621c8396fca08551dd14c9a757d019ad | 16,775 |
def CMYtoRGB(C, M, Y):
""" convert CMY to RGB color
:param C: C value (0;1)
:param M: M value (0;1)
:param Y: Y value (0;1)
:return: RGB tuple (0;255) """
RGB = [(1.0 - i) * 255.0 for i in (C, M, Y)]
return tuple(RGB) | cfc2c7b91dd7f1faf93351e28ffdd9906613471a | 16,776 |
def update_local_artella_root():
"""
Updates the environment variable that stores the Artella Local Path
NOTE: This is done by Artella plugin when is loaded, so we should not do it manually again
"""
metadata = get_metadata()
if metadata:
metadata.update_local_root()
return True... | 23fb9f0eb47aec566dc6b9862474535545b963dc | 16,777 |
def app_tests(enable_migrations, tags, verbosity):
"""Gets the TestRunner and runs the tests"""
# prepare the actual test environment
setup(enable_migrations, verbosity)
# reuse Django's DiscoverRunner
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.runner.Disc... | c56ca20ea98dadf97f39a30e2f07c0eb3952b418 | 16,778 |
def quicksort(numbers, low, high):
"""Python implementation of quicksort."""
if low < high:
pivot = _partition(numbers, low, high)
quicksort(numbers, low, pivot)
quicksort(numbers, pivot + 1, high)
return numbers | 064aa30f032036aa73f08b2b94ce4556ffc565fd | 16,779 |
import scipy
def bsput_delta(k, t, *, x0=1., r=0., q=0., sigma=1.):
"""
bsput_delta(k, t, *, x0=1., r=0., q=0., sigma=1.)
Black-Scholes put option delta.
See Also
--------
bscall
"""
r, q = np.asarray(r), np.asarray(q)
d1, d2 = bsd1d2(k, t, x0=x0, r=r, q=q, sigma=sigma)
retur... | d6e1e3e6c2f97fa856b156170ac49ea3d5530423 | 16,780 |
from typing import Sequence
import re
def regex_filter(patterns: Sequence[Regex], negate: bool = False, **kwargs) -> SigMapper:
"""Filter out the signals that do not match regex patterns (or do match if negate=True)."""
patterns = list(map(re.compile, patterns))
def filt(sigs):
def map_sig(sig):
... | 4c76d4bd5f76d5d35373ec14c910291b155cd4db | 16,781 |
def cpncc(img, vertices_lst, tri):
"""cython version for PNCC render: original paper"""
h, w = img.shape[:2]
c = 3
pnccs_img = np.zeros((h, w, c))
for i in range(len(vertices_lst)):
vertices = vertices_lst[i]
pncc_img = crender_colors(vertices, tri, pncc_code, h, w, c)
pnccs... | 8c7e380b56e26197cfb6b9b65c8d373ada0be4b1 | 16,782 |
import time
def run_net(X, y, batch_size, dnn, data_layer_name, label_layer_name,
loss_layer, accuracy_layer, accuracy_sink, is_train):
"""Runs dnn on given data"""
start = time.time()
total_loss = 0.
run_iter = dnn.learn if is_train else dnn.run
math_engine = dnn.math_engine
accur... | 43121dff269df6a03763f130e8f75f0ce6984a57 | 16,783 |
from typing import Any
import json
def json_safe(arg: Any):
"""
Checks whether arg can be json serialized and if so just returns arg as is
otherwise returns none
"""
try:
json.dumps(arg)
return arg
except:
return None | 97ac87464fb4b31b4fcfc7896252d23a10e57b72 | 16,784 |
def _key_iv_check(key_iv):
"""
密钥或初始化向量检测
"""
# 密钥
if key_iv is None or not isinstance(key_iv, string_types):
raise TypeError('Parameter key or iv:{} not a basestring'.format(key_iv))
if isinstance(key_iv, text_type):
key_iv = key_iv.encode(encoding=E_FMT)
if len(key_iv) > ... | 809ff811a433f9843b330a56be926411871d8b7a | 16,785 |
def decomposeArbitraryLength(number):
"""
Returns decomposition for the numbers
Examples
--------
number 42 : 32 + 8 + 2
powers : 5, 3, 1
"""
if number < 1:
raise WaveletException("Number should be greater than 1")
tempArray = list()
current = number
position = 0
... | 5645c9024dd93aa3bfaf904d7a69f4d46977fb5a | 16,786 |
def ax_draw_macd2(axes, ref, kdata, n1=12, n2=26, n3=9):
"""绘制MACD
:param axes: 指定的坐标轴
:param KData kdata: KData
:param int n1: 指标 MACD 的参数1
:param int n2: 指标 MACD 的参数2
:param int n3: 指标 MACD 的参数3
"""
macd = MACD(CLOSE(kdata), n1, n2, n3)
bmacd, fmacd, smacd = macd.getResult(0),... | 3bcb73756211a8906f3bf601207092177aa45ade | 16,787 |
import scipy
def scipy_bfgs(
criterion_and_derivative,
x,
*,
convergence_absolute_gradient_tolerance=CONVERGENCE_ABSOLUTE_GRADIENT_TOLERANCE,
stopping_max_iterations=STOPPING_MAX_ITERATIONS,
norm=np.inf,
):
"""Minimize a scalar function of one or more variables using the BFGS algorithm.
... | e1d61454e7ea782d37b4ab222599c69b2c89df1b | 16,788 |
from random import shuffle
import six
def assign_to_coders_backend(sample,
limit_to_unassigned,
shuffle_pieces_before_assigning,
assign_each_piece_n_times,
max_assignments_per_piece,
coders, max_pieces_per_coder,
creation_time, creator):
"""Assignment to coders curr... | ffe59dce1b85f7b77e652a1823f298b643d104c7 | 16,789 |
def mask_rcnn_heads_add_mask_rcnn_losses(model, blob_mask):
"""Add Mask R-CNN specific losses."""
loss_mask = model.net.SigmoidCrossEntropyLoss(
[blob_mask, 'masks_int32'],
'loss_mask',
scale=model.GetLossScale() * cfg.MRCNN.WEIGHT_LOSS_MASK
)
loss_gradients = blob_utils_get_loss... | 1f94662948d2576874ca4bb13a602e0a0482d787 | 16,790 |
def parse_ns_headers(ns_headers):
"""Ad-hoc parser for Netscape protocol cookie-attributes.
The old Netscape cookie format for Set-Cookie can for instance contain
an unquoted "," in the expires field, so we have to use this ad-hoc
parser instead of split_header_words.
XXX This may not make the bes... | 91d1006d6495b1ad86ff65abbc1575d9c759f183 | 16,791 |
def same_kind_right_null(a: DataType, _: Null) -> bool:
"""Return whether `a` is nullable."""
return a.nullable | 005e9d62702d8f9c6d1e1a4911c7dedf7d81bb73 | 16,792 |
def unary_col(op, v):
"""
interpretor for executing unary operator expressions on columnars
"""
if op == "+":
return v
if op == "-":
return compute.subtract(0.0, v)
if op.lower() == "not":
return compute.invert(v)
raise Exception("unary op not implemented") | ff4eec1f333cd0425cb1b7c533ec4dc94179512e | 16,793 |
def test_start_sep_graph() -> nx.Graph:
"""test graph with known clique partition that needs start_separate"""
G = nx.Graph()
G.add_nodes_from(range(6))
G.add_edges_from([(0, 1, {'weight': 1.0}), (0, 2, {'weight': -10}), (0, 3, {'weight': 1}), (0, 4, {'weight': -10}), (0, 5, {'weight': -10}),
... | 84bd5a140ff7c8882513395a305f69d64d1830a7 | 16,794 |
def structure(table_toplevels):
"""
Accepts an ordered sequence of TopLevel instances and returns a navigable object structure representation of the
TOML file.
"""
table_toplevels = tuple(table_toplevels)
obj = NamedDict()
last_array_of_tables = None # The Name of the last array-of... | c34590f604d52ff4bfcf3cf1bae1fc41a7a1f3ec | 16,795 |
import math
def h(q):
"""Binary entropy func"""
if q in {0, 1}:
return 0
return (q * math.log(1 / q, 2)) + ((1 - q) * math.log(1 / (1 - q), 2)) | ad3d02d6e7ddf622c16ec8df54752ac5c77f8972 | 16,796 |
def has_next_page(page_info: dict) -> bool:
"""
Extracts value from a dict with hasNextPage key, raises an error if the key is not available
:param page_info: pagination info
:return: a bool indicating if response hase a next page
"""
has_next_page = page_info.get('hasNextPage')
if has_next... | 13c7bf0096127e054adaa8a331d2168bfb76c1d3 | 16,797 |
def _stuw_code(current_name=None):
""""
Zoekt door TYPESTUW naar de naam van het stuwtype, geeft attribuut waarde uit DAMO
"""
if current_name not in TYPESTUW.values():
return 99
for i, name in TYPESTUW.items():
if name == current_name:
return i | f0444885fd9956bdb150442dc1de7de09a0ac693 | 16,798 |
def _build_init_nodes(context, device):
"""
Build initial inputs for beam search algo
"""
decoder_input = _prepare_init_inputs(context, device)
root_node = BeamSearchNode(None, None, decoder_input, 0, len(context))
return [root_node] | 009cf7b09f39eb5c9722015d310ecab0b32f7c59 | 16,799 |
import typing
def compute_accuracy(data):
"""Return [wpm, accuracy]."""
prompted_text = data["promptedText"][0]
typed_text = data.get("typedText", [""])[0]
start_time = float(data["startTime"][0])
end_time = float(data["endTime"][0])
return [typing.wpm(typed_text, end_time - start_time),
... | c10b5d681392c71967b86f12d33be3edc1361446 | 16,802 |
from typing import IO
def write_file(filename: str, content: str, mode: str = "w") -> IO:
"""Save content to a file, overwriting it by default."""
with open(filename, mode) as file:
file.write(content)
return file | 5d6b7ac1f9097d00ae2b67e3d34f1135c4e90946 | 16,803 |
def get_minimum_integer_attribute_value(node, attribute_name):
"""
Returns the minimum value that a specific integer attribute has set
:param node: str
:param attribute_name: str
:return: float
"""
return maya.cmds.attributeQuery(attribute_name, min=True, node=node)[0] | ce36c252478e9cb5d5e5ade3e2d70716d206748a | 16,804 |
import numpy as np
import yt
import string
def get_star_locs(plotfile):
"""Given a plotfile, return the location of the primary and the secondary."""
ds = yt.load(plotfile)
# Get a numpy array corresponding to the density.
problo = ds.domain_left_edge.v
probhi = ds.domain_right_edge.v
dim ... | 429758abd92d4eff7a1948278bbe8c348ba83862 | 16,805 |
def get_list(_list, persistent_attributes):
"""
Check if the user supplied a list and if its a custom list, also check for for any saved lists
:param _list: User supplied list
:param persistent_attributes: The persistent attribs from the app
:return: The list name , If list is custom or not
"""... | 497fa8427660bafa3cc3023abf0132973693dc6e | 16,806 |
import socket
import re
def inode_for_pid_sock(pid, addr, port):
"""
Given a pid that is inside a network namespace, and the address/port of a LISTEN socket,
find the inode of the socket regardless of which pid in the ns it's attached to.
"""
expected_laddr = '%02X%02X%02X%02X:%04X' % (addr[3], a... | 4d47d9de118caa87854b96bf759a75520b8409cb | 16,807 |
from typing import List
from typing import Tuple
import logging
def get_edges_from_route_matrix(route_matrix: Matrix) -> List[Tuple]:
"""Returns a list of the edges used in a route according to the route matrix
:param route_matrix: A matrix indicating which edges contain the optimal route
:type route_mat... | 32e84bc782cdf3939affa881f0c2cf23ff81eeee | 16,808 |
def nicer(string):
"""
>>> nicer("qjhvhtzxzqqjkmpb")
True
>>> nicer("xxyxx")
True
>>> nicer("uurcxstgmygtbstg")
False
>>> nicer("ieodomkazucvgmuy")
False
"""
pair = False
for i in range(0, len(string) - 3):
for j in range(i + 2, len(string) - 1):
if ... | 7c543bbd39730046b1ab3892727cca3a9e027662 | 16,809 |
from typing import Union
def multiple_choice(value: Union[list, str]):
""" Handle a single string or list of strings """
if isinstance(value, list):
# account for this odd [None] value for empty multi-select fields
if value == [None]:
return None
# we use string formatting ... | aae54f84bc1ccc29ad9ad7ae205e130f66601131 | 16,810 |
def Jnu_vD82(wav):
"""Estimate of ISRF at optical wavelengths by van Dishoeck & Black (1982)
see Fig 1 in Heays et al. (2017)
Parameters
----------
wav : array of float
wavelength in angstrom
Returns
-------
Jnu : array of float
Mean intensity Jnu in cgs units
... | 287dbf88d7a5ba58ca8792cd78ff61393df3aae2 | 16,811 |
def _coexp_ufunc(m0, exp0, m1, exp1):
""" Returns a co-exp couple of couples """
# Implementation for real
if (m0 in numba_float_types) and (m1 in numba_float_types):
def impl(m0, exp0, m1, exp1):
co_m0, co_m1 = m0, m1
d_exp = exp0 - exp1
if m0 == 0.:
... | 11df0f4c06edb758945b7a86940edd4975c47c85 | 16,812 |
def get_lorem(length=None, **kwargs):
""" Get a text (based on lorem ipsum.
:return str:
::
print get_lorem() # -> atque rerum et aut reiciendis...
"""
lorem = ' '.join(g.get_choices(LOREM_CHOICES))
if length:
lorem = lorem[:length]
return lorem | a3ece5c011d69e0a532bcb4b91fa6583dd028c1d | 16,813 |
import warnings
def try_get_graphql_scalar_type(property_name, property_type_id):
"""Return the matching GraphQLScalarType for the property type id or None if none exists."""
maybe_graphql_type = ORIENTDB_TO_GRAPHQL_SCALARS.get(property_type_id, None)
if not maybe_graphql_type:
warnings.warn(
... | 70c4406b9cd08b3de6e48a473e62869470f579b1 | 16,814 |
import requests
def get(path):
"""Get GCE metadata value."""
attribute_url = (
'http://{}/computeMetadata/v1/'.format(_METADATA_SERVER) + path)
headers = {'Metadata-Flavor': 'Google'}
operations_timeout = environment.get_value('URL_BLOCKING_OPERATIONS_TIMEOUT')
response = requests.get(
attribut... | 044db931369de13e6c16db9007fe4bad28a940a8 | 16,815 |
def greedy_helper(hyper_list, node_dict, fib_heap, total_weight, weight=None):
"""
Greedy peeling algorithm. Peel nodes iteratively based on their current degree.
Parameters
----------
G: undirected, graph (networkx)
node_dict: dict, node id as key, tuple (neighbor list, heap node) as value. He... | b2c0f3e91e6c9a80a8396dc104abc804af8875e5 | 16,816 |
def CleanFloat(number, locale = 'en'):
"""\
Return number without decimal points if .0, otherwise with .x)
"""
try:
if number % 1 == 0:
return str(int(number))
else:
return str(float(number))
except:
return number | 03ccc3bfe407becf047515b618621058acff37e7 | 16,817 |
def ssd_bboxes_encode(boxes):
"""
Labels anchors with ground truth inputs.
Args:
boxex: ground truth with shape [N, 5], for each row, it stores [y, x, h, w, cls].
Returns:
gt_loc: location ground truth with shape [num_anchors, 4].
gt_label: class ground truth with shape [num_an... | 1e0a07c1305fe2b1ba99f535609d2d52d72befa8 | 16,818 |
def _get_partial_prediction(input_data: dt.BatchedTrainTocopoData,
target_data_token_ids: dt.NDArrayIntBO,
target_data_is_target_copy: dt.NDArrayBoolBOV,
target_data_is_target_pointer: dt.NDArrayBoolBOV
) -> ... | 1a0fdc53e4e49bf3d0c0824eca6ba381d7a72f1f | 16,819 |
from tqdm import tqdm_notebook as tqdm
from tqdm import tqdm
from tqdm import tqdm as tqdm
def get_energy_spectrum_old(udata, x0=0, x1=None, y0=0, y1=None,
z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None,
window=None, correct_signal_loss=True, remove_undersampled_r... | aa29358215897f3bcb630d2c62b679d2b6ebef88 | 16,820 |
def createDefaultClasses(datasetTXT):
"""
:param datasetTXT: dict with text from txt files indexed by filename
:return: Dict with key:filename, value:list of lists with classes per sentence in the document
"""
classesDict = {}
for fileName in datasetTXT:
classesDict[fileName] = []
... | 8bec5768710a929c21f75fa70865e25f340409f6 | 16,821 |
def getGlobals():
"""
:return: (dict)
"""
return globals() | 0fa230d341ba5435b33c9e6a9d9f793f99a74238 | 16,822 |
from typing import Iterable
from typing import List
def split_text_to_words(words: Iterable[str]) -> List[Word]:
"""Transform split text into list of Word."""
return [Word(word, len(word)) for word in words] | 6317e794a5397da44be96216308573ae9d5a788f | 16,823 |
import khorosjx
def init_module_operation():
"""This function imports the primary modules for the package and returns ``True`` when successful."""
khorosjx.init_module('admin', 'content', 'groups', 'spaces', 'users')
return True | d6cbc3b94d4b4005d301d9b597bb7086e211bfa2 | 16,824 |
def connect_to_rds(aws, region):
"""
Return boto connection to the RDS in the specified environment's region.
"""
set_progress('Connecting to AWS RDS in region {0}.'.format(region))
wrapper = aws.get_api_wrapper()
client = wrapper.get_boto3_client(
'rds',
aws.serviceaccount,
... | cdfaa984c6795c7e03f0d8b3e3620f6de757fcbb | 16,825 |
def export_graphviz(DecisionTreeClassificationModel, featureNames=None, categoryNames=None, classNames=None,
filled=True, roundedCorners=True, roundLeaves=True):
"""
Generates a DOT string out of a Spark's fitted DecisionTreeClassificationModel, which
can be drawn with any library capable... | eb4484136fbbe92537a3f030375f6ac80081befd | 16,826 |
def _get_next_sequence_values(session, base_mapper, num_values):
"""Fetches the next `num_values` ids from the `id` sequence on the `base_mapper` table.
For example, if the next id in the `model_id_seq` sequence is 12, then
`_get_next_sequence_values(session, Model.__mapper__, 5)` will return [12, 13, 14, ... | 63ad9e5e55228dd873ee2c5d9080d223c89e1bc6 | 16,827 |
def overview(request):
"""
Dashboard: Process overview page.
"""
responses_dict = get_data_for_user(request.user)
responses_dict_by_step = get_step_responses(responses_dict)
# Add step status dictionary
step_status = get_step_completeness(responses_dict_by_step)
responses_dict_by_step['... | 4ac165cf5b4bf7de6f060d6649935f25fcf5a0a9 | 16,828 |
def _guess_os():
"""Try to guess the current OS"""
try:
abi_name = ida_typeinf.get_abi_name()
except:
abi_name = ida_nalt.get_abi_name()
if "OSX" == abi_name:
return "macos"
inf = ida_idaapi.get_inf_structure()
file_type = inf.filetype
if file_type in (ida_ida.f_ELF... | bb2cb2f0c294f2554ec419ee1bdea665abaf6957 | 16,829 |
def create_conf(name, address, *services):
"""Create an Apple TV configuration."""
atv = conf.AppleTV(name, address)
for service in services:
atv.add_service(service)
return atv | 0326a4c21b39ef12fe916f3a3fbee34af52c12a2 | 16,830 |
def log_transform(x):
""" Log transformation from total precipitation in mm/day"""
tp_max = 23.40308390557766
y = np.log(x*(np.e-1)/tp_max + 1)
return y | 61783d103db36ed668e494f557550caef611b84a | 16,831 |
from datetime import datetime
import requests
import json
def get_flight(arguments):
"""
connects to skypicker servive and get most optimal flight base on search criteria
:param arguments: inputs arguments from parse_arg
:return dict: flight
"""
api_url = 'https://api.skypicker.com/flights?v=3... | 690b7bd170b8b83f4b83f5c0ce98da919134107c | 16,832 |
def use_ip_alt(request):
"""
Fixture that gives back 2 instances of UseIpAddrWrapper
1) use ip4, dont use ip6
2) dont use ip4, use ip6
"""
use_ipv4, use_ipv6 = request.param
return UseIPAddrWrapper(use_ipv4, use_ipv6) | c33d74b6888124413d1430e4873140475db4748e | 16,833 |
import torch
def radius_gaussian(sq_r, sig, eps=1e-9):
"""Compute a radius gaussian (gaussian of distance)
Args:
sq_r: input radiuses [dn, ..., d1, d0]
sig: extents of gaussians [d1, d0] or [d0] or float
Returns:
gaussian of sq_r [dn, ..., d1, d0]
"""
return torch.exp(-sq... | cd5bb2bb85641b1200ce67cb7eb52bc1705cd0a1 | 16,834 |
from typing import List
from typing import Dict
from typing import Any
def index_papers_to_geodata(papers: List[Paper]) -> Dict[str, Any]:
"""
:param papers: list of Paper
:return: object
"""
geodata = {}
for paper in papers:
for file in paper.all_files():
for location in f... | f892d84e3dc8f239885b5c4110c931b088922bcc | 16,835 |
def _get_all_prefixed_mtds(
prefix: str,
groups: t.Tuple[str, ...],
update_groups_by: t.Optional[t.Union[t.FrozenSet[str],
t.Set[str]]] = None,
prefix_removal: bool = False,
custom_class_: t.Any = None,
) -> t.Dict[str, t.Tuple... | 2387fb3f2aa0416ad9837f6c1b4c27488d406fea | 16,836 |
from functools import reduce
def cartesian_product(arrays):
"""Create a cartesian product array from a list of arrays.
It is used to create x-y coordinates array from x and y arrays.
Stolen from stackoverflow
http://stackoverflow.com/a/11146645
"""
broadcastable = np.ix_(*arrays)
broadca... | 552b898a9187df637cc5f10b49e6a1fe004af95c | 16,838 |
def advanced_split(string, *symbols, contain=False, linked='right'):
"""
Split a string by symbols
If contain is True, the result will contain symbols
The choice of linked decides symbols link to which adjacent part of the result
"""
if not isinstance(string, str):
raise Exception('Strin... | 3e46fcc0c3fa6ab99b9d4d45cf950d9ad3f03ac1 | 16,839 |
def _get_resource_info(
resource_type="pod",
labels={},
json_path=".items[0].metadata.name",
errors_to_ignore=("array index out of bounds: index 0",),
verbose=False,
):
"""Runs 'kubectl get <resource_type>' command to retrieve info about this resource.
Args:
... | b9a98fe469eb7aa5fcfb606db0948cb53410ddec | 16,840 |
def rotate_line_about_point(line, point, degrees):
"""
added 161205
This takes a line and rotates it about a point a certain number of degrees.
For use with clustering veins.
:param line: tuple contain two pairs of x,y values
:param point: tuple of x, y
:param degrees: number of degrees t... | c5954604d6f7852e66fe7b19f53193271582619d | 16,841 |
def arith_relop(a, t, b):
"""
arith_relop(a, t, b)
This is (arguably) a hack.
Represents each function as an integer 0..5.
"""
return [(t == 0).implies(a < b),
(t == 1).implies(a <= b),
(t == 2).implies(a == b),
(t == 3).implies(a >= b),
(t == 4).implies(a > b),
... | 8b06d545e8d651803683b36facafb647f38fb2ff | 16,842 |
import logging
def initialise_framework(options):
"""This function initializes the entire framework
:param options: Additional arguments for the component initializer
:type options: `dict`
:return: True if all commands do not fail
:rtype: `bool`
"""
logging.info("Loading framework please ... | e62b34189e330fdaea7ec6c81084616bd015a587 | 16,843 |
def get_registration_form() -> ConvertedDocument:
"""
Вернуть параметры формы для регистрации
:return: Данные формы профиля + Логин и пароль
"""
form = [
gen_field_row('Логин', 'login', 'text', validate_rule='string'),
gen_field_row('Пароль', 'password', 'password'),
... | 76bcab98d840523e94234c456cb1ccbd2b1f9129 | 16,844 |
def get_docker_stats(dut):
"""
Get docker ps
:param dut:
:return:
"""
command = 'docker stats -a --no-stream'
output = st.show(dut, command)
return output | cd994701c622ce9ea1f6f123f24b9913aa02698d | 16,845 |
def enthalpyvap(temp=None,pres=None,dvap=None,chkvals=False,
chktol=_CHKTOL,temp0=None,pres0=None,dvap0=None,chkbnd=False,
mathargs=None):
"""Calculate ice-vapour vapour enthalpy.
Calculate the specific enthalpy of water vapour for ice and water
vapour in equilibrium.
:arg temp: Temper... | dadc59bf28272de3a298b89cb13901825fd58c95 | 16,848 |
async def get_eng_hw(module: tuple[str, ...], task: str) -> Message:
"""
Стандартный запрос для английского
"""
return await _get_eng_content('zadanie-{}-m-{}-z'.format(*module), task) | 15e5425173c643074dde08c6753ffcd333414565 | 16,849 |
import json
def get_image_blobs(pb):
""" Get an image from the sensor connected to the MicroPython board,
find blobs and return the image, a list of blobs, and the time it
took to find the blobs (in [ms])
"""
raw = json.loads(run_on_board(pb, script_get_image, no_print=True))
img = np.flip(np.tran... | 5d563aeb490c5c1d509e442a3f7210bcfd9d6779 | 16,851 |
def classification_report(y_true, y_pred, digits=2, suffix=False):
"""Build a text report showing the main classification metrics.
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a classifier.
digits : int. Number of dig... | 6158c82879b2894c96479bb96f986e348ef02b00 | 16,852 |
def tidy_conifer(ddf: DataFrame) -> DataFrame:
"""Tidy up the raw conifer output."""
result = ddf.drop(columns=["marker", "identifier", "read_lengths", "kraken"])
result[["name", "taxonomy_id"]] = result["taxa"].str.extract(
r"^(?P<name>[\w ]+) \(taxid (?P<taxonomy_id>\d+)\)$", expand=True
)
... | 88e55855d5f9ca8859a0e058a593aadd44774387 | 16,853 |
import collections
def get_duplicates(lst):
"""Return a list of the duplicate items in the input list."""
return [item for item, count in collections.Counter(lst).items() if count > 1] | 8f10226c904f95efbee447b4da5dc5764b18f6d2 | 16,855 |
def relu(x, alpha=0):
"""
Rectified Linear Unit.
If alpha is between 0 and 1, the function performs leaky relu.
alpha values are commonly between 0.1 and 0.3 for leaky relu.
Parameters
----------
x : numpy array
Values to be activated.
alpha : float, optional
Th... | f18b331ef66d14a29e1ad5f14b610af583ea7b3a | 16,856 |
def build_unique_dict(controls):
"""Build the disambiguated list of controls
Separated out to a different function so that we can get
the control identifiers for printing.
"""
name_control_map = UniqueDict()
# collect all the possible names for all controls
# and build a list of them
... | 931b90a34e151550c399b314d368a54e3c816796 | 16,857 |
def serialize_thrift_object(thrift_obj, proto_factory=Consts.PROTO_FACTORY):
"""Serialize thrift data to binary blob
:param thrift_obj: the thrift object
:param proto_factory: protocol factory, set default as Compact Protocol
:return: string the serialized thrift payload
"""
return Serializer... | f6845b7539da82dc0555e11b0013db034d297e70 | 16,858 |
def _add_noise(audio, snr):
"""
Add complex gaussian noise to signal with given SNR.
:param audio(np.array):
:param snr(float): sound-noise-ratio
:return: audio with added noise
"""
audio_mean = np.mean(audio**2)
audio_mean_db = 10 * np.log10(audio_mean)
noise_mean_db = snr - audio... | 4f77e7a2893dc0bdcaf5e170c5e17371127b80d5 | 16,861 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.