content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def attention_lm_moe_prepare_decoder(targets, hparams):
"""Prepare one shard of the model for the decoder.
Args:
targets: a Tensor.
hparams: run hyperparameters
Returns:
decoder_input: a Tensor, bottom of decoder stack
decoder_self_attention_bias: a Tensor, containing large negative values
t... | 598a7b3b03a596478fd7c30b1d7b23a47e1fc1d6 | 3,622,903 |
import math
def lat_meters(lat: float) -> float:
"""
Transform latitude degree to meters.
Parameters
----------
lat : float
This represent latitude value.
Returns
-------
float
Represents the corresponding latitude value in meters.
Examples
--------
Latit... | c31025552778b0039079d33e134e0b19077b83d4 | 3,622,904 |
def make_rpc_report(repo_dir, old_commit, new_commit,
args):
"""Create initial RST report header for OpenStack-Ansible."""
# Do we have a valid commit range?
# NOTE:
# An exception is thrown by osa_differ if these two commits
# are the the same, but it is sometimes necessary to ... | cc7900f21e6e80dc7da2ee0063032c51579eafc5 | 3,622,905 |
def generic_blockvisibility_workflow(visfunction, vis_list, additive=True, *args, **kwargs):
""" Definition of interface for create_generic_blockvisibility_graph_visfunction.
:func visfunction: Function to be applied
:param vis_list: List of vis_graphs
:param additive: Add to existing visibility? (True... | 62364879a081cc39289dada0c60f839e9082ca99 | 3,622,906 |
import re
def year_parse(s):
"""Parses a year from a string."""
regex = r"((?:19|20)\d{2})(?:$|[-/]\d{2}[-/]\d{2})"
try:
year = int(re.findall(regex, ustr(s))[0])
except IndexError:
year = None
return year | b4070f3842cb4d9d68f5b69d31a8088e2add5e38 | 3,622,907 |
def recompute_etas_P(D, dataloader):
"""Recomputes etas integrating dD/dx over P
"""
etas = 0
n_samples = 0
for data in dataloader:
_, _, Ep_grad2 = compute_objective_terms(data, D, need_penalty_terms=True)
# Only 1 term, i.e. integrate over P ((P+Q)/2 would work also)
etas +... | a33724c569e0843c6b646b39a3ffd031b4fed734 | 3,622,908 |
def parse(fp, encoding='utf8'):
"""
Read PSD file from file-like object.
:rtype: ParseResult
Example::
from psd_tools.reader.reader import parse
with open('/path/to/input.psd', 'rb') as fp:
result = parse(fp)
"""
header = psd_tools.reader.header.read(fp)
retu... | 063dcbb6be0d3fc085898fd1db353ac1f91dfeb9 | 3,622,909 |
def median(x):
"""返回数据 x 的中位数"""
n = len(x)
sorted_x = sorted(x)
midpoint = n // 2
if n % 2 == 0:
# 如果是奇数,返回中间值
return sorted_x[midpoint]
else:
# 如果是偶数,返回中间两个值的均值
lo = midpoint - 1
hi = midpoint
return (sorted_x[lo] + sorted_x[hi]) / 2 | f44d593f38ec14418d72513a68b4b8e2921afa5c | 3,622,910 |
def lost_to_gaia(gaia_ids):
"""Find villagers lost to specified gaia object types."""
query = """
select units.match_id, units.initial_player_number as number, units.destroyed::interval(0) as timestamp
from object_instances as gaia join object_instances as units on units.destroyed_by_instance_id... | 5c0dcba0c9852ce4a915a38a8b0fd24532479d16 | 3,622,911 |
def getFilteredLexicon(lexicondict, allwords):
""" Returns a lexicon with just the necessary words.
Assumes all wanted keys exist in the given lexicon """
return { word: lexicondict[word] for word in allwords } | db3c58b71df848ef5b1d49ebdd4670a552481c64 | 3,622,912 |
def post(item):
""" blog item """
name = item.split(".")[0] # No extension
return render_template(
"post.html",
html_tab_title=f"Villoro - {item}".replace(".html", ""),
**u.get_content()["blog"][name],
) | 298858dc75fb674c8ffa000dc0f22910bd430f14 | 3,622,913 |
def relu(x, name=None):
"""
relu activation.
.. math::
out = max(x, 0)
Parameters:
x (Tensor): The input Tensor with data type float32, float64.
name (str, optional): Name for the operation (optional, default is None).
For more information, please refer to :ref:`ap... | 119b51f4684018c0a1a7a9c0ea687fd1b5a34779 | 3,622,914 |
import unittest
def filter_suite(condition, suite):
"""Return tests for which ``condition`` is True in ``suite``.
:param condition: A callable receiving a test and returning True if the
test should be kept.
:param suite: A test suite that can be iterated. It contains either tests
or suit... | 9131d49d3f87a117d2b9625d521e932db2666860 | 3,622,915 |
def build_loss_fun():
"""Build the loss function."""
return get_loss_fun()() | d7b193191fa947c32729e7f396469e681d3f4e57 | 3,622,916 |
def deleteAccident(id=None, object=None):
""" delete the photos then delete the Accident
perm : object = the Accident object"""
if id:
accident = Accident.query.get(id)
elif object:
accident = object
if not accident:
return False
# delete the photos
deletePhoto(accident)
# delete the person
db.sessi... | f49d37b03ec26614934d649eb1a1f5dbd2320d82 | 3,622,917 |
def perms_canonical_labels(p, e=None):
"""
Relabel a list with a common conjugation such that two conjugated
lists are relabeled the same way.
INPUT:
- ``p`` is a list of at least 2 permutations
- ``e`` is None or a list of integer in the domain of the
permutations. If provided, then th... | 03e3450469239de160b0b596e9da7347ca2713a1 | 3,622,918 |
def trotterization(hamiltonian, time, trotter_order):
"""
Uses first order Trotter-Suzuki decomposition:
exp(iHt) = (exp(ih_1 t)exp(ih_2 t)exp(ih_n t))^N + O(t*delta_t),
where H = h_1 * h_2 * ... * h_n, delta_t is t/N
:param hamiltonian: is the Hamiltonian (H in the formula)
:param time: is... | 10041795dd82f5fea813870d9d7beb468e96c86c | 3,622,919 |
import torch
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (images,
triplets_local_indexes, triplets_global_indexes).
triplets_local_indexes are the indexes referring to each triplet within images.
triplets_global_indexes are the global indexes of each image... | c7267579e6e7f4fa54cca951b5cad15e4ce5283a | 3,622,921 |
def bit_size_decorator (bs) :
"""Return a decorator for `dusort`-ing by bit-size `bs`.
Integral byte sizes compare before sub-byte sizes, even sizes compare
before odd sizes, larger values compare before smaller values.
"""
return - byte_alignment ((bs + 4) >> 3), - bs | e8e3e1df1ea7aba24c6ecbff210c65b45c31696c | 3,622,922 |
def wavelength2rgb(wavelength: float, gamma: float = 0.8) -> tuple[float, float, float]:
"""
http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
This converts a given wavelength into an approximate RGB value.
The given wavelength is in nanometers.
The range of wavelength is 380 nm through 750 nm.
... | 37317a5235bb3450ebf991439a7ca5ed40ede062 | 3,622,924 |
def bytes_to_long(in_bytes):
"""Converts a byte string into a long"""
hexstr = ''.join(["%0.2x" % ord(byte) for byte in in_bytes])
return int(hexstr, 16) | 89d82a72226457c3a1ac1438cab1071d3cbcd62d | 3,622,925 |
import logging
def addfile_handler(logger, filename=FILE_NAME, level=LOG_LEVEL, write_headers=False):
"""
Add a file handler to the input.
Parameters
----------
logger : logging.Logger or logging.Logger
Logger where to add the file handler.
filename : str, optional
Name of the... | b097f8dd29f4d888481c60489023591cc1dc852b | 3,622,926 |
def func():
"""Return a new matrix of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty matrix.
dtype : data-type, optional
Desired output data-type.
order : {'C', 'F'}, optional
Whether to store multi... | c48914045c296b25fbfef0f1e409b7bc40b1a677 | 3,622,928 |
def gcp_connect(module, provider, get_driver, user_agent_product, user_agent_version):
"""Return a Google libcloud driver connection."""
if not HAS_LIBCLOUD_BASE:
module.fail_json(msg='libcloud must be installed to use this module')
creds = _get_gcp_credentials(module,
... | da9118fbc52f2d712e85d8218100f8f74e8e72ad | 3,622,929 |
def create_c1_opt(optimizer_config, exp):
"""
Create an object for C1 optimal control.
Parameters
----------
optimizer_config : str
File path to a hjson file containing the C1 configuration.
lindblad : boolean
Include lindbladian dynamics.
Returns
-------
C1
... | e073f3f27dedb122a77baccd34725ec45faaae7a | 3,622,930 |
def choose_stance(info: GameInfo, my_car: Car, team, last_sent):
""" High level assignment of "stances"
Upon entering a stance, each Marujo is able to decide a few things to do
"""
ball = info.ball
teammates = info.get_teammates(my_car)
my_team = [my_car] + teammates
their_goal = ground(... | a4f131811916266172d89c3363e1727c40bb8d34 | 3,622,932 |
def javadoc(metadata, indent = 4):
"""
Returns a function to format a markdown syntax text block as a
javadoc comment section, given a set of metadata
Args:
metadata: A Metadata instance, representing the top-level root
of the metadata for cross-referencing
indent: baseline level of indentation f... | 2c05afa2bc20f622d2aedd60d4fc0ba4abd13725 | 3,622,933 |
import math
def deg2tilecoord(lat_deg, lon_deg, zoom):
"""
Convert latitude,longitude coordinates in degrees into tile coordinates for
given zoom.
"""
try:
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - math.log(... | 2328cba962f958dada14a559492bbf4c908e4718 | 3,622,934 |
def clean_data(row: dict) -> dict:
"""
Function to clean film permit row.
"""
eventid = row['eventid']
addresses = _split_addresses(row['parkingheld'])
addresses = [
_get_intersections(address) for address in addresses
]
startdate = _clean_datetime(row['startdatetime'])
endd... | e63e47f0795c4c1b3ec3df59d289e1b8e1f6d16a | 3,622,936 |
def project_featurestore():
"""
Gets the project's featurestore name (project_featurestore)
Returns:
the project's featurestore name
"""
project_name = hdfs.project_name()
featurestore_name = project_name.lower() + constants.FEATURE_STORE.FEATURESTORE_SUFFIX
return featurestore_nam... | f1669739f6ac5e443e6cf941122cb5c4263feb2c | 3,622,937 |
def find():
"""
List all busses and returns a list of baseboards detected
"""
l = []
try:
for b in usb.core.find(find_all=True, idVendor=FISCHER_LT_VENDOR, idProduct=FISCHER_LT_PRODUCT):
l.append(usb_device(b))
except:
pass
return l | 46b4c6acb32a20f4b1ad1b90225bc90ef91f3c3a | 3,622,938 |
def cli(ctx, library_id, access_in="", modify_in="", add_in="", manage_in=""):
"""Set the permissions for a library. Note: it will override all security for this library even if you leave out a permission type.
Output:
General information about the library
"""
return ctx.gi.libraries.set_library_permi... | 833f828b5405b29d577a8859da8a895791da22bc | 3,622,940 |
def type_encoding_table(tblname, arr):
"""Table of strings of all instructions."""
return string_table(tblname, (x[1] for x in arr)) | a9cdbdfd03e1a09269236f624c9aaa637885a615 | 3,622,941 |
def controller_unlock_foreign_drives(handle, controller_type,
controller_slot, security_key,
server_id=1):
"""
Unlocks on the given controller, drives encrypted on another controller.
Args:
handle (ImcHandle)
controll... | ad71c17d0f16608729e042edea900ed40e91a0b5 | 3,622,942 |
def create(i):
"""
Input: {
data_uoa - virtual environment name
(force_detect) - if 'yes' force to detect installed python again
(template) - if !='', use scripts from this venv.template entry
at the end of venv creation.
... | 0b125919f2e7fa079f2bce120a089e334de84818 | 3,622,943 |
def _item_to_zone(iterator, resource):
"""Convert a JSON managed zone to the native object.
:type iterator: :class:`~google.cloud.iterator.Iterator`
:param iterator: The iterator that has retrieved the item.
:type resource: dict
:param resource: An item to be converted to a managed zone.
:rty... | 97c8b6cc928239a1da33ef6cfa93b214cf025a77 | 3,622,944 |
def get_sklearn_primitives_names():
"""Helper to return names of all sklearn primitives."""
return [x for x in get_primitive_names() if ".SKlearn" in x] | afc446098c2e95f5c764d1038ac45a13ea219c0a | 3,622,945 |
def get_users():
"""Retrieve information about users"""
return "get users" | 40e2c1e8046beaa6d1b6f7875c2a3e3f7bad8e69 | 3,622,946 |
import grp
def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
"""Upgrade a SAM group.
:param samldb: SAM database.
:param gid: Group GID
:param sid_name_use: SID name use
:param nt_name: NT Group Name
:param comment: NT Group Comment
:param domaindn: Dom... | 05c005c01131684bad78fd45af0b82d4b1b2fedc | 3,622,947 |
import platform
import scipy
def version(silent=False):
"""NeuroKit2's version.
This function is a helper to retrieve the version of the package.
Examples
---------
>>> import neurokit2 as nk
>>>
>>> nk.version()
"""
if silent is False:
print(
"- OS: " + plat... | c03044b457096fd60e9f58196bbb7ab8e0fb74fb | 3,622,948 |
from typing import Any
def _str_to_type(content: str) -> Any:
"""Get skl2onnx type by string.
This is used to parse model defintion to skl2onnx I/O
Parameters
----------
content: str
The key representation of type.
Returns
----------
Any:
The type of the string key.
... | 05f166afd4543270fe6c38dcfb1bfb9da5c30846 | 3,622,949 |
def parse_tls_extension(data):
"""
This parses one extension from the given data (which may contain
multiple extension records).
:returns: parsed object along with unparsed data
:rtype: 2-element tuple containing a `py:TlsExtension` object and the
remaining data which has not yet been parsed
"""
t = data[0:2]... | 3eb297938cb3382334bb7087541f14766d5c6e39 | 3,622,950 |
def get_postgres_curie_prefix(curie):
"""The representation in postgres moves things to lowercase, and replaces . with _"""
if ':' not in curie:
raise ValueError(f'Curies ought to contain a colon: {curie}')
prefix = curie.lower().split(':')
prefix = '_'.join(prefix[0].split('.'))
return pref... | 314d59205fffd7e3dcdfb3a5ca7a81a12baffa76 | 3,622,951 |
def extract_svc2_features(trace):
"""
Extract all of the features for the svc model in the [svc.py](../attacks/svc.py) file.
@param trace is a trace of loading a web page in the following format `[(time, incoming)]`
where outgoing is 1 is incoming and -1
"""
features = []
get_packet_st... | 548c7f7eded2b9ce9d5f1dc9f8c6ddfa96cc02df | 3,622,952 |
import json
def parse_stations(html):
"""
Strips JS code, loads JSON
"""
html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '')
html = json.loads(html)
return html['suggestions'] | f9fb64d21c0b206b4c034e0f8a5c560eccb9b9e4 | 3,622,953 |
def read_template(sitename, docname):
"""get the source of a specific template"""
# moet eigenlijk met read_data maar dan moet ik die eerst geschikt maken
with (WEBROOT / sitename / '.templates' / docname).open() as f_in:
data = ''.join(f_in.readlines()).replace('\r\n', '\n')
return data | eca5d8d3e10a9e32adc0b6e5de1cae95ae65faed | 3,622,954 |
def boxplot(
data,
order=None,
colors=None,
at=None,
ax=None,
showfliers=False,
capprops=dict(linewidth=0),
boxprops=dict(linewidth=1, linestyle='-'),
medianprops=dict(linewidth=2, color='k'),
whiskerprops=dict(linewidth=1, linestyle='-'),
**box_args
):
"""Boxplot.
... | 8a23a9ac1277ae6e21cf70e660e26be4837b6d91 | 3,622,956 |
def peer(socket_path=None):
"""
>>> p.peer()
>>> try:
>>> p.startup()
>>> # do something with p
>>> finally:
>>> p.shutdown()
or
>>> with peer() as p:
>>> # do something with p
>>>
"""
if socket_path not in _instances:
_instances[socket_path] = UBusPeer(socket_path)
return _instances[s... | aa74c08623955ae4e298df318364ce030e100ad3 | 3,622,957 |
def actors(request):
"""
Return list of actors for datalist in app.js.
View isn't rendered; only used to return json to app.js.
"""
search_for = request.GET.get('name', default='').lower()
LIMIT = 20
actor_list = []
actors = Name.objects.filter(
Q(lowercase_name__startswith=sea... | f82289521581f020b64c2d8ca58a6b7d4c766cc3 | 3,622,959 |
def get_opt_d(series, ds=None, lag=1, thres=1e-5, max_size=10000,
p_thres=1e-2, autolag=None, verbose=1, **kwargs):
"""Find minimum value of degree of stationary differntial
Args:
series (pd.Series)
ds (array-like, optional): Defaults to np.linspace(0, 1, 100)\
Search ... | 4316dfc00f35b79167792a6603cad9857c633c64 | 3,622,960 |
def agentPortrayal(agent):
"""
Función que define como se visualizarán los agentes en pantalla
Parámetros:
agent - agente(s) que se visualizarán
Retorno:
portrayal - diccionario con las especificaciones de como se visualizarán los agentes
"""
portrayal = {
"Filled": "true",
... | 9d496c921808da8d78230ee40e95ef41a8ec2e7d | 3,622,961 |
def transform_image_batch(image_batch, input_meta_type, output_meta_type):
"""."""
output_batch = np.empty(image_batch.shape, dtype=output_meta_type.dtype)
for i in range(len(image_batch)):
image_with_meta = add_meta_to_image(image_batch[i], meta_type=input_meta_type)
output_batch[i] = trans... | e1a8b4a870db5b8cd6befb74e466f21889c60cac | 3,622,962 |
import json
def json_to_str(json_obj):
"""JSONをstr型へ変換"""
return json.dumps(json_obj, separators=(",", ":"), ensure_ascii=False) | 1ef38962b264991287f5b468489b20bd85be30ff | 3,622,963 |
def get_color(orig_label=None,
gt_label=None,
target_label=None,
adv_label=None,
targeted_attack=False):
"""Get color according to different possible correctness combinations."""
if ((gt_label is None or orig_label == gt_label) and
(adv_label is None or ... | 8a05dde4c60582bc2559f182423e795d2ecc1c1d | 3,622,964 |
import click
def __get_params(ctx):
"""
Get parameters from config file.
:param click.core.Context ctx: Context object of click.
:return: parameters
:rtype LogParam
"""
# load parameters from ini file
p = params.LogParam()
ret = p.read_ini()
if not ret:
click.echo('ログ取得... | 7e54402371a8718800eb91d62d56871b14ede8bf | 3,622,965 |
from typing import Dict
from typing import Optional
from typing import List
def _create_sub_keys(
spec: config_pb2.MetricsSpec
) -> Dict[Optional[metric_types.AggregationType],
List[Optional[metric_types.SubKey]]]:
"""Creates sub keys per aggregation type."""
result = {}
if spec.HasField('binarize... | c1770f80769d131e1043efd51ab6b56b7081831e | 3,622,966 |
import binascii
def int2bytes(integer_number: int) -> bytes:
"""整数还原为原始的二进制字节流, 默认方式: 大端, 和struct功能一致
还原方式从高位按位截取
"""
hex_str = int2hex(integer_number)
if len(hex_str) % 2 != 0:
hex_str = '0%s' % hex_str
return binascii.a2b_hex(hex_str) | 154163c4be8e0d7d3afda534687e6a043aade651 | 3,622,967 |
def get_user(request):
"""
Returns the user model instance associated with the given request session.
If no user is retrieved an instance of `VerbaAnonymousUser` is returned.
"""
user = None
try:
user_id = request.session[SESSION_KEY]
token = request.session[AUTH_TOKEN_SESSION_KE... | f55ddf9ee0c7d75bd8c9dd1f70273b757114944c | 3,622,968 |
def set_mode():
""" Select the game mode """
# This is an error checking version of reading user input
# This will be explained in class - pay attention!!
# Understanding try/except cases is important for
# verifying user input
# handle game crashing
try:
app.write("Please select a s... | 7e3ac1eb7fdeefe1e0df2fc06fab1290309cd166 | 3,622,969 |
def get_comment(pk):
"""
This method returns a comment by its id.
"""
try:
return Comment.objects.get(pk=pk)
except Comment.DoesNotExist:
raise NotFound({"error": "Comment not found."}) | 68378741ea7d2df442998ca75502683cfa2a3e77 | 3,622,970 |
def inverse_multi_quadratic_rbf(r, kappa):
"""
Computes the Inverse-Multi-Quadratic Radial Basis Function between two points with distance `r`.
Parameters
----------
r : float
Distance between point `x1` and `x2`.
kappa : float
Shape parameter.
Returns
-------
phi :... | 3c556be2ab0507fbfbd005ddbea7ae462b78663c | 3,622,971 |
def clean_list(dirtylist):
"""Takes a list of algorithm names as the user put them in.
Turns abbreviations in to their non-abbreviated form.
Returns a list of the corresponding encoders or encrypters in the same
order as given in the input list.
Returns an empty list if any of the input... | 0aea1b2549818a4f236299ad1ea4d1769c15023d | 3,622,972 |
from datetime import datetime
def days_between(T_begin, T_end):
"""
格式如下
:param T_begin: 2018-01-01
:param T_end: 2018-01-01
:return:
"""
b = datetime.strptime(T_begin, time_format)
e = datetime.strptime(T_end, time_format)
return (e - b).days | 07542029d2231aeca43ef9ed849dc070bff4ccae | 3,622,975 |
import re
def read_cpr(path):
"""Read and parse a CPR file. Return masks, which are (id, RLE data).
Note: Python 3.6.4 docs say its XML module is not secure, se we use regexp.
"""
# Example: <Mask id="123">[12 34 56]</Mask>
mask_pattern = r'<Mask\s.*?id="(.*?)".*?>.*?\[(.*?)\].*?</Mask>'
text... | b5781607c150d0521d816c9027660e2b5e4b0fe0 | 3,622,976 |
def category_from_dict(category_dictionary: dict):
"""
The method converts a dictionary of Category to a Category object.
:param category_dict: A dictionary that contains the keys of a Category.
:type category_dict: dict
:rtype: ibmpairs.catalog.Category
:raises ... | b6913c685b4236769b08969c0d1ada6831b87ad4 | 3,622,977 |
import math
def schaffer6(phenome):
"""The bare-bones Schaffer function 6."""
sum_of_squares = phenome[0] ** 2 + phenome[1] ** 2
result = math.sin(math.sqrt(sum_of_squares)) ** 2 - 0.5
result /= (1.0 + 0.001 * sum_of_squares) ** 2
result += 0.5
return result | 80f19b28ebf4511a0670dfa622ffd3c55e8ec670 | 3,622,978 |
import math
def pseudo(flight_data_df, mass, ke, kd, v0, dt=1./25, release_frame=0, units=Units.KM_PER_HOUR):
"""Return a dataframe of pseudo airspeed and angle given an input dataframe with watts and rise
Parameters
----------
flight_data_df: pandas.DataFrame
Must have frame, rise, and watts... | ce45bf3266bed1041f5c5def428529393c457e4e | 3,622,980 |
def n_7(x):
"""Max z_0.5c, z_LE, or z_TE of wing at centreline"""
# z_max(LE/TE) = z + abs(c_0/2 * tan(twist_0))
z_le_te = x[1] + np.abs(x[2] / 2 * np.tan(np.radians(x[4])))
# z_max_50% chord = z + 0.5 * t/c * c
z_50 = x[1] + 0.5 * x[3] * x[2]
# Check if diamond centre is higher than LE/TE
... | 4010c2b10b02c5a2469962c20bd491c34e5a41f8 | 3,622,981 |
from astropy.time import Time
from dateutil.parser import isoparser
def dateobs2night(dateobs):
"""
Convert DATE-OBS ISO8601 UTC string to YEARMMDD int night of KPNO sunset
"""
# use astropy to flexibily handle multiple valid ISO8601 variants
try:
mjd = Time(dateobs).mjd
except ValueEr... | 4630c213a2dcc456e286d93f626304409e584f66 | 3,622,982 |
def write_fm_rectangle(path: StrOrPath,
dx: Num,
dy: Num,
x0: Num = 0,
x1: Num = 18,
y0: Num = 1,
y1: Num = 5) -> AnyByStrDict:
"""Create a rectangular Delft3D flexible mesh grid... | 2f48a56f99c7cce24e498ad348862bef117ef42e | 3,622,983 |
def take_before_exclusive(iterable, predicate):
"""Yield items up to but excluding including the first match.
If no matching item is present, the result is empty.
Args:
iterable: An iterable series of items.
predicate: A function of one argument used to select the last item.
Returns:... | 3f62a1575541dfcd071424fca4b290f3f50cc518 | 3,622,984 |
def root_graphql_schema_query():
"""
Get the graphql schema.
Dig up the introspection query string from file, run it through graphql,
and jsonify the result.
"""
return flask.send_file(flask.current_app.schema_file) | c636882df1af171aed938a9f8e73c870098bd410 | 3,622,985 |
def write_vol(model, file_name, data_label, nsteps, file_format):
"""
Writes out the model as a 3d volume grid
Parameters
----------
model : GeologicalModel object
Geological model to export
file_name : string
Name of file that model is exported to, including path, but without t... | 44553ff9419221f17b50e98301c70089150eb1a9 | 3,622,986 |
import inspect
import http
def GetJSONRPCCallerIP():
"""Retrieve the IP address of the JSON RPC caller.
This is a hack that depends on the implementation details of jsonrpclib.
We know that JSON-RPC over HTTP requires a SimpleHTTPServer and
SimpleJSONRPCRequestHandler dervies from SimpleXMLRPCRequestHandler,... | c2174a1c670bc0ad8d3df67d0b1dc47865bed3cb | 3,622,988 |
def build_received_request(qparams):
""""Fills the `receivedRequest` part with the request data"""
request = {
'meta': {
'requestedSchemas' : build_requested_schemas(qparams),
'apiVersion' : None,
},
# 'query': None
}
return request | 16e1f243ac5b447be2208a7a2612e590b2f81afd | 3,622,992 |
from typing import Dict
def _read_static_tables_eia() -> Dict[str, pd.DataFrame]:
"""Build dataframes of static EIA tables for use as foreign key constraints.
There are many values specified within the data that are essentially
constant, but which we need to store for data validation purposes, for use
... | fbb49226a542db5be2a74d9b294e4193476332aa | 3,622,994 |
def build_filters(tbinfogolden):
"""
Build for each tb in tbinfo a filter
"""
filter_return = []
"""Each assembler string"""
for tb in tbinfogolden["assembler"]:
tb_filter = []
"""remove first split, as it is empty"""
split = tb.split("[ ")
"""For each line"""
... | fdbf2c0b64c9582a00acb38c8395d249dfeb6f56 | 3,622,995 |
from typing import Optional
def init_dml_stmt(
ir_stmt: irast.MutatingStmt,
*,
ctx: context.CompilerContextLevel,
parent_ctx: context.CompilerContextLevel,
) -> DMLParts:
"""Prepare the common structure of the query representing a DML stmt.
Args:
ir_stmt:
IR of the DML sta... | 122daa6c2329159b8ee00c339deec9a26edc616c | 3,622,996 |
from typing import cast
def ca_stc_get_digest_name_by_id(slot, digest_id):
"""
Get name of digest by its ID
:param slot: slot id
:param digest_id: digest id
:return: digest name
"""
h_slot = CK_SLOT_ID(slot)
c_digest_id = CK_ULONG(digest_id)
c_name_len = CK_BYTE(CRYPTO_NAME_BUFFER... | 3c547181d04608c39a18a169490ac824fb391972 | 3,622,998 |
from pathlib import Path
def data_root_directory():
"""Get a path to the top level data directory. Checks whether you have created the local store of data at the expected
location and returns that as default if found, otherwise returns the location on the shared folder
Returns:
(pathlib Path): A ... | f687ffcf05aa74c521624467c3be7ec108de6a46 | 3,622,999 |
import torch
from typing import Optional
def camera_to_image_space(
points: torch.Tensor,
focal_x: float,
focal_y: float,
center_x: float,
center_y: float,
flip_h: bool = True,
height: Optional[int] = None,
device: Optional[torch.device] = None,
_validate_args: bool = True
) -> torch.Tensor:
"""Tr... | 60417fcfa657a5a40e8e3fde8212c1d0faba9dd8 | 3,623,000 |
def get_devices(db: Session, skip: int = 0, limit: int = 100):
"""
Get Device list (default: up to 100 devices)
"""
return (
db.query(models.Device)
.order_by(asc(models.Device.id))
.offset(skip)
.limit(limit)
.all()
) | d1076c1038c1ffcd9a60b5205d310688a69e6107 | 3,623,002 |
def _swap_log_prob_and_maybe_grads(
pre_swap_replica_results,
post_swap_replica_states,
inner_kernel,
):
"""Swap 'target_log_prob' and maybe 'grads_target_log_prob'.
After swapping states, the log probs for replicas need to be evaluated at
the new points, then tempered. The easiest way to do this is ... | 71cb2b05bb4aed15ff32106975f7e1b83bb2101c | 3,623,003 |
def shapes_to_labels_masks(img_shape, shapes, label_name_to_value):
"""Converting shapes in json generated by Labelme to masks and class ids
Args:
img_shape: Size of mask (height, width)
shapes: list of labels and points [{"label":"mouse", "points": [[x1,y1], [x2,y2]...]},
... | 36fbdf7a62ae0a834573bf4d6c148418026fd276 | 3,623,004 |
def read_gpm(infile):
"""
READ_GPM
Read HDF5 GPM file with these parameters:
- dataQuality
- landSurfaceType
- flagPrecip
- flagBB
- heightBB
- widthBB
- qualityBB
- typePrecip
- qualityTypePrecip
- zFactorCorrected
It will reverse direction along the beam for re... | 995361838c4a2ea22ffb0040fb62fffeab254a3b | 3,623,005 |
import re
import socket
def get_host_name() -> str:
"""Get the host name.
:return: A string value.
"""
return re.sub(r"\.(?:local|lan)", "", socket.gethostname()) | 225889a0bf40943ef962903551bde85fd2729ac8 | 3,623,006 |
def read_data(data_path):
"""This function reads in the histogram data from the provided path
and returns a pandas dataframe
"""
gwas_df = pd.read_csv(data_path)
return gwas_df | 034a65ac32613ae52187bf715151ec026cb63e00 | 3,623,007 |
def fix_hyphen_commands(raw_cli_arguments):
"""Update options to match their module names with underscores."""
for i in ['gen-sample', 'run-python', 'run-stacker']:
raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i]
raw_cli_arguments.pop(i)
return raw_cli_arguments | cbc420547f1d3a04787d059aa09eb0199df82dba | 3,623,008 |
from typing import Tuple
def pspnet(input_size: int, num_classes: int, loss, channels: int = 3) -> Tuple[Model, str]:
"""
Pyramid Scene Parsing Network
https://arxiv.org/abs/1612.01105
https://hszhao.github.io/projects/pspnet/
https://github.com/Vladkryvoruchko/PSPNet-Keras-tensorflow
"""
... | ec16ceb1a7572551605c96dcc39934ea75190a0f | 3,623,009 |
def get_data_types(nb_sensors):
"""
What should be the data type for each sensor (1 - integer, 2 - float)
Input
nb_sensors -> how many sensors (int)
Output
data_type_per_sensor -> list of data types for each sensor
"""
print("Choose data type for each sensor: 1-integer / 2-floa... | f3133d415f1d6c8448fec57a1f14fb88d697107d | 3,623,010 |
from typing import Sequence
from typing import Union
def cpgrid_to_rg(
volume: xr.Dataset,
xyzcorn_df: pd.DataFrame,
mapping_dims: Sequence[str] = ("xline", "iline"),
depth_dim: Union[str, None] = None,
buffer: int = 0,
srate: float = 0.1,
client: Union[None, Client] = None,
) -> xr.Datase... | 4b860df568ad74d348dfc1e00895582c7b15becb | 3,623,011 |
def get_trip_walking(origin, destin):
"""
Return trip data between two pois, by default mode of travel is driving
"""
myconfig_walking = RequestConfig(app.config['OSRM_WALK_ADDRESS']) # service for mode walking
coord_start = [float(item) for item in origin]
coord_finish = [float(item) for i... | 4a548b1ad5b2eaae9177e83bc60472046a57a333 | 3,623,012 |
from typing import List
def confidence_threshold(boxes: List[DetectionBox]) -> List[DetectionBox]:
"""
Filter a list of boxes with a given confidence threshold.
:param boxes: A list of boxes.
:return: A list of boxes with confidences higher than the threshold.
"""
return [box for box in boxes ... | 17256a2c9b89ce249c7f326715854a1ed60e061e | 3,623,013 |
def get_linear_regression_id(linear_regression):
"""Returns a linearregression/id.
"""
return get_resource(c.LINEAR_REGRESSION_PATH, linear_regression) | 2ffee0afbb4feae3bac94d2c075ec8a59a08e599 | 3,623,014 |
def retry(freq=3, retry_callback=None):
"""
装饰器,为函数添加此装饰器当函数抛出异常时会对函数重新调用,重新调用次数取决于freq指定的参数
:param freq: 重试次数
:param retry_callback: 重试时回调执行的函数
:return: 原函数返回值
"""
def decorator(func):
def wrap(*args, **kwargs):
now_freq = 1
while True:
tr... | 0536b56e9b5260e78e3858c143c3845ccab3e53f | 3,623,019 |
def models(draw, states=None, spread_probs=None, modalities=None):
"""Define search strategy for generating unilateral models"""
graph = draw(graphs(max_size=4))
model = Unilateral(graph)
if states is not None:
num_lnls = len(model.lnls)
model.state = draw(
hynp.arrays(dtype... | 9d1cd1052ae1d4e0b0d728b564d0c718ec68a3d1 | 3,623,020 |
def read_line_offset(file, offset):
""" Seek to offset in file, read a line and return the line and new offset """
fp = open(file, "r")
fp.seek(offset, 0)
line = fp.readline()
offset = fp.tell()
fp.close()
return (line, offset) | 429d592cf44e1f287eea5a67302a78473eb2362f | 3,623,022 |
def load_config(stream, config_globals):
"""Load a configuration file and generate importer and exporter classes.
Args:
stream: Stream containing config YAML.
config_globals: Dict to use to reference globals for code in the config.
Returns:
BulkloaderEntry
Raises:
InvalidConfiguration: If the... | ee0d5158a8aca7d65dc3045b5a4763159b17b1a2 | 3,623,023 |
def endpoint_api_abort():
"""
Serves an API endpoint, non-gracefully emergency aborting what is being done now.
"""
machine_worker_process.kill()
return jsonify({'status': "OK"}) | 6403f1b235ffebd71b1a209574d92e7c3b685b1b | 3,623,024 |
def test_get_username_return_none(entered_username, monkeypatch, config):
"""Prompt for username when it's not in keyring."""
class FailKeyring:
@staticmethod
def get_credential(system, username):
return None
monkeypatch.setattr(auth, "keyring", FailKeyring())
assert auth.R... | c8701617e0098ccd5d25e0ff893498edc3f20b19 | 3,623,025 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.