content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import ast
def apply_bin_op(left, right, op):
"""
Finds binary expression class suitable for combination of left and right
expressions depending on whether their output is scalar or vector and
creates instance of this expression with specified operation.
"""
exr_class = BIN_EXPR_CLASSES.get(
... | fb5e6c0434dfa209ab34c4253e71bba6cb74e901 | 27,740 |
def pre_filter(image):
"""Apply morphological filter"""
return cv2.morphologyEx(image, cv2.MORPH_OPEN, np.ones((3, 3))) | a1af13d831d8462bc9c23443d2416efe66d3082b | 27,742 |
def build_corpus(docs: DocumentSet, *, remove_words=None, min_word_length=3,
min_docs=5, max_docs_ratio=0.75, max_tokens=5000,
replace_words=None, custom_bigrams=None, ngram_threshold=None
) -> Corpus:
""" Build a `Corpus` object.
This function takes the words... | 746eaa78fa498cd32950b3a006bfa669431037d0 | 27,743 |
def _Data_to_bytes(data: Data) -> bytes:
"""
Cast websockets.typing.Data to bytes.
Parameters
----------
data : str | bytes
Returns
-------
bytes
Either casted string or original bytes.
"""
return data.encode() if isinstance(data, str) else data | 0391dd9b9de0c8a978b16b6c89f9f3515f1a49de | 27,744 |
import torch
import time
def run_pairs(genotype_df, variant_df, phenotype1_df, phenotype2_df, phenotype_pos_df,
covariates1_df=None, covariates2_df=None, p1=1e-4, p2=1e-4, p12=1e-5, mode='beta',
maf_threshold=0, window=1000000, batch_size=10000, logger=None, verbose=True):
"""Compute C... | 3a38f2f38bd7351b93d3ede0f6c6d2e07427263d | 27,745 |
def main(local_argv):
"""
local_argv is the argument list, progrom name is first arugment
this function prints the fibonacci list calcuated by the command line argument n
"""
if len(local_argv) != 2:
print("must add one and only one command argument, , exit ")
return
... | 932c2b7a4f82ed03c62739e6e48350db057957da | 27,746 |
def alternate(*iterables):
"""
[a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...]
>>> alternate([1,4], [2,5], [3,6])
[1, 2, 3, 4, 5, 6]
"""
items = []
for tup in zip(*iterables):
items.extend([item for item in tup])
return items | ed3b0c8a32de8d88fc24b8bb08012a0900b37823 | 27,747 |
def softmax(x, axis=-1, t=-100.):
"""
Softmax operation
Args:
x (numpy.array): input X
axis (int): axis for sum
Return:
**softmax** (numpy.array) - softmax(X)
"""
x = x - np.max(x)
if np.min(x) < t:
x = x/np.min(x)*t
e_x = np.exp(x)
return e_x / e_x.sum(axis, keepdims=True) | 7979c7eeaf4be319f06532abc2a2cc3a23af134d | 27,748 |
def format_params_in_str_format(format_string):
"""
Get the "parameter" indices/names of the format_string
Args:
format_string: A format string (i.e. a string with {...} to mark parameter placement and formatting
Returns:
A list of parameter indices used in the format string, in the or... | a8b79cb6ee7a544b60c193dfbc2dbdc22d5d1f92 | 27,749 |
def AMO(df, M1=5, M2=10):
"""
成交金额
:param M1:
:param M2:
:return:
"""
AMOUNT = df['amount']
AMOW = AMOUNT / 10000.0
AMO1 = MA(AMOW, M1)
AMO2 = MA(AMOW, M2)
return pd.DataFrame({
'AMOW': AMOW, 'AMO1': AMO1, 'AMO2': AMO2
}) | ef45e245e1abb5705760e55b99e2e0757c66667c | 27,750 |
def tex_initial_states(data):
"""Initial states are texed."""
initial_state = []
initial_state = [''.join(["\lstick{\ket{", str(data['init'][row]),"}}"]) for row in range(len(data['init']))]
return data, initial_state | cd1758b594ee854cfb7854ec742dc177a43b54b7 | 27,751 |
import csv
def get_upgraded_dependencies_count(repo_path, django_dependency_sheet) -> tuple:
"""
Entry point to read, parse and calculate django dependencies
@param repo_path: path for repo which we are calculating django deps
@param django_dependency_sheet: csv which contains latest status of django ... | 1a793c57b69966c45f680fd39fec31a94d4d5616 | 27,752 |
def FanOut(num):
"""Layer construction function for a fan-out layer."""
init_fun = lambda rng, input_shape: ([input_shape] * num, ())
apply_fun = lambda params, inputs, **kwargs: [inputs] * num
return init_fun, apply_fun | 7e6d07319be600dabf650a4b87f661bf20832455 | 27,754 |
import urllib
import logging
def is_online(url="http://detectportal.firefox.com", expected=b"success\n"):
"""
Checks if the user is able to reach a selected hostname.
:param hostname: The hostname to test against.
Default is packages.linuxmint.com.
:returns: True if able to connect or False otherw... | 00081e05fbb1cfaa81a03a487201af4c07b23fd2 | 27,755 |
def get_Data_temblor():
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
credentials = get_credentials()
... | 1dca23ae977dc4400b31e323d1c2aac5e6e685a3 | 27,756 |
def triplet_loss(y_true, y_pred, alpha = 0.2):
"""
Implementation of the triplet loss as defined by formula (3)
Arguments:
y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
y_pred -- python list containing three objects:
anchor -- t... | 41257b626fdb4773769bf20d2aa11caaa8896259 | 27,757 |
import inspect
def node_from_dict(node_dict):
"""Create a new node from its ``node_dict``.
This is effectively a shorthand for choosing the correct node class and
then calling its ``from_dict`` method.
Args:
node_dict (dict): dict-representation of the node.
Returns:
New schema ... | 299cc2e1f194338ff3bbc13f729284b61b884b1b | 27,758 |
def _get_activation(upsample_activation):
"""get activation"""
nonlinear = getattr(nn, upsample_activation)
return nonlinear | 4423edf977ccd6db6fa6fdb5de426ecbaaed7e55 | 27,759 |
import time
def computeSensitivity(P, W):
"""
The function at hand computes the sensitivity of each point using a reduction from L_\infty to L1.
:return: None
"""
P = np.hstack((P, np.arange(P.shape[0])[:, np.newaxis]))
B, idxs = applyBiCriterea(P[:, :-1], W) # attain set of flats which give... | 089442a4c136ef473582db93b04575562ebecd96 | 27,760 |
def num_bytes_needed_for_data(rom_dict):
"""
Get the number of bytes to store the largest data in the rom.
Args:
rom_dict (dict(int:int)): Dictionary of address and data values
Returns:
(int): Number of bytes needed for largest piece of data
"""
largest_data = max(rom_dict.iterv... | af039a39c86c17d0349d53b2e5020d8cf3560f5d | 27,761 |
def run_simulation(model, **kwargs):
"""Runs the given model using KaSim and returns the parsed results.
Parameters
----------
**kwargs : List of keyword arguments
All keyword arguments specifying conditions for the simulation are
passed to the function :py:func:`run_kasim` (see documen... | 26aba6818a567faf8a08df8d5a47c213bb717183 | 27,762 |
import importlib
def _bot_exists(botname):
"""
Utility method to import a bot.
"""
module = None
try:
module = importlib.import_module('%s.%s' % (botname, botname))
except ImportError as e:
quit('Unable to import bot "%s.%s": %s' % (botname, botname, str(e)))
return module | c091be6d586faa8aacd48b30f4ce2f4fcc665e0b | 27,763 |
def bootstrap_alert_message(msg, alert_type):
"""
Wrap Ajax error message for display
:param msg: Message text
:param alert_type: must be alert-danger, alert-success, alert-info, alert-warning
:return: html formatted message
"""
if not msg:
msg = _('An unknown error has occurred')
... | cec9fa851272274a734dfbf6599ee67ed2c7c9f8 | 27,765 |
def get_message_dispatched(correlation_id, steps, primary=True):
"""
Sets a flag in cache to indicate that a message has been dispatched.
:param correlation_id: a str guid for the fsm
:param steps: an integer corresponding to the step in the fsm execution
:return: True if cached and False otherwise... | cd9a373f6b104617dfae2d488fc2348ffae61c5b | 27,766 |
def _format_exponent_notation(input_number, precision, num_exponent_digits):
"""
Format the exponent notation. Python's exponent notation doesn't allow
for a user-defined number of exponent digits.
Based on [Anurag Uniyal's answer][answer] to the StackOverflow
question ['Python - number of digits i... | 59f61897c70ca1d9f95412b2892d5c9592e51561 | 27,767 |
import typing
def unicode_blackboard_activity_stream(
activity_stream: typing.List[blackboard.ActivityItem]=None,
indent: int=0,
show_title: bool=True
):
"""
Pretty print the blackboard stream to console.
Args:
activity_stream: the log of activity, if None, get the entire activity str... | 435c52b630d467aea2835644297e5099d1c69490 | 27,768 |
def normalize(vector):
"""Normalize a vector to unit length.
Args:
vector (list/tuple/numpy.ndarray): Array to be normalized
Return:
vector (numpy.ndarray): Normalized vector.
"""
length = np.sqrt(np.sum(np.asarray(vector) ** 2))
if length == 0:
return np.asarray(vector... | 5f51933a93fd6b3df0955024585105a8887f3fd2 | 27,770 |
def get_struc_qty(*args):
"""get_struc_qty() -> size_t"""
return _idaapi.get_struc_qty(*args) | f370db3d60fdc0b5870baf8a9b616163d55860c6 | 27,771 |
from typing import Callable
def evaluate0(gametree_: Callable[[Board],
Node], static_eval_: Callable[[Board], int],
prune_: Callable[[Node], Node]) -> Callable[[Board], int]:
"""Return a tree evaluation function"""
def evaluate_(board: Board) -> int:
re... | eda97c4a6be5bac08ca0a73e0653b9c58321b539 | 27,772 |
import http
def fortune(inp):
"""
.fortune -- returns one random card and it's fortune
"""
try:
cards = http.get_json("https://tarot-api.com/draw/1")
except HTTPError:
return "The spirits are displeased."
card = cards[0]
return card["name"] + ": " + ", ".join(card["keywo... | d167238880a63afdd0aee11c2d02354a672d7fb8 | 27,773 |
def declin_0(x, obl):
"""
declination of a point of ecliptic
:param x: longitude of the point in degree
:param obl: obliquity of the ecliptic in degree
return declination in degree
"""
return DEG * m.asin(m.sin(x * RAD) * m.sin(obl * RAD)) | 5853ceb9d0424618a1b1406ee53ea87779f3b535 | 27,774 |
def network_data_structures(stream_names_tuple, agent_descriptor_dict):
"""Builds data structures for the network. These data
structures are helpful for animating the network and
for building networks of processes.
Parameters
----------
Same as for make_network.
Return Values
------... | 158484dd882eb14da1824408c35d7124282d47e1 | 27,775 |
import numpy
from typing import OrderedDict
def to_onnx(model, X=None, name=None, initial_types=None,
target_opset=None, options=None, rewrite_ops=False,
white_op=None, black_op=None, final_types=None):
"""
Converts a model using on :epkg:`sklearn-onnx`.
@param model ... | 27a21d66d78e2432362718b89d8df830471d521c | 27,776 |
def setRx(phi):
"""Rotation matrix around x axis"""
Rx = np.zeros((phi.size,3,3))
Rx[:,0,0] = 1.
Rx[:,1,1] = np.cos(phi)
Rx[:,2,2] = Rx[:,0,0]
Rx[:,1,2] = -np.sin(phi)
Rx[:,2,1] = -Rx[:,0,2]
return Rx | a70699ccc61b30d820fd9172b459680a1287e8e0 | 27,777 |
def discrete_resample(df, freq_code, agg_fun, remove_inter=False, **kwargs):
"""
Function to properly set up a resampling class for discrete data. This assumes a linear interpolation between data points.
Parameters
----------
df: DataFrame or Series
DataFrame or Series with a time index.
... | 502a63b81c8cf027853e45f77e2c9b18c1beddb4 | 27,778 |
def reflect(data, width):
"""Ceflect a data word, means revert the bit order."""
reflected = data & 0x01
for _ in range(width - 1):
data >>= 1
reflected = (reflected << 1) | (data & 0x01)
return reflected | bd5a0b804419c52ebdc6777fa0256c6a2dd4475c | 27,779 |
def snell_angle_2(angle_1, n_1, n_2):
"""Calculate the angle of refraction of a ray travelling between two mediums
according to Snell's law.
Args: angle_1 (array_like[float]): angle of incidence with respect to surface
normal in radians. n_1 (float): index of refraction in first medium.... | 5917dfc412e002bdfe494b3648dfdb7ba63a3cd7 | 27,780 |
def npv(ico, nci, r, n):
""" This capital budgeting function computes the net present
value on a cash flow generating investment.
ico = Initial Capital Outlay
nci = net cash inflows per period
r = discounted rate
n = number of periods
Example: npv(100000, 15000, .03, 10)
"""
pv_nc... | fa3128de0fe8a2f7b8bbe754f0e1b1e1a0eb222d | 27,781 |
import time
import functools
import threading
def instrument_endpoint(time_fn=time.time):
"""Decorator to instrument Cloud Endpoint methods."""
def decorator(fn):
method_name = fn.__name__
assert method_name
@functools.wraps(fn)
def decorated(service, *args, **kwargs):
service_name = service... | cf2fdfff5aa8854cc6c02850d6a9787ca45b7c7e | 27,782 |
def manhattan_distances(X, Y):
"""Compute pairwise Manhattan distance between the rows of two matrices X (shape MxK)
and Y (shape NxK). The output of this function is a matrix of shape MxN containing
the Manhattan distance between two rows.
Arguments:
X {np.ndarray} -- First matrix, contai... | 0cbec7eae4cb33d0ed13947bbc7df7b4b6171807 | 27,783 |
def remove_access_group(request):
"""
Add access groups to the image.
"""
if request.method != "POST":
messages.error(request, "Invalid request method.")
return redirect('images')
if 'id' not in request.POST or not request.POST.get('id').isdigit() or 'access_group' not in request.PO... | 1e61b0a403a06154dce5b7f745a401e7ddf635d6 | 27,784 |
def replace_strings_in_file(i):
"""
Input: {
file
(file_out) - if !='', use this file for output, otherwise overwrite original one!
replacement_json_file - replacement file with multiple strings to substitute
}
Output: {
return... | b15d3058e1486d6f6171438bd62da05cb8d5732b | 27,786 |
def fill_polygon(points, im_shape):
"""Fill the polygon defined by convex or contour points
Parameters
----------
points: array
Coordinates of the points that define the convex or contour of the mask
im_shape: array
Array shape of the mask
Returns
-------
im_cnt: array
Fil... | abbe69180582c12233c8632ca2ca60485ce4d717 | 27,787 |
def load(section, option, archive=_ConfigFile):
"""
Load variable
"""
cfg = ConfigParser()
try:
cfg.readfp(file(archive))
except Exception, e:
sys.stderr.write("%s, %s\n" % (archive, e.strerror))
return
try:
return cfg.get(section, option)
except:
sys.stderr.write("Incorrect value... | 3cf8bebb9ffdaf4a25ece950560680fabdf8c459 | 27,788 |
def merge_duplicates(model_name, keep_descriptors=False):
"""
Identifies repeated experimental values and returns mean values for those
data along with their standard deviation. Only aggregates experimental
values that have been acquired at the same temperature and pressure.
Parameters
--------... | a3baa232535f9c3bfd9496259f0cf3fd6142665b | 27,789 |
def autoencoder_cost_and_grad_sparse(theta, visible_size, hidden_size, lambda_, rho_, beta_, data):
"""
Version of cost and grad that incorporates the hidden layer sparsity constraint
rho_ : the target sparsity limit for each hidden node activation
beta_ : controls the weight of the sparsity pen... | 9810517cab7adc5ca71d46d602e347b301a392d4 | 27,790 |
def isnpixok(npix):
"""Return :const:`True` if npix is a valid value for healpix map size, :const:`False` otherwise.
Parameters
----------
npix : int, scalar or array-like
integer value to be tested
Returns
-------
ok : bool, scalar or array-like
:const:`True` if given value is... | 9501ab6e3172761cba0ec2e3693e5442924162af | 27,791 |
def get_team_metadata(convert_users_role_to_string=False):
"""Returns team metadata
:param convert_users_role_to_string: convert integer team users' roles to human comprehensible strings
:type convert_users_role_to_string: bool
:return: team metadata
:rtype: dict
"""
response = _api.send_re... | 6b48cc6f30bd2304f54c1ff695be6faaab187a9f | 27,794 |
def get_request_timestamp(req_type=None, timestamp=getCurrentMillis()):
"""
:param req_type: YTD, QTD, MTD, WTD, TODAY or None
if None return first unix timestamp
:return: unix timestamp
"""
@dataclass
class YTD(object):
pass
bench_date = pd.to_datetime(getUTCBeginDay(timestamp... | 2e18c23167bca388b8f2ad4febfe6f3a39df1151 | 27,795 |
def to_nest_placeholder(nested_tensor_specs,
default=None,
name_scope="",
outer_dims=()):
"""Converts a nest of TensorSpecs to a nest of matching placeholders.
Args:
nested_tensor_specs: A nest of tensor specs.
default: Optional consta... | 329bf5e76f5753a07f78394a8a065e3e44334929 | 27,796 |
import asyncio
async def discover():
"""Discover and return devices on local network."""
discovery = TuyaDiscovery()
try:
await discovery.start()
await asyncio.sleep(DEFAULT_TIMEOUT)
finally:
discovery.close()
return discovery.devices | fb3fed149011983520d884f139f9296973686459 | 27,797 |
def update_firewall_policy(module, oneandone_conn):
"""
Updates a firewall policy based on input arguments.
Firewall rules and server ips can be added/removed to/from
firewall policy. Firewall policy name and description can be
updated as well.
module : AnsibleModule object
oneandone_conn: ... | 0d99fbee3a67e2c571bd9d9ad5ce698588ac0df4 | 27,798 |
import math
def expanded_velocities_from_line_vortices(
points,
origins,
terminations,
strengths,
ages=None,
nu=0.0,
):
"""This function takes in a group of points, and the attributes of a group of
line vortices. At every point, it finds the induced velocity due to each line
vortex... | 228f7aa527dd1e9386bdc76da7c6e3c58698e58c | 27,800 |
def normcase(path):
"""Normalize the case of a pathname. On Unix and Mac OS X, this returns the
path unchanged; on case-insensitive filesystems, it converts the path to
lowercase. On Windows, it also converts forward slashes to backward slashes."""
return 0 | d52dca00cc9db607d4ba22c12ba38f512a05107b | 27,801 |
def typeof(obj, t):
"""Check if a specific type instance is a subclass of the type.
Args:
obj: Concrete type instance
t: Base type class
"""
try:
return issubclass(obj, t)
except TypeError:
return False | 67fbcf8b1506f44dba8360a4d23705a2e8a69b47 | 27,802 |
def get_all_clusters(cluster_type, client_id):
"""Get a list of (cluster_name, cluster_config)
for the available kafka clusters in the ecosystem at Yelp.
:param cluster_type: kafka cluster type
(ex.'scribe' or 'standard').
:type cluster_type: string
:param client_id: name of the client maki... | 8860435edfde332fd78e3bf01789a2831d884165 | 27,803 |
from .. import getPlottingEngine
def plot(x, y, show=True, **kwargs):
""" Create a 2D scatter plot.
:param x: A numpy array describing the X datapoints. Should have the same number of rows as y.
:param y: A numpy array describing the Y datapoints. Should have the same number of rows as x.
:param colo... | 0b43a2b1e442ae19feaf0fb3a64550cad01b3602 | 27,804 |
def get_transform_ids(workprogress_id, request_id=None, workload_id=None, transform_id=None, session=None):
"""
Get transform ids or raise a NoObject exception.
:param workprogress_id: Workprogress id.
:param session: The database session in use.
:raises NoObject: If no transform is founded.
... | 08fbd67eb932c7c48b04528dd0863e67669e526e | 27,805 |
from typing import Optional
def get_link(hub_name: Optional[str] = None,
link_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLinkResult:
"""
The link resource format.
Latest API Versi... | b94a7d2ed3977afbff0699e861da67e1267581b4 | 27,806 |
import random
def selection_elites_random(individuals : list, n : int = 4, island=None) -> list:
"""
Completely random selection.
Args:
individuals (list): A list of Individuals.
n (int): Number to select (default = 4).
island (Island): The Island calling the method (default = Non... | 2f7df4e8a347bcd9a770d0d15d91b52956dbd26c | 27,808 |
import ctypes
def ekssum(handle, segno):
"""
Return summary information for a specified segment in a specified EK.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekssum_c.html
:param handle: Handle of EK.
:type handle: int
:param segno: Number of segment to be summarized.
:type ... | 9c9920d29ed1c1c85524a511119f37322143888c | 27,809 |
def compare_prices_for_same_urls(
source_df: pd.DataFrame, target_df: pd.DataFrame, tagged_fields: TaggedFields
):
"""For each pair of items that have the same `product_url_field` tagged field,
compare `product_price_field` field
Returns:
A result containing pairs of items with same `product_ur... | dc23577169bf6788ecd17eb2fc6c959e367b5000 | 27,810 |
def _check_param(dict_):
"""
check dictionary elements and reformat if need be
:return: dictionary reformat
"""
# default empty dictionary
_ = {}
if "google_users" in dict_:
_["google_users"] = _check_param_google_users(dict_["google_users"])
else:
_logger.exception(f"N... | 17ccc017fb4a34f3d68ef7150165185e62c7a8dc | 27,811 |
def fetch_dataset_insistently(url: str, link_text_prefix: str, user_agent: str) -> dict:
"""Fetch the approved routes dataset."""
proxies = get_proxies_geonode() + get_proxies()
print(f'{len(proxies)} proxies found.')
for i, proxy in enumerate(proxies):
print(f'Fetching dataset, try with proxy [... | c98985becc3989980782c4886e18fe7fa56f8d06 | 27,812 |
import numpy
def _dense_to_one_hot(labels_dense):
"""Convert class labels from scalars to one-hot vectors."""
num_classes = len(set(labels_dense))
num_labels = labels_dense.shape[0]
labels_to_numbers = {label: i for i, label in enumerate(list(set(labels_dense)))}
labels_as_numbers = numpy.asarray(... | 49cc3ab6bc5f4ec81323321a9fe13d4da030fb4a | 27,813 |
def swish(x):
"""Swish activation function. For more info: https://arxiv.org/abs/1710.05941"""
return tf.multiply(x, tf.nn.sigmoid(x)) | 40766f934d2e691dc28d5dcd3a44c37cef601896 | 27,814 |
def fatorial(n=1):
"""
-> Calcúla o fatorial de um número e o retorna
:param n: número
"""
f = 1
for i in range(1, n + 1):
f *= i
return f | 5c64b8ccf4a62a1b4294e576b49fbf69e85972ec | 27,815 |
def retrieve_context_nw_topology_service_name_name_by_id(value_name): # noqa: E501
"""Retrieve name by ID
Retrieve operation of resource: name # noqa: E501
:param value_name: ID of value_name
:type value_name: str
:rtype: NameAndValue
"""
return 'do some magic!' | 4dcc0b25c6fd76bf94e14d63cb9731946b97b06a | 27,816 |
def conv1x1(in_planes, out_planes, wib, stride=1):
"""1x1 convolution"""
# resnet_wib = False
resnet_wib = True
resnet_alpha = 1E-3
if not wib:
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
else:
return WibConv2d(alpha=resnet_alpha,
... | 0ce1d9d47ff98dc7ce607afafb4ea506c850afc3 | 27,817 |
def get_rules(fault_block, zone):
"""Get rules for fault block and zone names.
In this model the rules depend only on the zone; they do NOT
vary from fault block to fault block for a given zone.
Args:
fault_block (str)
Name of fault block.
zone (str)
Zone name.
... | 12b19cd795ecf618995a2f67f3844792b372d09d | 27,818 |
from operator import concat
def conv_cond_concat(x, y):
"""Concatenate conditioning vector on feature map axis."""
x_shapes = tf.shape(x)
y_shapes = tf.shape(y)
return concat([
x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])], 3) | 583ed5df67245b483531f8e3129ba88b9ec811ef | 27,819 |
def get_clusters(cloud_filtered):
"""
Get clusters from the cloud.
Parameters:
-----------
cloud: pcl.PointCloud()
Returns:
-----------
clusters: pcl.PointCloud() array N
"""
clusters = []
tree = cloud_filtered.make_kdtree()
ec = cloud_filtered.make_EuclideanCl... | b4b7fa0ff8b7f362783bc94727253a2eb41f6f7e | 27,820 |
import json
def errorResult(request, response, error, errorMsg, httpStatus = 500, result = None, controller = None):
""" set and return the error result
@param controller: pylon controller handling the request, where cal context is injected and later retrieved by trackable
"""
response.status_int... | df386f939751ea268907c016120db7219c3e93bc | 27,821 |
from typing import Dict
import logging
def parse_main(text: str = "") -> Dict:
"""
A loop for processing each parsing recipe. Returns a dict of parsed values.
"""
if text == "":
logging.warning("Empty string provided for parsing")
parsed_data = {}
for recipe in parser_recipe:
... | 4574b3e9dce321f169f31031e46e572fac14fce3 | 27,822 |
def main():
""" Returns the answer. """
return 42 | f6800af5efb0b65f7c7afdd5ea0ede896fd740f8 | 27,823 |
def collect_accuracy(path):
""" Collects accuracy values in log file. """
r1 = None
r5 = None
mAP = None
r1_content = 'Rank-1 '
r5_content = 'Rank-5 '
map_content = 'mAP:'
with open(path) as input_stream:
for line in input_stream:
candidate = line.strip()
... | fa94724f16a332fe18d13df3cc0fbcdd060fe897 | 27,825 |
from typing import Type
from typing import Mapping
def recursively_get_annotations(ty: Type) -> Mapping[str, Type]:
"""Given a type, recursively gather annotations for its subclasses as well. We only
gather annotations if its subclasses are themselves subclasses of Deserializable,
and not Deserializable i... | ba531eeba8006aa9393fa2487c056d6309df43d4 | 27,826 |
def sector_model():
"""SectorModel requiring precipitation and cost, providing water
"""
model = EmptySectorModel('water_supply')
model.add_input(
Spec.from_dict({
'name': 'precipitation',
'dims': ['LSOA'],
'coords': {'LSOA': [1, 2, 3]},
'dtype': '... | 528548e24052913a315804a782cb74cef53b0f08 | 27,827 |
def maybe_flip_x_across_antimeridian(x: float) -> float:
"""Flips a longitude across the antimeridian if needed."""
if x > 90:
return (-180 * 2) + x
else:
return x | 50fac7a92d0ebfcd003fb478183b05668b9c909c | 27,828 |
def contour_check(check_points, random_walk):
"""check_points have dim (n, ndim)
random_walk has 3 elements.
[0] is boundary unit vectors (can be in any space),
[1] is boundary ls (relative to origin)
[2] is origin
returns: indexer of [True,..... etc.] of which points are in or not
... | fa973c943c4827bd180eb95a3bbc3e0a7d2beb2a | 27,829 |
def _get_erroneous_call(report_text: str) -> str:
"""."""
erroneous_line = [
line for line in report_text.splitlines() if line.startswith('> ') and RAISES_OUTPUT_SIGNAL_IN_CONTEXT in line
][0]
erroneous_assertion = erroneous_line.lstrip('> ')
erroneous_assertion = string_remove_from_start(er... | 125267db8fb978285fc44ec078364b214c022ca9 | 27,830 |
def write_output(features, forecast_hours, poly, line, point):
"""
writes output to OUTDATA dict depending on query type
:param features: output from clipping function
:param forecast_hours: list of all queried forecast hours
:param poly: boolean to identify a polygon query
:param line: boolean... | abc92e597e4d8a409f7c4d0e0b224a76b4a6cd63 | 27,831 |
def index():
"""
Index set as main route
"""
return render_template('index.html', title='Home') | bacc433a4523a9b390bdde636ead91d72303cf01 | 27,832 |
def plus_one(digits):
"""
Given a non-empty array of digits representing a non-negative integer,
plus one to the integer.
:param digits: list of digits of a non-negative integer,
:type digits: list[int]
:return: digits of operated integer
:rtype: list[int]
"""
result = []
carry ... | a11668a1b2b9adb9165152f25bd1528d0cc2bd71 | 27,833 |
def run_experiment(input_frame, n_samples=1, temperature=1, npartitions=1):
"""
Runs experiment given inputs.
Takes `n_samples` samples from the VAE
Returns a list of size `n_samples` of results for each input
"""
encoder_data = a.get_encoder()
decoder_data = a.get_decoder()
vae = a.g... | 2729a977b14235bf5a0e020fbe8a528a5906f212 | 27,834 |
def to_angle(s, sexagesimal_unit=u.deg):
"""Construct an `Angle` with default units.
This creates an :class:`~astropy.coordinates.Angle` with the following
default units:
- A number is in radians.
- A decimal string ('123.4') is in degrees.
- A sexagesimal string ('12:34:56.7') or tuple ... | 106a5be01c3f9150862c1e02f5cd77292b029cf6 | 27,835 |
def simpleBlocking(rec_dict, blk_attr_list):
"""Build the blocking index data structure (dictionary) to store blocking
key values (BKV) as keys and the corresponding list of record identifiers.
A blocking is implemented that simply concatenates attribute values.
Parameter Description:
rec_dict... | 5bf9b85ad84ffa3dc11a39a876cbcfefe09a5b2c | 27,836 |
def get_marker_obj(plugin, context, resource, limit, marker):
"""Retrieve a resource marker object.
This function is used to invoke
plugin._get_<resource>(context, marker) and is used for pagination.
:param plugin: The plugin processing the request.
:param context: The request context.
:param ... | 5e66ca50382c6e8a611983252ce44bf50019177b | 27,837 |
def generative(max_value: int = FIBONACCI_MAX) -> int:
"""
This is the fully generative method for the Fibonacci sequence. The full sequence list is generated, the even ones
are sought out, and summed
--> benchmark: 8588 ns/run
:param max_value: The ceiling value of Fibonacci numbers to be added
... | 086076d2599297fd23eaa5577985bd64df10cc81 | 27,839 |
def enc_net(num_classes, pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = Net(num_classes, **kwargs)
# if pretrained:
# model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))... | ff8429e6b0e5ef522f6f2a3b0b10a76951a95db8 | 27,841 |
def get_bytes(data):
"""
Helper method to get the no. of bytes in the hex"""
data = str(data)
return int(len(sanatize_hex(data)) / 2) | 014715aa301370ba2d3598c02b66c5b88741b218 | 27,842 |
import collections
def _group_by(input_list, key_fn):
"""Group a list according to a key function (with a hashable range)."""
result = collections.defaultdict(list)
for x in input_list:
result[key_fn(x)].append(x)
return result | 288c108588f9e4ea60c4dac6ff656c8c8ffde580 | 27,843 |
import json
def set_parameters_in_cookie(response: Response) -> Response:
"""Set request parameters in the cookie, to use as future defaults."""
if response.status_code == HTTPStatus.OK:
data = {
param: request.args[param]
for param in PARAMS_TO_PERSIST
if param in ... | bc5f4e225bdef907ee794e3f8f95ac3d78677046 | 27,844 |
from _pytest.logging import LogCaptureFixture
import json
from typing import Any
import logging
def test_wild_dlq_error(mock_handler: MagicMock, mock_rsmq: MagicMock, caplog: LogCaptureFixture) -> None:
"""test error level logs when message fails to successfully reach DLQ"""
mock_handler.return_value = False,... | d00c32e27833975d819b333c723734d24b3ead65 | 27,845 |
from typing import VT
from typing import Optional
def teleport_reduce(g: BaseGraph[VT,ET], quiet:bool=True, stats:Optional[Stats]=None) -> BaseGraph[VT,ET]:
"""This simplification procedure runs :func:`full_reduce` in a way
that does not change the graph structure of the resulting diagram.
The only thing... | 38474e11094a21e581a18591b7649fdbdd977d72 | 27,846 |
def map_coords_to_scaled(coords, orig_size, new_size):
"""
maps coordinate indices relative to the original 3-D image to indices corresponding to the
re-scaled 3-D image, given the coordinate indices and the shapes of the original
and "new" scaled images. Returns integer indices of the voxel that con... | 74236074a0c6c5afbb56bd5ec75caaf517730040 | 27,847 |
def _PromptToUpdate(path_update, completion_update):
"""Prompt the user to update path or command completion if unspecified.
Args:
path_update: bool, Value of the --update-path arg.
completion_update: bool, Value of the --command-completion arg.
Returns:
(path_update, completion_update) (bool, bool)... | 2759e9c42c702a69fa617fc3302cb3c850afc54a | 27,848 |
def _get_static_covariate_df(trajectories):
"""The (static) covariate matrix."""
raw_v_df = (
trajectories.static_covariates.reset_coords(drop=True).transpose(
'location', 'static_covariate').to_pandas())
# This can then be used with, e.g. patsy.
# expanded_v_df = patsy(raw_v_df, ...patsy detail... | 15c8f367452fc5007ad93fd86e04cfea07e96982 | 27,850 |
import json
def answer_cells_of_nb(a_ipynb):
"""
get the contents of all answer cells (having grade_id)
in an a_ipynb file
"""
cells = {}
with open(a_ipynb) as ipynb_fp:
content = json.load(ipynb_fp)
for cell in content["cells"]:
meta = cell["metadata"]
... | 3b011d48a8ccfa13d462cccf1b0a58440231a1ce | 27,851 |
def _transpose_augment(img_arr):
""" 对称扩增 """
img = Image.fromarray(img_arr, "L")
return [np.asarray(img.transpose(Image.FLIP_LEFT_RIGHT))] | 096c8db4c008c78a5f22bffeea8bb64fb0a4de09 | 27,852 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.