content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_flavor(disk=None, min_disk=None, min_ram=None, name=None, ram=None, region=None, rx_tx_factor=None, swap=None, vcpus=None):
"""
Use this data source to get the ID of an available OpenStack flavor.
"""
__args__ = dict()
__args__['disk'] = disk
__args__['minDisk'] = min_disk
__args__[... | f6689712d4bde04ae43bb4c999b04df34b1db089 | 3,643,205 |
from typing import Tuple
def deal_hands(deck: Deck) -> Tuple[Deck, Deck, Deck, Deck]:
"""Deal the cards in the deck into four hands"""
return (deck[0::4], deck[1::4], deck[2::4], deck[3::4]) | 151def07061a23df6c80f2be6d9015e3efbd515e | 3,643,206 |
import select
def add_new_publication_group(project):
"""
Create a new publication_group
POST data MUST be in JSON format
POST data SHOULD contain the following:
name: name for the group
published: publication status for the group, 0 meaning unpublished
"""
request_data = request.get... | 0890b71f972149bd860768dfeb5a377bd4fd28b0 | 3,643,207 |
def test_gmres_against_graph_scipy(n, tensor_type, dtype, error, preconditioner, solve_method):
"""
Feature: ALL TO ALL
Description: test cases for [N x N] X [N X 1]
Expectation: the result match scipy in graph
"""
if not _is_valid_platform(tensor_type):
return
# Input CSRTensor of... | 47fde403d403138dd1746cab532f7c7cf9b2f5a3 | 3,643,208 |
def wtime() -> float:
"""
:return: the current time as a floating point number.
"""
return MPI.Wtime() | 862b18fc688fd5e34ccfc7a2f986bdb2ceb98ed4 | 3,643,209 |
def survival_df(data, t_col="t", e_col="e", label_col="Y", exclude_col=[]):
"""
Transform original DataFrame to survival dataframe that would be used in model
training or predicting.
Parameters
----------
data: DataFrame
Survival data to be transformed.
t_col: str
Column na... | 8d35c27a75340d5c6535727e0e419fc0548d6094 | 3,643,210 |
from datetime import datetime
def get_date_today():
"""Get date today in str format such as 20201119. """
return datetime.today().strftime('%Y%m%d') | d5e69607dbf4b8c829cfe30ea0335f46c7d2512a | 3,643,211 |
import json
def generate_api_key(request):
"""Handles AJAX requests for a new API key."""
new_key = ApiUser.objects.get_unique_key()
return HttpResponse(json.dumps({'token' : new_key}), content_type="application/javascript") | 9e29a82c3a967d7a98537ec680a0a2bfe068a88c | 3,643,213 |
def input_output_details(interpreter):
"""
input_output_details:
Used to get the details from the interperter
"""
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
return input_details, output_details | 3024f2a6c91a533c3aff858ee3a1db11d360bb25 | 3,643,214 |
def charge_drone_battery(drone):
"""Handle the drone battery charging operation."""
battery_level = drone["State"]["Battery"]
if float(battery_level) < 95:
# Increase battery level
drone["State"]["Battery"] = float(battery_level) + 5
else:
# If battery >= 95 set battery level to ... | 2f7d955a44310215883ac5bed57fb27463a66315 | 3,643,215 |
def expirations(self, symbol, useDatetime=True, block: bool = True):
"""Gets list of available expiration dates for a symbol.
Calls the 'market/options/expirations.json' endpoint to get list of all
exp_dates available for some given equity.
Args:
symbol: Specify the stock symbol against wh... | 24a33bdac8da42be9433400b32c16fa4fb860766 | 3,643,216 |
from re import T
def track(name, x, direction=None):
"""
An identity function that registers hooks to
track the value and gradient of the specified tensor.
Here is an example of how to track an intermediate output ::
input = ...
conv1 = nnt.track('op', nnt.Conv2d(shape, 4, 3), 'all')... | 81ae80bc8b77c16d493befdb209fe648e9a07c96 | 3,643,217 |
from pathlib import Path
from typing import Callable
from datetime import datetime
def expected_l1_ls8_folder(
l1_ls8_folder: Path,
offset: Callable[[Path, str], str] = relative_offset,
organisation="usgs.gov",
collection="1",
l1_collection="1",
lineage=None,
):
"""
:param collection: ... | 16b934d3ea6c4a3daee3bde2a37bd5a7a48856b9 | 3,643,218 |
def fetchPackageNames(graphJson):
"""Parses serialized graph and returns all package names it uses
:param graphJson: Serialized graph
:type graphJson: dict
:rtyoe: list(str)
"""
packages = set()
def worker(graphData):
for node in graphData["nodes"]:
packages.add(node["p... | ccac1cfa1305d5d318cf3e2e3ed85d00fff7e56b | 3,643,219 |
def get_nc_BGrid_POP(grdfile, name='POP_NEP', \
xrange=(170,270), yrange=(240, 350)):
"""
grd = get_nc_BGrid_POP(grdfile)
Load Bgrid object for POP from netCDF file
"""
nc = pycnal.io.Dataset(grdfile)
lon_t = nc.variables['TLONG'][:]
lat_t = nc.variables['TLAT'][:... | 3ce9eec34f3332d21fce1ceaca2862faa69443d1 | 3,643,220 |
def types_and_shorthands():
"""a mapping from type names in the json doc to their
one letter short hands in the output of 'attr'
"""
return {
'int': 'i',
'uint': 'u',
'bool': 'b',
'decimal': 'd',
'color': 'c',
'string': 's',
'regex': 'r',
'... | 39f364677a8e2ee1d459599ba2574a8a4f4cd49e | 3,643,221 |
def to_region(obj):
"""Convert `obj` to instance of Region."""
if obj is not None and not isinstance(obj, Region):
return Region(*obj)
else:
return obj | da5412adcc182c97950465e3c4e3248be00f242b | 3,643,223 |
import PIL
def create_textures():
""" Create a list of images for sprites based on the global colors.
!!! SHOULD be able to add custom images in here instead of the general colors."""
texture_list = []
for color in colors:
image = PIL.Image.new('RGB', (WIDTH, HEIGHT), color)
texture_l... | 2652812d96157fc6f7d502e6ca39f4c4eee32dea | 3,643,224 |
import psutil
def check_if_process_is_running(process_name):
""""
Check if there is any running process that contains the given name process_name.
"""
# Iterate over the all the running process
for process in psutil.process_iter():
try:
# Check if process name contains the give... | 372cd2183b7250ce738157c986adb9a3abfdca84 | 3,643,225 |
import cProfile
import pstats
import io
from pstats import SortKey # type: ignore
import optparse
def exec_main_with_profiler(options: "optparse.Values") -> int:
"""Enable profiler."""
profile = cProfile.Profile()
profile.enable()
ret = exec_main(options)
profile.disable()
string_io = io.Str... | 8eefc801319d94081364218fc80500b710610f31 | 3,643,226 |
def put_text(image, text, point, scale, color, thickness):
"""Draws text in image.
# Arguments
image: Numpy array.
text: String. Text to be drawn.
point: Tuple of coordinates indicating the top corner of the text.
scale: Float. Scale of text.
color: Tuple of integers. RG... | aeab690da16577e7eff27b515cf9b682110716e9 | 3,643,227 |
def CreateRootRelativePath(self, path):
"""
Generate a path relative from the root
"""
result_path = self.engine_node.make_node(path)
return result_path.abspath() | 79053bb1bcb724e8ddf9bfc4b5b13b67be9227f0 | 3,643,229 |
import json
from typing import Mapping
def to_shape(shape_ser):
""" Deserializes a shape into a Shapely object - can handle WKT, GeoJSON,
Python dictionaries and Shapely types.
"""
if isinstance(shape_ser, str):
try:
# Redirecting stdout because there's a low level exception th... | d9a0975696ee48d816d5b61e7cc57c0547ff5033 | 3,643,231 |
import inspect
def _from_module(module, object):
"""
Return true if the given object is defined in the given module.
"""
if module is None:
return True
elif inspect.getmodule(object) is not None:
return module is inspect.getmodule(object)
elif inspect.isfunction(object):
... | 564157a4eb10b887b6b56c82d17d74557c233104 | 3,643,232 |
def _escape_pgpass(txt):
"""
Escape a fragment of a PostgreSQL .pgpass file.
"""
return txt.replace('\\', '\\\\').replace(':', '\\:') | 3926f683a2715ff1d41d8433b525793e8214f7a9 | 3,643,233 |
from typing import Dict
from typing import Set
from typing import List
import math
def gen_index(doc_term_map: Dict[PT.Word, Set[PT.IndexNum]],
dependency_map: Dict[PT.IndexNum, Count],
i: PT.IndexNum,
words: List[PT.Word]
) -> PT.PkgIndex:
"""Generate packa... | 4d82498309019f9bdc55fec8b6917576b2b0ff22 | 3,643,235 |
from typing import OrderedDict
def arr_to_dict(arr, ref_dict):
"""
Transform an array of data into a dictionary keyed by the same keys in
ref_dict, with data divided into chunks of the same length as in ref_dict.
Requires that the length of the array is the sum of the lengths of the
arrays in each... | 55339447226cdd2adafe714fa12e144c6b38faa2 | 3,643,236 |
def test_makecpt_truncated_zlow_zhigh(position):
"""
Use static color palette table that is truncated to z-low and z-high.
"""
fig = Figure()
makecpt(cmap="rainbow", truncate=[0.15, 0.85], series=[0, 1000])
fig.colorbar(cmap=True, frame=True, position=position)
return fig | f615d425d6433a6e4bc6dc0d8d5e18f2a0aa60c7 | 3,643,237 |
def captured_stdout():
"""Capture the output of sys.stdout:
with captured_stdout() as stdout:
print("hello")
self.assertEqual(stdout.getvalue(), "hello\n")
"""
return captured_output("stdout") | 9226c23c13ad86cc09f2c08ce1ffb44f324a1044 | 3,643,239 |
def login():
"""
Handles user authentication.
The hash of the password the user entered is compared to the hash in the database.
Also saves the user_id in the user's session.
"""
form = SignInForm()
banned = None
reason = None
if form.validate_on_submit():
user_id = form.user... | d2cea08572c7b1461cda490f063009bc139c7c3a | 3,643,240 |
def create_ipu_strategy(num_ipus,
fp_exceptions=False,
enable_recomputation=True,
min_remote_tensor_size=50000,
max_cross_replica_sum_buffer_size=10*1024*1024):
"""
Creates an IPU config and returns an IPU strategy r... | 2aaa76de946e43305cdb7e50b673e39a08e19a50 | 3,643,241 |
def run_pipeline(context, func, ast, func_signature,
pipeline=None, **kwargs):
"""
Run a bunch of AST transformers and visitors on the AST.
"""
# print __import__('ast').dump(ast)
pipeline = pipeline or context.numba_pipeline(context, func, ast,
... | 559d9c44ae143e49ff505fd76df0393bae56f012 | 3,643,242 |
from typing import Union
from typing import Optional
def convert_acc_data_to_g(
data: Union[AccDataFrame, ImuDataFrame], inplace: Optional[bool] = False
) -> Optional[Union[AccDataFrame, ImuDataFrame]]:
"""Convert acceleration data from :math:`m/s^2` to g.
Parameters
----------
data : :class:`~bi... | e9c60ebdc143cd8243fa7ec7ebde27f0ad5beceb | 3,643,243 |
def replace_by_one_rule(specific_rule: dict, sentence: str):
"""
This function replace a sentence with the given specific replacement dict.
:param specific_rule: A dict containing the replacement rule, where the keys are the words to use, the values will
be replaced by the keys.
:param sentence: A s... | 31a5bd58ef77d76c968c353dd493ba3357d5b506 | 3,643,244 |
def get_os(platform):
"""
Return the icon-name of the OS.
@type platform: C{string}
@param platform: A string that represents the platform of the
relay.
@rtype: C{string}
@return: The icon-name version of the OS of the relay.
"""
if platform:
for os in __OS_LIST:
... | 1610c373076a8fd9b647dad22c5ff39732d14fa7 | 3,643,245 |
def get_loglikelihood_fn(dd_s, f_l=f_l, f_h=f_h, n_f=n_f):
"""
x: parameter point
dd_s: signal system
"""
fs = jnp.linspace(f_l, f_h, n_f)
pad_low, pad_high = get_match_pads(fs)
def _ll(x):
# Unpack parameters into dark dress ones
gamma_s, rho_6T, M_chirp_MSUN, log10_q = x
... | da3843fd069a9c3a4646aa282c854bbd5557d74b | 3,643,246 |
def to_module_name(field):
"""_to_module_name(self, field: str) -> str
Convert module name to match syntax used in https://github.com/brendangregg/FlameGraph
Examples:
[unknown] -> [unknown]'
/usr/bin/firefox -> [firefox]
"""
if field != '[unknown]':
field = '[{}]'.format(fi... | 75e3fbb9a45710ea6dacecf5ecc34a5b9409606a | 3,643,247 |
def ApplyMomentum(variable, accumulation, learning_rate, gradient, momentum, use_nesterov=False, gradient_scale=1.0):
"""apply momentum"""
return apply_momentum.apply_momentum(variable, gradient, accumulation, learning_rate,
momentum, use_nesterov=use_nesterov, grad_scal... | f86b923e707c7f98d55cbf23a7ac17040bf2929c | 3,643,248 |
def init():
"""Return True if the plugin has loaded successfully."""
ok = True
if ok:
#g.registerHandler('start2',onStart2)
g.plugin_signon(__name__)
#serve_thread()
#g.app.remoteserver = ss = LeoSocketServer()
return ok | 74cc6395310d648b809b6df965700ca708581b5e | 3,643,249 |
def _fftconvolve_14(in1, in2, int2_fft, mode="same"):
"""
scipy routine scipy.signal.fftconvolve with kernel already fourier transformed
"""
in1 = signaltools.asarray(in1)
in2 = signaltools.asarray(in2)
if in1.ndim == in2.ndim == 0: # scalar inputs
return in1 * in2
elif not in1.ndi... | a32d85bb24fe0d1e64b12cdae14391c0c8e9e111 | 3,643,250 |
def solve_step(previous_solution_space, phase_space_position, step_num):
"""
Solves the differential equation across the full spectrum of trajectory angles and neutrino energies
:param previous_solution_space: solution to previous step of the differential equation
across all angles and energies, include... | 6678a9482453f2a43942f04085c892e8484e75cc | 3,643,251 |
def execute(*args, **kw):
"""Wrapper for ``Cursor#execute()``."""
return _m.connection["default"].cursor().execute(*args, **kw) | 8bb11436046e479c580c48eb42d4cb2b37372945 | 3,643,253 |
def get_login_client():
"""
Returns a LinodeLoginClient configured as per the config module in this
example project.
"""
return LinodeLoginClient(config.client_id, config.client_secret) | 786d3d6981f81afa95ed7de62544896982b17c58 | 3,643,254 |
import re
def detect_ascii_slice(lines):
# type: (List[str]) -> slice
"""
Given a list of strings, this will return the most likely positions of byte
positions. They are returned slice which should be able to extract the
columns from each line.
"""
for line in lines:
# if the conte... | 06cf3b9faa24f46aef37ae94495cbe129851bd7c | 3,643,255 |
import torch
def inception_model_pytorch():
"""The InceptionBlocks model the WebGME folks provided as a test case for deepforge."""
class InceptionBlocks(nn.Module):
def __init__(self):
super().__init__()
self.asymmetric_pad = nn.ZeroPad2d((0, 1, 0, 1))
self.conv2... | c70e4ea71eb38ae0d81b6985076a0c1588758df2 | 3,643,256 |
def project_in_2D(K, camera_pose, mesh, resolution_px):
"""
Project all 3D triangle vertices in the mesh into
the 2D image of given resolution
Parameters
----------
K: ndarray
Camera intrinsics matrix, 3x3
camera_pose: ndarray
Camera pose (inverse of extrinsics), 4x4
mes... | 9615d940fe083853e0bc179b79e1a19b7f9304bf | 3,643,259 |
from typing import Any
def forbidden(description: Any) -> APIGatewayProxyResult:
"""Return a response with FORBIDDEN status code."""
error = ForbiddenError(description)
return _build_response(error, HTTPStatus.FORBIDDEN) | 7b87e41081f1f7fa8f1e140a2c4d5ee597222193 | 3,643,260 |
from datetime import datetime
def str_2_datetime(p_str, fmt="%Y-%m-%d %H:%M:%S"):
""" 将字符串转换成日期
:param p_str: 原始时间字符串
:param fmt: 时间格式
:rtype: datetime.datetime
"""
# don't need to transform
if isinstance(p_str, datetime.datetime):
return p_str
if not isinstance(p_str, str):
... | 0fa86e0aebcf2c2ff53ceb26ae93ed762175ef03 | 3,643,261 |
def traitement(l):
"""Permet de retirer les cartes blanches inutiles"""
while l[-1][1] == 'nan':
del l[-1]
return l | d21a7d493a35fc53195315da9b824b0ca3c8ba25 | 3,643,262 |
from datetime import datetime
import bisect
def group_frames_by_track_date(frames):
"""Classify frames by track and date."""
hits = {}
grouped = {}
dates = {}
footprints = {}
metadata = {}
for h in frames:
if h['_id'] in hits: continue
fields = h['fields']['partial'][0]
... | 327a6357c5ce8fc9a54d27107e2cb43424dd7630 | 3,643,265 |
def generate_violin_figure(dataframe, columns, ytitle, legend_title=None):
""" Plot 2 columns of data as violin plot, grouped by block.
:param dataframe: Variance of projections.
:type dataframe: pandas.DataFrame
:param columns: 2 columns for the negative and the positive side of the violins.
:type... | 23baa052cf835ba55a43ffa496d606cccadb0c5b | 3,643,266 |
def measure_single(state, bit):
"""
Method one qubit one time
:param state:
:param bit:
:return:
"""
n = len(state.shape)
axis = list(range(n))
axis.remove(n - 1 - bit)
probs = np.sum(np.abs(state) ** 2, axis=tuple(axis))
rnd = np.random.rand()
# measure single bit
i... | ff2c18039e6900febaa731f9a3db9f16b797e18b | 3,643,267 |
def anchor_to_offset(anchors, ground_truth):
"""Encodes the anchor regression predictions with the
ground truth.
Args:
anchors: A numpy array of shape (N, 6) representing
the generated anchors.
ground_truth: A numpy array of shape (6,) containing
the label boxes in t... | 3aced37f0838d2ab4f90ce0e212747111fc87876 | 3,643,268 |
def horizontal_flip(img_array):
"""Flip image horizontally."""
img_array = cv2.flip(img_array, 1)
return img_array | 7f53442b072127e5c02253aefabcc8e7bd422504 | 3,643,269 |
def chunker(file_path):
"""
Read a block of lines from a file
:param file_path:
:return:
"""
words = []
with open(file_path, 'r') as file_object:
for word in file_object:
word = word.strip()
if word:
words.append(word)
return words | a60b6f3cc7003955ae6acd8ac5e74574cdbd5976 | 3,643,270 |
def legalize_names(varnames):
"""returns a dictionary for conversion of variable names to legal
parameter names.
"""
var_map = {}
for var in varnames:
new_name = var.replace("_", "__").replace("$", "_").replace(".", "_")
assert new_name not in var_map
var_map[var] = new_name
... | ad8e9ef3394d4ac3cfa80198f488c1834bd227fc | 3,643,272 |
def _IsUidUsed(uid):
"""Check if there is any process in the system running with the given user-id
@type uid: integer
@param uid: the user-id to be checked.
"""
pgrep_command = [constants.PGREP, "-u", uid]
result = utils.RunCmd(pgrep_command)
if result.exit_code == 0:
return True
elif result.exit... | 8a4e529a98298ec4c2d9df30c6fc28a91c124edd | 3,643,273 |
def mobilenetv3_large(data_channel):
"""
Constructs a MobileNetV3-Large model
"""
cfgs = [
# k, t, c, SE, NL, s
[3, 16, 16, 0, 0, 1],
[3, 64, 24, 0, 0, 2],
[3, 72, 24, 0, 0, 1],
[5, 72, 40, 1, 0, 2],
[5, 120, 40, 1, 0, 1],
[5, 120, 40, 1, 0, 1]... | ec14d6628bf9e69f05a79f4207a32e00fbae1b8b | 3,643,274 |
def ravel_lom_dims(tensor, name='ravel_lom_dims'):
"""Assumes LOM is in the last 3 dims."""
return tf.reshape(tensor, tensor.shape_as_list()[:-3] + [-1], name=name) | f0f56c4f747b4a40e63bddbb7d6dd3452044151f | 3,643,275 |
def run_cv(cfg, df, horiz, freq, cv_start, cv_stride=1, dc_dict=None,
metric="smape"):
"""Run a sliding-window temporal cross-validation (aka backtest) using a
given forecasting function (`func`).
"""
y = df["demand"].values
# allow only 1D time-series arrays
assert(y.ndim == 1)
... | cb95657aeaa4cb74c6252d46029db88c6be18ddb | 3,643,276 |
import pyarrow as pa
def ST_Area(geos):
"""
Calculate the 2D Cartesian (planar) area of geometry.
:type geos: Series(dtype: object)
:param geos: Geometries in WKB form.
:rtype: Series(dtype: float64)
:return: The value that represents the area of geometry.
:example:
>>> import pan... | ae69ec90c9e5c54c5f6afa468d6cb1212e64eaf4 | 3,643,277 |
from operator import matmul
def P_from_K_R_t(K, R, t):
"""Returns the 3x4 projection matrix P = K [R | t]."""
K = K.astype(np.float64)
R = R.astype(np.float64)
t = t.astype(np.float64)
return matmul(K, np.column_stack((R, t))) | 0304ea513df81a67e653ba1e3516c39ec38f94ad | 3,643,279 |
from typing import List
from typing import Union
from typing import Callable
from typing import Type
from typing import OrderedDict
from typing import Any
def multi_value_precondition(parameter_selector: List[Union[int, str]], predicate: Callable[..., bool],
exception_factory: Union[Type[... | 97632d8e77858e3d854a8f610fae772a8a6c3c5b | 3,643,280 |
from operator import itemgetter
import json
def activity_list_retrieve_view(request): # activityListRetrieve
"""
Retrieve activity so we can populate the news page
:param request:
:return:
"""
status = ''
activity_list = []
activity_manager = ActivityManager()
activity_notice_seed... | 4ab7d7e2cd5c0a3c812b6ec1729efda19fb87ced | 3,643,281 |
import http
from typing import Optional
def edit_action(
request: http.HttpRequest,
pk: int,
workflow: Optional[models.Workflow] = None,
action: Optional[models.Action] = None,
) -> http.HttpResponse:
"""Invoke the specific edit view.
:param request: Request object
:param pk: Action PK
... | 43f128dfe2abd47c1c6cf78d667343d9086aeb98 | 3,643,283 |
from typing import Any
from typing import Set
from typing import KeysView
def to_set(data: Any) -> Set[Any]:
"""Convert data to a set. A single None value will be converted to the empty set.
```python
x = fe.util.to_set(None) # set()
x = fe.util.to_set([None]) # {None}
x = fe.util.to_set(7) # ... | df2649d0b7c7c2323984edd3eeea76eff0eab4d2 | 3,643,284 |
def Pei92(wavelength, Av, z, Rv=-99.0, ext_law="smc", Xcut=False):
"""
Extinction laws from Pei 1992 article
Parameters
----------
wavelength: `array` or `float`
wavlength in angstroms
Av: `float`
amount of extinction in the V band
z: `float`
redshift
Rv: `flo... | 9b0b9690f548319ffed7fcc964dc0e651828371f | 3,643,285 |
import mimetypes
def get_mimetype(path):
"""
Get (guess) the mimetype of a file.
"""
mimetype, _ = mimetypes.guess_type(path)
return mimetype | 7677259fcdf052f9647fe41e4b4cb71d83ea50cd | 3,643,287 |
import select
async def read_clients_epics(
client_id: int = None, session: Session = Depends(get_session)
):
"""Get epics from a client_id"""
statement = (
select(Client.id, Client.name, Epic.name)
.select_from(Client)
.join(Epic)
.where(Client.id == client_id)
)
r... | e5af5d2776a941cde83ea341143732bcdb67da2a | 3,643,288 |
def id_number_checksum(gd):
"""
Calculates a Swedish ID number checksum, using the Luhn algorithm
"""
n = s = 0
for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']):
# Letter? It's an interimspersonnummer and we substitute the letter
# with 1.
if c.isalpha():
... | bbf0a9fa7f6ed2c2bfc414173fd2ac9e9c1d8835 | 3,643,289 |
def date_loss_l1(pred,
target_min,
target_max,
mask):
"""L1 loss function for dates."""
pred = jnp.squeeze(pred, 0)
loss = 0.
loss += jnp.abs(pred - target_min) * jnp.less(pred, target_min).astype(
pred.dtype)
loss += jnp.abs(pred - target_max) * jnp.g... | 12f0d5a1f7efbb8d51501c4d3fe41d192528010d | 3,643,290 |
def new_single_genres(genres, val):
"""Takes the genres list and returns only one genre back if multiple genres are present
Also has the parameter val with values "high" and "low"
High picks the genres belonging to the existing genres with the highest examples count
Low picks the genres belonging to the... | 0cabcb93548007b3cd87dc40740da5d0f4614867 | 3,643,291 |
def roparameter(cosphi, hist, s_cosphi=0.25):
"""
...
Parameters
----------
cosphi : ...
hist : ...
s_cosphi : ...
Returns
-------
...
"""
perp=(np.abs(cosphi)>1.-... | c9f30db90482600c50a9369139fc75c046d57e40 | 3,643,293 |
def polyfill_bbox(
min_lng, max_lng, min_lat, max_lat, min_resolution=0, max_resolution=30
):
"""Polyfill a planar bounding box with compact s2 cells between resolution levels"""
check_valid_polyfill_resolution(min_resolution, max_resolution)
rc = s2sphere.RegionCoverer()
rc.min_level = min_resolu... | d6c2cb0d3f0d7a9eea05a456beda96a1a646e306 | 3,643,295 |
from lvmspec.qa import qalib
import copy
def qa_skysub(param, frame, skymodel, quick_look=False):
"""Calculate QA on SkySubtraction
Note: Pixels rejected in generating the SkyModel (as above), are
not rejected in the stats calculated here. Would need to carry
along current_ivar to do so.
Args:
... | 3b53f99ae4936fa6870dc8020d677ffddcb2d4ef | 3,643,296 |
def _code_to_symbol(code):
"""
生成symbol代码标志
"""
if code in ct.INDEX_LABELS:
return ct.INDEX_LIST[code]
else:
if len(code) != 6 :
return ''
else:
return 'sh%s'%code if code[:1] in ['5', '6', '9'] else 'sz%s'%code | 4b783adad975246c9d6722f6eeeb95a2388d1823 | 3,643,297 |
def gesv(a, b):
"""Solve a linear matrix equation using cusolverDn<t>getr[fs]().
Computes the solution to a system of linear equation ``ax = b``.
Args:
a (cupy.ndarray): The matrix with dimension ``(M, M)``.
b (cupy.ndarray): The matrix with dimension ``(M)`` or ``(M, K)``.
Returns:
... | 333f06bd8f91bdfde5526c80894c284580074bb5 | 3,643,298 |
def del_none(d):
"""
Delete dict keys with None values, and empty lists, recursively.
"""
for key, value in d.items():
if value is None or (isinstance(value, list) and len(value) == 0):
del d[key]
elif isinstance(value, dict):
del_none(value)
return d | 46cf9e331c633f5f69b980f3b10c96306d3478c2 | 3,643,299 |
def aes_block(ciphertext, key):
"""Uses the AES algorithm in ECB mode to decrypt a 16-byte ciphertext
block with a given key of the same length.
Keyword arguments:
ciphertext -- the byte string to be decrypted
key -- the byte string key
"""
if len(ciphertext) != 16:
raise Val... | b0b894bcf860c92b46235ce45b8fd6c8c045b1ca | 3,643,300 |
import logging
def getLogger(*args, **kwargs):
"""
Wrapper around ``logging.getLogger`` that respects `overrideLogLevel <#setOverrideLogLevel>`_.
"""
logger = logging.getLogger(*args, **kwargs)
if _overrideLogLevel is not None:
logger.setLevel(logging.NOTSET)
return logger | f4ae90925e8bd20a63997e2e5e04924aeeafbcaa | 3,643,301 |
def split_metadata_string(text, chunk_length=None):
"""Split string by length.
Split text to chunks by entered length.
Example:
```python
text = "ABCDEFGHIJKLM"
result = split_metadata_string(text, 3)
print(result)
>>> ['ABC', 'DEF', 'GHI', 'JKL']
```
Ar... | c2e97aa768f64f02ef1a691dfadce3dd9fe5538a | 3,643,302 |
def load_kimmel_data(root_data_path,
flag_size_factor=True, total_ct_per_cell=1e4,
flag_log1p=True):
"""Load normalized data from Kimmel et al, GR, 2019
1. Size factor normalization to counts per 1 million (total_ct_per_cell)
2. log(x+1) transform
Args:
... | 324f5779c180811db0b9316125553f7089d5a34b | 3,643,303 |
import requests
def get_coupon_page() -> bytes:
"""
Gets the coupon page HTML
"""
try:
response = requests.get(COUPONESE_DOMINOS_URL)
return response.content
except RequestException as e:
bot.logger.error(e.response.content)
return None | 919cd65ec9e4f0af7b06a79c8aa962f164fb7af6 | 3,643,304 |
def get_program_similarity(fingerprint_a, fingerprint_b):
"""Find similarity between fingerprint of two programs.
A fingerprint is a subset of k-gram hashes generated from program. Each of
the k-gram hashes is formed by hashing a substring of length K and hence
fingerprint is indirectly based on substr... | c3cc3def2d17657c266e09ce5b05da773e1f6f1a | 3,643,305 |
def linear_transformation(x, y_min, y_max):
"""
x : the range to be transformed
y_min, y_max : lower and upper boundaries for the range into which x
is transformed to
Returns y = f(x), f(x) = m * x + b
"""
x_min = np.min(x)
x_max = np.max(x)
if x_min == x_max:
x_max = x_min *... | ddd6da6b006888a43711dc391948ffce96bd0a81 | 3,643,308 |
import random
def resize_image(image, desired_width=768, desired_height=384, random_pad=False):
"""Resizes an image keeping the aspect ratio mostly unchanged.
Returns:
image: the resized image
window: (x1, y1, x2, y2). If max_dim is provided, padding might
be inserted in the returned image. I... | 9744bb52c58e1049c8cbd6ce9e1f1864f64ac3c5 | 3,643,309 |
def get_state(*names):
"""
Return a list of the values of the given state keys
Paramters
---------
*names : *str
List of name of state values to retreive
Returns
-------
[any, ...]
List of value matching the requested state property names
"""
_app = get_app_inst... | 8f863bdb9f578eb0e12731d1b752f197d4476a2c | 3,643,310 |
def ver_datos_basicos(request, anexo_id):
"""
Visualización de los datos básicos de un anexo.
"""
anexo = __get_anexo(request, anexo_id)
parts = anexo.get_cue_parts()
return my_render(request, 'registro/anexo/ver_datos.html', {
'template': 'registro/anexo/ver_datos_basicos.html... | 63cb5222cad1fa702dd5bd2fc7a14c38f4b71d65 | 3,643,311 |
def fill_sections(source, sections):
"""
>>> fill_sections(\
' /* Begin User Code Section: foobar *//* End User Code Section: foobar */', {'foobar': 'barbaz'})
' /* Begin User Code Section: foobar */\\n barbaz\\n /* End User Code Section: foobar */'
"""
def repl(matches):
indent_... | 6a76826f45aa0880039e70ad6bb41aa93442976b | 3,643,312 |
def CNOT(n):
"""CNOT gate on 2-Qubit system with control qubit = 0 and target qubit = 1"""
x=np.copy(I4)
t=np.copy(x[2,])
x[2,]=x[3,]
x[3,]=t
return x.dot(n) | af72004c9dd6f4a970e95d1da48a9d3776bd730b | 3,643,313 |
import tokenize
def parse(s):
"""Parse a single string. This is just a convenience function."""
return pogo(parseSingleExpression(tokenize(s),
identity_cont)) | 9a7a2f4b2afd1daf22e6d2258e13ac9d13d380b3 | 3,643,314 |
def link_match_check(row):
"""
Indicating that link is already in database
"""
all_objects = Post.objects.all()
try:
row_link = row.a["href"]
for object_founded in all_objects:
return row_link == object_founded.link
except TypeError:
return False | 2d55554248791b8edb5ec6080bc4c4f152a6a23a | 3,643,315 |
def merge_s2_threshold(log_area, gap_thresholds):
"""Return gap threshold for log_area of the merged S2
with linear interpolation given the points in gap_thresholds
:param log_area: Log 10 area of the merged S2
:param gap_thresholds: tuple (n, 2) of fix points for interpolation
"""
for i, (a1, g... | 36dd06c8af828e3dc2ef5f1048046039feaa6c21 | 3,643,316 |
def rename_indatabet_cols(df_orig):
"""
"""
df = df_orig.copy(deep=True)
odds_cols = {'odds_awin_pinn': 'awinOddsPinnIndatabet',
'odds_draw_pinn': 'drawOddsPinnIndatabet',
'odds_hwin_pinn': 'hwinOddsPinnIndatabet',
'odds_awin_bet365': 'awinOddsBet365In... | a07e7c9757e1b207528f7b7fda63e06a1dced47a | 3,643,317 |
import urllib
def get_market_updates(symbols, special_tags):
"""
Get current yahoo quote.
'special_tags' is a list of tags. More info about tags can be found at
http://www.gummy-stuff.org/Yahoo-data.htm
Returns a DataFrame
"""
if isinstance(symbols, str):
sym_list = symbols
e... | d3dd970ef513a131147cc687cb9ad2076ee0b0ff | 3,643,318 |
def HLRBRep_SurfaceTool_Torus(*args):
"""
:param S:
:type S: Standard_Address
:rtype: gp_Torus
"""
return _HLRBRep.HLRBRep_SurfaceTool_Torus(*args) | 46aa63882557b1a2e13cb245f81fcf9871903a18 | 3,643,319 |
def load_augmentation_class():
"""
Loads the user augmentation class.
Similar in spirit to django.contrib.auth.load_backend
"""
try:
class_name = AUTH.USER_AUGMENTOR.get()
i = class_name.rfind('.')
module, attr = class_name[:i], class_name[i + 1:]
mod = import_module(module)
klass = getatt... | 16f737a2687e0b2e5002982adcafef9c32c82e36 | 3,643,320 |
def FieldTypeFor(descriptor, field_desc, nullable):
"""Returns the Javascript type for a given field descriptor.
Args:
descriptor: The descriptor module from the protobuf package, e.g.
google.protobuf.descriptor.
field_desc: A field descriptor for a particular field in a message.
nullable: Whet... | 0e2c2d48dc22d209053d06fda354e4df9912144a | 3,643,321 |
def unadmin(bot, input):
"""Removes person from admins list, owner only"""
if not input.owner: return False
bot.config.set_del('admins',input.group(2).lower())
bot.reply("Unadmin'd {0}".format(input.group(2))) | 1a74ab0a3d3d1b41dd6d1f065b71a48557af84ed | 3,643,322 |
def sim_beta_ratio(table, threshold, prior_strength, hyperparam, N,
return_bayes=False):
"""
Calculates simulated ratios of match probabilites using a beta
distribution and returns corresponding means and 95% credible
intervals, posterior parameters, Bayes factor
Parameters
-... | 01e61719dbecb89e40bdf2688578d493c951591c | 3,643,323 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.