content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def minibatch_discriminator(x):
""" Computes minibatch discrimination features from input tensor x"""
diffs = K.expand_dims(x, 3) - \
K.expand_dims(K.permute_dimensions(x, [1, 2, 0]), 0)
l1_norm = K.sum(K.abs(diffs), axis=2)
return K.sum(K.exp(-l1_norm), axis=2) | 6aca40e80c5b86d291251adec1457f715a77ee45 | 61,800 |
def parse_module_descriptors(raw_json: bytes) -> list[ModuleDescriptor]:
"""Parse the JSON output of `go list -m`."""
if not raw_json:
return []
module_descriptors = []
for raw_module_descriptor in ijson.items(raw_json, "", multiple_values=True):
if raw_module_descriptor.get("Main", Fal... | 750af019899f554cd2cb8b8043360d3893850837 | 61,801 |
from typing import Any
from typing import Tuple
from typing import Optional
import numbers
import torch
def _parse_array_or_scalar_like_pair(actual: Any, expected: Any) -> Tuple[Optional[Exception], Optional[_ParsedInputs]]:
"""Parses an scalar-or-array-like pair.
Args:
actual: Actual array-or-scalar... | eadfa0b9de6cd419bdf657a3b66207d0ac052b7c | 61,802 |
def atomic(session=default_session):
"""
with atomic(): # None
pass
with atomic(session): # Session
pass
@atomic # Callable
def x():
pass
@atomic(session): # Session
def x():
pass
"""
if (
not isinstance(session, (Session, scoped_session... | 909160c1f67c3af61d81139a5776a64fa171eaa5 | 61,803 |
import mpmath
def var(k, theta):
"""
Variance of the gamma distribution.
"""
k = mpmath.mpf(k)
theta = mpmath.mpf(theta)
return k * theta**2 | 9dbbc299f41810555dd379dfcc3dd6f16daa74a5 | 61,804 |
def count_newlines_fast(path: Pathlike):
"""
Counts newlines in a file using buffered chunk reads.
The fastest possible option in Python according to:
https://stackoverflow.com/a/68385697/5285891
(This is a slightly modified variant of that answer.)
"""
def _make_gen(reader):
b = re... | 6c79bb00834685e00cb201d31ca61637b0c0a94f | 61,805 |
def crc32(seq):
"""Returns the crc32 checksum for a sequence (string or Seq object)."""
#NOTE - On Python 2 returns a signed int, on Python 3 it is unsigned
#Docs suggest should use crc32(x) & 0xffffffff for consistency.
#TODO - Should we return crc32(x) & 0xffffffff here?
try:
#Assume its a... | f403a94fe72fee204acdea276cfaa7c40a3e879d | 61,806 |
def current_date_int():
"""
获取当前时间日期 int值
不使用时间api,直接进行字符串解析,执行效率高
:return: 日期int值
"""
date_int = 0
# 首先获取str
today = current_str_date()
# 手动比系统a时间pi快
today_array = today.split("-")
if len(today_array) == 3:
date_int = int(today_array[0]) * 10000 + int(today_array[1])... | 8a2425f64b39ece46b5e2ee1088f9d8d690e25a7 | 61,807 |
import os
def load_scalar(layer):
"""
Load the feature mean / variance scalar for the input layer
:type layer: str
:param layer: Feature layer
:return: scalar
"""
if not layer in feature_layers:
raise NotImplementedError('Feature Layer Type Not Found.')
features_path = os.pa... | f6898657d2c3a30d78b7abef0a080873dc63e04c | 61,808 |
import signal
def _timeout(seconds):
"""Decorator for preventing a function from running for too long.
Inputs:
seconds (int): The number of seconds allowed.
Notes:
This decorator uses signal.SIGALRM, which is only available on Unix.
"""
assert isinstance(seconds, int), "@timeout(... | afa077719853ed132cd0ca92225bbbe555371c0f | 61,809 |
import asyncio
def listen_properties_changed(bus, callback):
"""Create a future for a PropertiesChanged signal listener.
Args:
bus: The system bus object to use.
callback: The callback function to run when signal is received.
Returns:
Integer rule id.
"""
return bus.addM... | 1c6685eac1bb9419d95cb3e32409b247714b365c | 61,810 |
import os
async def check_files(hass):
"""Return bool that indicates if all files are present."""
# Verify that the user downloaded all files.
base = f"{hass.config.path()}/custom_components/{DOMAIN}/"
missing = []
for file in REQUIRED_FILES:
fullpath = "{}{}".format(base, file)
if... | ee2fb55d2af13f425337a387eeeeb1357fa7788e | 61,811 |
import yaml
import subprocess
def validate_output(output, fmt, mcf):
"""compare values in merp2tbl output with merp -d row for row, non-NA must agree
Parameters
----------
output : dict
as returned by format_output
fmt : str
'tsv' or 'yaml'
mcf : str
path to merp command ... | 2d9e7c89f8280751abfc328042c0ee3bd1572f4a | 61,812 |
import select
def get_hadoop_conf_dir():
"""
Gets the shared hadoop conf directory using:
1. Start with /etc/hadoop/conf
2. When the stack is greater than HDP-2.2, use /usr/hdp/current/hadoop-client/conf
3. Only when doing a RU and HDP-2.3 or higher, use the value as computed
by conf-select. This ... | 27ac913d5ad34772bef51a6befb3f685390ef7cd | 61,813 |
from .query import Database
from bob.db.base.utils import null
import sys
def reverse(args):
"""Returns a list of file database identifiers given the path stems"""
db = Database()
output = sys.stdout
if args.selftest:
output = null()
try:
r = db.reverse(args.path)
except KeyError as err:
r... | 3b6d0d869c78d40c53f719f6f59404f1365416c3 | 61,814 |
from typing import List
from typing import Tuple
def delme_list_to_rangemap(delme_verts: List[int]) -> Tuple[List[int],List[int]]:
"""
Given an ascending sorted list of ints, build a pair of lists that let me know what indices OTHER things will map
to when THESE indices are deleted. list1 is the index each cluster... | 447d783a24926857acb174e4908295640ed6e8ae | 61,815 |
from typing import Sequence
from typing import Iterable
import functools
def generate_aggregate_pubkeys(validators: Sequence['ValidatorRecord'],
vote_data: 'SlashableVoteData') -> Iterable[BLSPubkey]:
"""
Compute the aggregate pubkey we expect based on
the proof-of-custody i... | 478cdb3ab19c75b0e2fe042248cdbbb1cf251ebf | 61,816 |
def get_dimensions(unit):
"""get the set of basis units"""
if hasattr(unit, 'dimension'):
return unit.dimension
if isinstance(unit, Mul):
return Mul.fromiter([get_dimensions(arg) for arg in unit.args])
if isinstance(unit, Pow):
base, exp = unit.as_base_exp()
return Pow(ge... | a564a6d1369f19d4830cdbffdf7240e3f362248a | 61,817 |
from typing import Tuple
def mutual_information(
indices_a: np.ndarray, indices_b: np.ndarray
) -> Tuple[float, float]:
""" Mutual Information
Parameters
----------
indices_a : array-like, shape(n_samples)
Symbolic time series.
indices_b : array-like, shape(n_samples)
Symbol... | 4aaf38a01257a8de8b052eb07e3a9ca9bcac6945 | 61,818 |
import json
def validate_token(func):
"""Decorator for validating the JWT token required for API requests."""
@wraps(func)
def wrapper(*args, **kwargs):
"""Tries to decode the JWT token using the SECRET KEY.
Executes the original function if token is valid.
Otherwise ret... | 43b5427cc8edd8d2639634411f60ca6b61586891 | 61,819 |
from typing import Sequence
from typing import Tuple
import numpy
def image_stabilisation_proj_(
projections: Sequence[Tuple], ndim: int, keep_best: bool = True, debug_output: str = None, **kwargs
) -> SequenceRegistrationModel:
"""
Same as 'sequence_stabilisation_proj' but takes projections instead,
... | f8fd86330c69a7b4eb8cedf56882ed66c9f105d3 | 61,820 |
def get_node_properties(node_ids, **options):
"""Get properties associated with nodes."""
fields = options.pop('fields', None)
functions = {
'type': 'labels(n)',
}
if fields is not None:
prop_string = ', '.join([f'{key}:{functions[key]}' if key in functions else f'{key}:n.{key}' for... | bbd107aa07fa7d84891f83fa7c531e7bc66e2ae3 | 61,821 |
import os
def RunPipe(pipe_list, infile=None, outfile=None,
capture=False, capture_stderr=False, oneline=False,
raise_on_error=True, cwd=None, **kwargs):
"""
Perform a command pipeline, with optional input/output filenames.
Args:
pipe_list: List of command lines to execute... | 89d5cf89109f8433b0a103b97b1c7bae6c33efb8 | 61,822 |
def reverse(insts):
"""
Reverse the order of instances.
This function should be passed to :meth:`InstanceSet.select` without any
argument.
>>> insts = InstanceSet('prediction_result_path').select(reverse)
"""
return list(reversed(insts)) | 44c63fc05015bb4eb5bed9bfdb3cdd4fbd456226 | 61,823 |
def destination(φ1: float, λ1: float, α: float, d: float):
"""Destination point, provided origin, bearing, and distance.
This is the solution to the "first" (or "forward") geodetic problem,
assuming a spherical Earth.
Parameters
----------
φ1, λ1 : float
initial latitude, longitude
... | 7d128cfa7a529eb7d9598f7aff8d8bbebbec5e8f | 61,824 |
def create_volumes(kname, cname):
"""
Creates volume bindings for Kraken name `kname` and container name `cname`.
"""
volumes = {}
# Mount configuration directory. This is necessary for components which
# populate templates and need to mount the populated template into the
# container.
... | d4db9bcd77efeb852f016834d571fb698f70d78d | 61,825 |
def double_pend(
y: list,
t: float,
m_1: float,
l_1: float,
m_2: float,
l_2: float,
g: float
) -> list:
"""
Calculate one step for coupled pendulums.
Args:
y: (theta_1, theta_d_1, theta_2, theta_d_2) at this timestep.
t: Time (unused).
m_1: Mass 1.
... | 386384102ddf1ff3d1a44452da6b5586b25398f6 | 61,826 |
import functools
def ClientOnly(f):
"""A decorator that asserts _IS_CLIENT."""
@functools.wraps(f)
def Wrapper(*args, **kwargs):
assert _IS_CLIENT
return f(*args, **kwargs)
return Wrapper | ae48c4347d160a0b04cabb2ee1080210f42288f5 | 61,827 |
def read_var_def(line: str, type_word: str = None, fun_only: bool = False):
"""Attempt to read variable definition line"""
if type_word is None:
type_match = NAT_VAR_REGEX.match(line)
if type_match is None:
return None
else:
type_word = type_match.group(0).strip()... | 4f388ec192d0f39690ba004ef9a208f53afca84a | 61,828 |
def get_user_by_api_key(api_key):
"""Looks up a user by an API key.
Args:
api_key: API key.
Returns:
A user dictionary.
Raises:
KeyError: If the specified user is not found.
"""
if not api_key:
raise KeyError('User not found by API key')
user = _db.users.fi... | 9d5dfc740398481bb9008c26181541f845321a88 | 61,829 |
def ROI(pred_thresh, im_crop, w, h, im_i=0, save_file=False):
"""
Finalize prediced ROI
:param pred_thresh: image region to analyze -
:param im_crop: RGB input
:param w,h: width and height to be resized to
:param im_i: serial ID of the input image
:param save_file: switch for saving file
Available option... | 7bfeccbbfb9e3aebe2338035c77989215636123c | 61,830 |
def _parse_comparison(sql, example, anonymize_values):
"""Parse the part relative to a comparison in the SQL query."""
successful_copy = True
for item in sql:
if item.ttype == sqlparse.tokens.Text.Whitespace:
continue
if _is_identifier(item):
successful_copy = _parse_identifier(item, example,
... | a2c75aa2961e9417f2bed5517c9064ec1d828afb | 61,831 |
def tanh(X):
"""an activation function which outputs the value between (-1,1)"""
if isinstance(X,np.ndarray):
return (2.0/(1.0+np.exp(-(2*X))))-1
else:
X=np.array(X)
return tanh(X) | dc774769242e4414243b6370d3b087b611b1d01d | 61,832 |
from typing import Optional
from typing import Mapping
from typing import Any
def char_key_value_linear_source_from_params(
params: Parameters,
*,
input_namespace: str = "input",
eval_context: Optional[Mapping[Any, Any]] = None,
) -> KeyValueLinearSource[str, str]:
"""
Get a key-value source b... | ac3eb4d529d75780b8793432229ed1bbb4fdc2b9 | 61,833 |
def get_train(opt):
"""Get training dataset for KDD 10 percent"""
return _get_adapted_dataset(opt, "train") | 591023b39b162682b2c396e8298bc8c0e492c5cb | 61,834 |
def sort_by_time(raw_folded, pdc_channels, return_indices=False):
""":param pdc_channels (tuple of lightkurve.FoldedlightCurve)"""
sort_idx_raw = np.argsort(raw_folded.time_original)
sort_idx_pdc = np.argsort(pdc_channels[0].time_original)
apply_indices_to_light_curve(raw_folded, sort_idx_raw)
for ... | c59c02651b60afc5b65079a10958f771ff32f887 | 61,835 |
def register_deserializer(instance, **options):
"""
registers a new deserializer or replaces the existing one.
if `replace=True` is provided. otherwise, it raises an error
on adding a deserializer which is already registered.
:param AbstractDeserializerBase instance: deserializer to be registered.... | 1e5ac3f1e26b1920ad23be1df2ba9aba74aedec9 | 61,836 |
import numpy
def maximum(input, labels=None, index=None):
"""
Find the maxima over an image at specified subregions.
Parameters
----------
input : ndarray
N-D image data
labels : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int... | f280c5b83ac191c208c799a59e5c483dcd4aaad5 | 61,837 |
def getViolationFromAria2(ariaViolation, constraint, violationList):
"""Descrn: Make a constraint's violation object in the input violation list given an Aria2
violation analysis object.
Inputs: Aria2 violation analysis object, NmrConstraint.DistanceConstraint, NmrConstraint.ViolationList
Outpu... | f89718bb8a2b767e51e9efa657768327548822f1 | 61,838 |
def enforce_connectivity(image, outside):
"""
Function to filter out any objects not connected to the largest
cluster in image.
Inputs:
image (np.ndarray) : Binary input raster with 1's corresponding
to hydrodynamically active areas, which get mapped to high
resolution, a... | 90e6f4fb7d8133ba2f2c8ad88d12951e4e221669 | 61,839 |
def psnd_chlA_vi(imgData, wave, mask=0, bands=[-1,-1]):
"""
Function that calculates the Pigment Sensitive Normalized Difference for Chlorophyll A.
This functions uses bands 675 and 800 nm. The closest bands to these values will be used.
Citation: Blackburn, G.A. 1998. Spectral indices for estimating p... | 9c27a09a6c83d31526dce83b50a23e5acdc3fb2c | 61,840 |
def test_request_without_setting_receive():
"""
If Request is instantiated without the receive channel, then .body()
is not available.
"""
def app(scope):
async def asgi(receive, send):
request = Request(scope)
try:
data = await request.json()
... | a1e3cc5dd59a20537ae66d8f1d575ef43f99136a | 61,841 |
def fraction_of_death_40():
"""
Real Name: b'fraction of death 40'
Original Eqn: b'0.4'
Units: b'dmnl'
Limits: (None, None)
Type: constant
b''
"""
return 0.4 | c4dd46a565660acf07273a58002cc9b2cbf94bc8 | 61,842 |
def test_video_file():
# type: () -> str
""" Fixture for test video file path (ensures file exists).
Access in test case by adding a test_video_file argument to obtain the path.
"""
return get_absolute_path("resources/testvideo.mp4") | c5a582ed4e4d1fdd52cdb026e86834626fc3678c | 61,843 |
from typing import Optional
from typing import Mapping
def _description_xml_to_dict(description_xml: str) -> Optional[Mapping[str, str]]:
"""Convert description (XML) to dict."""
try:
tree = DET.fromstring(description_xml)
except DET.ParseError as err:
_LOGGER.debug("Error parsing %s: %s",... | 8e4d139253c0c7da624c16d54315c945c106ba46 | 61,844 |
import torch
import tqdm
import os
def train_single_scale(D, G, reals, generators, noise_maps, input_from_prev_scale, noise_amplitudes, opt):
""" Train one scale. D and G are the current discriminator and generator, reals are the scaled versions of the
original level, generators and noise_maps contain informa... | eeb85f9a16a04beba164ed8b077711397cc3a5de | 61,845 |
import logging
import sys
def get_simultaneous_models(request, fit_problem, setup_request=False):
"""
Find related models and return a list of dictionary representing them.
:param Request request: http request object
:param FitProblem fit_problem: FitProblem object
:param bool set... | 1d43ca922e677275bd2e365615780dca55801f9f | 61,846 |
def write_ometiff(filepath, img,
scalex=0.1,
scaley=0.1,
scalez=1.0,
dimorder='TZCYX',
pixeltype=np.uint16,
swapxyaxes=True,
series=1):
"""ONLY FOR INTERNAL TESTING - DO NOT USE!
This f... | 61068659dfadedebec258644c188d57b2d95731e | 61,847 |
def mnist8m_data():
"""
Loads and returns data of MNIST8M dataset for all digits.
Returns
-------
data : list
A list of length = 1, where each element is a dictionary which contains ``train_outputs``,
``train_inputs``, ``test_outputs``, ``test_inputs``, and ``id``
References
... | 4302159bc205c9deb4c7fcdf04610246b07fdfd7 | 61,848 |
from typing import Dict
import pathlib
def dir_parser(path_to_dir: str) -> Dict[str, Dict[str, str]]:
"""
Parses the given directory, and returns the path, stem and suffix for files.
"""
files = pathlib.Path(path_to_dir).resolve().glob("*.*")
files_data = {}
for file in files:
files_... | 3b6c0ac172ad863470d492aa99713fab3ecf5d99 | 61,849 |
import os
import re
def get_core_dump_regs(path, pid, log):
""" Read all register values from a core dump
MacOS: all core dumps are stored as /cores/core.[pid]
Linux: the core dump is stored as a 'core' file in the cwd
Windows: If the given registry file was used, core dumps are stored in %LOCALAP... | c1c7eb0032cd2db67cd0fd3347d1a7ae259f4094 | 61,850 |
def logsumexp(x):
"""
Compute log(sum(exp(x))) avoiding over/underflow
"""
x = np.asarray(x)
m = x.max()
return np.log(np.sum(np.exp(x - m))) + m | f4fe60c804c7e97fec56050f43a42deadd4cdd2c | 61,851 |
def GetConfig(user_config):
"""Load and return benchmark config.
Args:
user_config: user supplied configuration (flags and config file)
Returns:
loaded benchmark configuration
"""
config = configs.LoadConfig(BENCHMARK_CONFIG, user_config, BENCHMARK_NAME)
if FLAGS['ycsb_client_vms'].present:
co... | 8fdcc5944252dfbbdc2fd5bd7dda7595c86396f0 | 61,852 |
def is_left(element1, element2):
"""Is element2 on the left of element1.
Args:
element1: XML element1 dump from UI.
element2: XML element2 dump from UI.
Returns:
Whether element2 is on the left of element1.
"""
[e1_x1, e1_y1, e1_x2, e1_y2] = get_element_bounds(element1)
[e2_x1, e2_y1, e2_x2, e... | e14ccc4c44b5fc1d5a282cf8e156ffa3bcda4cb1 | 61,853 |
def return_error_response():
"""Return error response sample"""
return make_response(jsonify({}), 403) | fa07ffc6c049962b129671a498a88f532b6be3ad | 61,854 |
import inspect
def is_redefined_dataclass_with_slots(old: type, new: type) -> bool:
"""Return True if `new` is the `old` dataclass redefined with `__slots__."""
# Must both be dataclasses.
if "__dataclass_fields__" not in old.__dict__ or "__dataclass_fields__" not in new.__dict__:
return False
... | c5c760bca752c0458139419f3c8e519ed8adad66 | 61,855 |
def get_total_characters(data):
"""
data - list
example:
data = [
[16,1027791027,993,GLORIA,MASTON,9,09/22/1938,F,W,*********7,*L**IA,******,**/**/****,F,*,8,2,0],
[16,1027791028,2412,GEORGE,MASTON,10,09/22/1938,M,W,*********8,*E**GE,******,**/**/****,M,*,8,2,0]
... | d1163615ee860be7991cce837f798eaf2d7d3781 | 61,856 |
def pyreq_rm_all_samples(httpreq_handler: HTTPRequestHandler, project_id: int, locale: str):
"""
Remove all samples in a locale of NLU model in Mix project by querying API endpoint
with DELETE method using "requests" package
API endpoint
::
DELETE f"nlu/api/v1/nlu/<PROJECT_ID>/interactions?... | e7db3dc160eda49f79922f6e639211f0aa90ceb0 | 61,857 |
def places(client, request,
geojson=None,
bbox=None,
buffer=None,
filter_category_ids=None,
filter_category_group_ids=None,
filters_custom=None,
limit=None,
sortby=None,
dry_ru... | 4b05a8d2f2d867517ca5b2b7a333eb4c46fa657b | 61,858 |
import numpy
def read_tmqm_properties(csvfile,xyzfile):
"""Reads the csv and xyz files comprising the tmqm dataset.
Args:
csvfile(str): Filename of the tmqm dataset csv file.
xyzfile(str): Filename of the tmqm dataset xyz file.
Returns:
numpy.ndarray: Numpy array of named propert... | 3161d437bd5288b0abdfcbcbb382cdfc2801f608 | 61,859 |
from .GSL import GSL as gsl
def gsl():
"""
The GSL package manager
"""
# grab the protocol
# and generate a facility
return gsl() | 469819fe050b9b17174c34ae5a99cf0ec22de8a0 | 61,860 |
def reference_selection_dop(target_position,receivers):
""" select reference receiver with lowest dop"""
dop_references = []
H_references = []
for idx in range(len(receivers)):
dop,H = calc_dop(target_position,receivers,receivers.keys()[idx])
dop_references.append(dop)
H_refere... | d5d2f9d311d8f0f831b0a5a7a793a5f22d42a844 | 61,861 |
import pickle
def BRN_fourier_integrand_splines(links, unwrap, Nvals=None, rvals=None, Bprop=None):
"""Return normalized, real space Green's function G(R;Rmax) for kinked WLC using
spline integration.
Parameters
----------
kvals : (29999,) array-like
k values for which to compute G(k; N) ... | ff5e483985787d955c137721196733866a84aa88 | 61,862 |
from lmfit import Parameters
from typing import OrderedDict
def residual_PM_IG_gamma(value_dict, time, f, data=None, weight=None, eps=None):
"""
derived the residual between model and data given params_local.
inputs:
value_dict dictionary with parameters, or lmfit.parameters instance.
... | 2844a38831753caea5cab77dcc89d8af78173a12 | 61,863 |
def merge_all(lst, strategy="smart", renderer="yaml", merge_lists=False):
"""
.. versionadded:: 2019.2.0
Merge a list of objects into each other in order
:type lst: Iterable
:param lst: List of objects to be merged.
:type strategy: String
:param strategy: Merge strategy. See utils.dictupd... | 1fd328f85a91599bf9956219a7256d477cb54480 | 61,864 |
import argparse
def cli_parse() -> tuple:
"""
Parse the command line arguments using the argparse library.
returns -- a named tuple with the arguments resolved and named.
"""
parser = argparse.ArgumentParser(description="Get headless chrome console log output from urls")
parser.add_argument... | 3d6d8bfdb0143ef52bf6ffc244139d7b5ecc3298 | 61,865 |
from typing import Optional
def __parseGregorian(date_str: str) -> Optional[str]:
"""Tries to parse the given string as a gregorian date.
Return the string 'DD.MM.YYYY' on success, `None`else.
Args:
date_str (str): The string to parse
Returns:
Optional[str]: The string 'DD.MM.YYYY' o... | 49c6dc46efa7367fde35d9937351d86db265e067 | 61,866 |
def ecc_overview():
"""
For lack of a better alternative redirect users to the main page
"""
return redirect(url_for('main.screen')) | c94242b9a1ed5f869bb8f0c1290de9c26843eaf2 | 61,867 |
def bprop_scalar_sign(x, out, dout): # pragma: no cover
"""Backpropagator for `scalar_sign`."""
return (zeros_like(dout),) | 138aa2813a62ac5f198b972882b158ef20707f31 | 61,868 |
from typing import List
def calculateFourCornersProduct(tiles: List[Tile]) -> int:
"""
Finds 4 corners tiles and multiplies IDs
"""
fourCornersProduct: int = 1
for i in range(len(tiles)):
top, bottom, left, right = False, False, False, False
for j in range(len(tiles)):
if i == j:
... | 74b7b934b176168206b95f36adcccb0c3789233a | 61,869 |
from typing import Union
import re
import random
async def urnotgod(ctx: Context) -> Union[Message, str]:
"""Responds with a variety of messages that oppose a person who claims to be god."""
if re.search(r"\b(i( )?('| a)?( )?m g( )?o( )?d)\b",
ctx.message.content.strip().lower()):
a... | c22356553d140c2abc8fc13e87605bc5c37cf87b | 61,870 |
def SiteParameters():
"""Create the site parameters for this site.
Returns:
dict containing SiteParameters for ChromeOS.
"""
# Chrome OS site parameters.
site_params = config_lib.DefaultSiteParameters()
# Helpers for constructing Chrome OS site parameters.
manifest_project = 'chromiumos/manifest'
... | 28a9a6f79ac319fecdfe5ef3ee861d34b5dfa442 | 61,871 |
import reproject
def project_to_header(fitsfile, header, **kwargs):
"""
Reproject an image to a header. Simple wrapper of
reproject.reproject_interp
Parameters
----------
fitsfile : string
a FITS file name
header : pyfits.Header
A pyfits Header instance with valid WCS to ... | 3a8719677dd7a1e2e8280a14d40a81f5850a54cf | 61,872 |
import tempfile
import shutil
import os
import json
def extract_subdir(path):
"""Extract the subdir from an artifact."""
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = str(tmpdir)
shutil.copy2(path, tmpdir)
path = os.path.join(tmpdir, path)
pkg_dir, pkg = os.path.spli... | 5f0d8d69afbef1652c2a8eb81ed52b637a947f53 | 61,873 |
from sys import path
def split_path(p):
"""
Split paths into segments
:param p: an path
:type p: str
:return: path segments
:rtype: List[str]
"""
segments = []
while True:
p, tail = path.split(p)
if tail:
segments.append(tail)
else:
... | 4473045f115829f84bd2afd6e32300cdb15758d5 | 61,874 |
def fetch_tae_df(preprocess=False):
"""
Fetch the `tae`_ dataset from OpenML and add `fairness_info`.
It contains information from teaching assistant (TA) evaluations.
at the University of Wisconsin--Madison.
The prediction task is a classification on the type
of rating a TA receives (1=Low, 2=... | 7dbb4fe32f280d0d6e1a3fef5ddbd805c1d3f293 | 61,875 |
def filter_data(data):
"""
Filters data for years after 2010 and data originating
from Syria.
Inputs:
data (pd.DataFrame): Input data with column "Year" and "Origin"
Returns:
data (pd.DataFrame): Filtered data
"""
if 'Origin' in data.columns:
data = data[(data.Year >... | 2daf6fbd815fcea9dd3c2712363cd99cdca62a34 | 61,876 |
def parse(tokens):
"""
Every time you generate a statement, backtrack to see if you have completed
an application.
"""
revlist = list(reversed(tokens))
stack = []
line = linecount(revlist)
col = 1
for tok in revlist:
col += 1
try:
if type(tok) == int:
... | 6d0b8b8efba06d9cf85c15bf6ad8b3bb002a733d | 61,877 |
def _mask_relv_scores(relv_scores, doc_masks):
"""
fill padded sentences with score of -np.inf for ranking purpose.
:param relv_scores: d_batch * max_ns_doc
:param doc_masks: d_batch * max_ns_doc
:return:
d_batch * max_ns_doc
"""
relv_mask = np.full_like(relv_scores, -np.inf)
... | 61bafb6b312e8d109fad4d97edc286adf631a986 | 61,878 |
def ridge(func, xlims, ylims, ds, *fargs, **kwargs):
"""Ridge detection
"""
x1, x2, A = repulsion_rate(func, xlims, ylims, ds, *fargs, plot=False, newfig=False, output=True, **kwargs)
X1, X2 = np.meshgrid(x1, x2)
V1, V2 = func([X1, X2], *fargs)
Ay, Ax = np.gradient(A, ds)
return x1, x2, (V2*Ax-V1*Ay)/(V1*... | 7cdcb2b1b75cb53aad2689c1e778495e492256e7 | 61,879 |
def strrep(strg,x):
""" A função retorna uma string com n repetições;
str, int -> str """
return strg*x | 6e3d59666778af9db781a11e6f48b61010e7de4d | 61,880 |
from datetime import datetime
def get_steps(image):
"""Get build steps for msan-libs-builder."""
timestamp = datetime.datetime.utcnow().strftime('%Y%m%d%H%M')
upload_name = 'msan-libs-' + timestamp + '.zip'
steps = build_base_images.get_steps([
'base-sanitizer-libs-builder',
'msan-libs-builder',... | bcb1be0a03f111f7448e60aeed1f4975447bd135 | 61,881 |
import logging
def prompt_for_description():
# TODO: Show the user the metadata version of the description and ask them if they'd like to change it.
"""
Prompt the user for a description.
:return: a user-supplied string that will be used as the bookmark's title
"""
while (desc := input("Provi... | 011bc4f89b369a4c6b98611a1d3a2ff2445d63b3 | 61,882 |
import collections
def get_top_n(predictions, n=10):
"""Return the top-N recommendation for each user from a set of predictions.
Args:
predictions(list of Prediction objects): The list of predictions, as
returned by the test method of an algorithm.
n(int): The number of recommendat... | 581da4680f5a122f2af86473ddd927353d4c579f | 61,883 |
def list_data_sources(*args, **kwargs):
"""
List all available data sources to use the hash_search API
Variables:
None
Arguments:
None
Data Block:
None
Result example:
[ <list of sources> ]
"""
return make_api_response(sorted(sources.keys())) | 25e7e371e5e43ccf874f1ab064fc8245a99d6884 | 61,884 |
def connect_to_mc_testing_db(forced_db_name='testing'):
"""
Get a DB object that is connected to the testing M&C database.
Parameters
----------
forced_db_name : str
Database name to use.
Returns
-------
DB object
An instance of the `DB` class providing access to the te... | a40ed3d9f61d1f1cac48761e114950ab7a2b84d0 | 61,885 |
def action_dispatcher(decoy: Decoy) -> ActionDispatcher:
"""Return a mock in the shape of an ActionDispatcher."""
return decoy.mock(cls=ActionDispatcher) | c7b7b28cc3454a71db25e61062f54ef801cbd677 | 61,886 |
import time
def get_token(session):
"""
Checks to see if there's a valid token for the current session and/or
whether an existing token is expired.
If expired, it grabs the refresh token.
"""
token_valid = False
token_info = session.get("token_info", {})
# Checking if the session a... | 2f14c9dd04285bdcb2c357095c5d631760afa8f0 | 61,887 |
from re import T
def leakyrelu_forward(input, negative_slope=0.1):
"""
forward pass of LeakyReLU
"""
out = T.leakyrelu(input, negative_slope)
return out | 8ee793d521be7911f028352f14a057626870d8e8 | 61,888 |
from typing import cast
import warnings
def register_type(
type_: type,
*,
widget_type: WidgetRef = None,
return_callback: ReturnCallback | None = None,
**options,
):
"""Register a ``widget_type`` to be used for all parameters with type ``type_``.
Parameters
----------
type_ : typ... | bdd933a4cc7fdfb8df31ea5cf804c34377d9cf85 | 61,889 |
from io import StringIO
def mixed_types_structured():
"""
Fixture providing hetergeneous input data with a structured dtype, along
with the associated structured array.
"""
data = StringIO(
(
"1000;2.4;alpha;-34\n"
"2000;3.1;beta;29\n"
"3500;9.9;gamma;12... | 7b489f526139d5012112169cf2ad4610df985038 | 61,890 |
def redirect_back(default='web.index', **kwargs):
"""
If next is not none, redirect next, if not, redirect index page
"""
for target in request.args.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return redirect(target)
return r... | b254e79d6d45dedcae5a9d5f5b022b28b8617d9e | 61,891 |
def take(n, iterable):
""" Yield n items of iterable.
Args:
n: an integer
iterable: an iterator
Returns:
A generator of the items.
Used by:
033, 044, 046
"""
return islice(iterable, n) | 5986d37ac38e7c7c3c635340aef367322b158044 | 61,892 |
def build_driver(executable_path: str = None, options: Options = None, headless=True, timeout=20) -> webdriver:
"""
Build Chrome driver instance
:param executable_path: str
:param options: Options
:param headless: bool
:param timeout: int
:return: webdriver
"""
kwargs = {}
if e... | e8c81398af59794ccf72010a5a450285ef95f401 | 61,893 |
def leaky_relu_gradient_op(node_A, node_B, alpha, ctx=None):
"""Computes the gradient of the ReLU function.
Parameters:
----
node_A : Node
LeakyRelu input.
node_B : Node
Previous gradient node.
alpha : float
LeakyRelu alpha
Returns:
----
A new Node instanc... | 86d3a045af456b52802fde94f29d941448c7b7b6 | 61,894 |
def getFssMaskLoss(cbsd_grant, constraint):
"""Gets the FSS mask loss for a FSS blocking protection constraint.
Args:
cbsd_grant: A CBSD grant of type |data.CbsdGrantInfo|.
constraint: The protection constraint of type |data.ProtectionConstraint|.
The constraint defines the FSS out of band left part,... | 270f883a3c002b7932caea5225296c32b6e906f6 | 61,895 |
def get_adversarial_data(dataset = "gtsrb",set_type = "Test_fgsm"):
"""
Get the numpy arrays of the dataset for test
Params:
set_type:
Test_fgsm -> Test set + adversarial examples from FGSM
Test_jsma -> Test set + adversarial examples from JSMA
Returns:
x_s... | e878cb16a531123680a26048f4d9953abad03378 | 61,896 |
def task_build():
"""Create full distribution."""
return {
'actions': ['python -m build'],
'task_dep': ['gitclean', 'mo', 'docs'],
} | 7112ab22031299207dfb9c14d2482ef52e975f89 | 61,897 |
def serve_pil_image(pil_img):
"""
see:
https://groups.google.com/forum/?fromgroups=#!topic/python-tornado/B19D6ll_uZE
http://stackoverflow.com/questions/7877282/how-to-send-image-generated-by-pil-to-browser
"""
img_io = cStringIO.StringIO()
pil_img.save(img_io, 'JPEG', quality=70)
... | 745c32a195208b0bda7300b2a92e0b7e987d50a4 | 61,898 |
def _feature_dtype(feature):
"""Returns a representation of a Feature's type as a tensorflow dtype."""
if feature.type == schema_pb2.BYTES:
return tf.string
elif feature.type == schema_pb2.INT:
return tf.int64
elif feature.type == schema_pb2.FLOAT:
return tf.float32
else:
raise ValueError('Fea... | c1be2ef5eb2c4074d1118cd6c944ed34a505fd39 | 61,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.