content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_or_modify(topic_name, question, answer, user):
""" Creates or modifies a topic based if we have topics with the name
entered and the user is the creator. """
query_ids = topics_by_id(topic_name)
topic_com = None
for topic_id in query_ids:
topic = Topic.objects.get(id=topic_id)
... | 1e0d47cb1f8cce0927f62ce38071bc0e184a3c3d | 3,608,608 |
def match_comment_type(file_name):
"""
Check the type of a single file and return the correct charachter that needs to be checked for comments
# -> python
// -> Java
# -> Textfile (my preference I recognize this loophole)
"""
if(file_name.endswith(".txt")):
return "#"
elif(file_n... | 20c4c04e8e656862443ea5ce7584e383d6c72842 | 3,608,609 |
def micore_tf_copts():
"""C options for Tensorflow builds.
Returns:
a list of copts which must be used by each cc_library which
refers to Tensorflow. Enables the library to compile both for
Android and for Linux.
"""
return tf_copts(android_optimization_level_override = None) + tf_opt... | d94c0a6c3c57b4ac4401863af9bd09848153fb23 | 3,608,610 |
def getDirName():
""" () -> None
Get the directory name for the repo
"""
try:
file = open('dirname', 'r')
return file.read()
except IOError:
return None | ca05bbd8da05dd5f06f95bc457e31df9c9b9e45a | 3,608,611 |
import operator
def getdata(filename, *args, **kwargs):
"""
Get the data from an extension of a FITS file (and optionally the
header).
Parameters
----------
filename : file path, file object, or file like object
File to get data from. If opened, mode must be one of the
follow... | ada665bb516c1f940b8aa485ceb9f4876e7e7e79 | 3,608,612 |
def get_conversion_factor_WTE(volume):
"""Return conversion factor of thermal conductivity."""
return (
(THz * Angstrom) ** 2 # ----> group velocity
* EV # ----> specific heat is in eV/
* Hbar # ----> transform lorentzian_div_hbar from eV^-1 to s
/ (volume * Angstrom**3)
) | 535ca4b4ca702cac72b10a6f8ec580a53b1ba844 | 3,608,613 |
def diagh2mat(dlow):
"""
Return hermitian matrix W from lower diagonal format.
Parameters
----------
dlow: ndarray, shape=(N//2+1, N)
Returns
-------
ndarray, shape=(N, N)
"""
N = dlow.shape[-1]
assert dlow.shape[-2] == N//2+1, "Seems dlow is out of shape!"
W = np.zeros... | e40fc7f44077b0680d4c519120fa75b790e02e4a | 3,608,615 |
def filter_submission(submission):
"""Determines whether to filter out this submission (over-18, deleted user, etc.)."""
if submission["num_comments"] < args.mincomments:
return True
if "num_crossposts" in submission and submission["num_crossposts"] > 0:
return True
if "locked" in submis... | 0e6a6c1b907d7e99aa9a96086103bd679ac64b6b | 3,608,616 |
def Append(**kwargs):
""" Recibe los nombres de los dataframes que se quieren añadir uno bajo el otro"""
appenddf = pd.DataFrame()
dfs = list(kwargs.values())
appenddf = appenddf.append(dfs, sort=False)
appenddf.reset_index(drop=True, inplace=True)
appenddf = appenddf.astype(object).where(pd.notnull(appenddf),No... | 0f0a2d551e879a1e4d3c8a90f1d1a8e6b8c726a2 | 3,608,617 |
def get_plannings(client, page, per_page):
"""
Gets the list of all plannings in the database
:param client: the client to make the request
:param page: the page to be shown
:param per_page: the amount of plannings per page
:return:
"""
pagedetails = dict(
page=page,
page... | 2ebfd016e4e32ec819f4bc5319cb980a1d4b2d6a | 3,608,618 |
def to_rq_symbol(symbol: str, exchange: Exchange) -> str:
"""将交易所代码转换为米筐代码"""
# 股票
if exchange in [Exchange.SSE, Exchange.SZSE]:
if exchange == Exchange.SSE:
rq_symbol = f"{symbol}.XSHG"
else:
rq_symbol = f"{symbol}.XSHE"
# 金交所现货
elif exchange in [Exchange.SGE... | 1f2189c2ad5aeacfe1035778e12758730a7fd1a2 | 3,608,619 |
def cat6(update: Update, _: CallbackContext) -> int:
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
keyboard = [
[InlineKeyboardButton("Katherine Johnson, la matemática que llevó astronautas", callback_data=str(ONE))],
[InlineKeyboardButton("Ada Lovelace, l... | a96e9c12be60230cf0dc7e69a28513524203e2fa | 3,608,620 |
import html
def function_metrics():
"""Determine the function metrics."""
settings = {
"report_directory": "D:\\\\Projects\\github\\sqatt\\reports",
"analysis_directory": "D:\\\\Projects\\github\\sqatt",
"tokens": "20",
"language": "python",
}
metrics_file = measure_f... | fb93dbc693999ec798c82517d77e12e73256554d | 3,608,621 |
import torch
def categorical_accuracy(preds, target):
"""
Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8
"""
max_preds = preds.argmax(dim=1, keepdim=True) # get the index of the max probability
correct = max_preds.squeeze(1).eq(target)
return correct.sum().to... | a37237b1a73efcef313a81d131e001e16ad506f7 | 3,608,622 |
from pathlib import Path
def create_planar_paths(mesh, planes):
"""
Creates planar contours. Does not rely on external libraries.
It is currently the only method that can return identify OPEN versus CLOSED paths.
Parameters
----------
mesh: :class: 'compas.datastructures.Mesh'
The mes... | eef2a06911ab262cddf4d6686d05062ced6d9beb | 3,608,623 |
def process_switch_positions(switch_positions: list) -> list:
"""iterate through the list of binary switch positions, return the ascii equivalent"""
ascii_characters = []
for byte in switch_positions:
byte_as_string = ""
for switch in byte:
byte_as_string += str(switch)
c... | 9194dd103d02e1f79cdf8d81a84e540626898dc9 | 3,608,624 |
def triangle_area(x_data: np.ndarray, y_data: np.ndarray, i0: int, i1: int, i2: int) -> float:
"""
Compute area of triangle given by 3 points given by their coordinates *x_data* and *y_data*, and their
indices *i0*, *i1*, *i2*.
"""
x0 = x_data[i0]
y0 = y_data[i0]
dx1 = x_data[i1] - x0
dy... | 8d0e68527b548d61a5c4dd1592630182f3c5ea9c | 3,608,625 |
import socket
def get_hostname():
"""Get hostname.
"""
return socket.getfqdn(socket.gethostname()) | 42a3ee2304e73c6858553c7fe00edd49c0747826 | 3,608,626 |
def horizontal_interp( lon_in_1d, lat_in_1d, mlat_misomip, mlon_misomip, lon_out_1d, lat_out_1d, var_in_1d ):
""" Interpolates one-dimension data horizontally to a 2d numpy array reshaped to the misomip standard (lon,lat) format.
Method: triangular linear barycentryc interpolation, using nans (i.e. gives nan... | 25e03985f7f13079c61e7b5a658b2672d43e1b97 | 3,608,627 |
def cross_entropy_seq(logits, target_seqs, batch_size=None):#, batch_size=1, num_steps=None):
"""Returns the expression of cross-entropy of two sequences, implement
softmax internally. Normally be used for Fixed Length RNN outputs.
Parameters
----------
logits : Tensorflow variable
2D tenso... | cf64aaaa5e65ff24f148c18c89679abfa04ce221 | 3,608,628 |
def class_net(images, level, num_classes, num_anchors=6, is_training_bn=False):
"""Class prediction network for RetinaNet."""
for i in range(4):
images = tf.layers.conv2d(
images,
256,
kernel_size=(3, 3),
bias_initializer=tf.zeros_initializer(),
kernel_initializer=tf.rand... | f75d12f65276e8195df990b5a4ac59f242e685ef | 3,608,629 |
def random_walk(nsteps=100, seed=1, start=(0, 0)):
"""Creates 2d random walk trajectory.
Parameters
----------
nsteps : int
Number of steps for trajectory to move.
seed : int
Seed for pseudo-random number generator for reproducability.
start : tuple of int or float
Start... | fea59a08bcad5ed0b15f8d98b052313209696c1b | 3,608,630 |
def update_perceptron_batch(lexicon, data, learning_rate=0.1, parser=None):
"""
Execute a batch perceptron weight update with the given training data.
Args:
lexicon: CCGLexicon with weights
data: List of `(x, y)` tuples, where `x` is a list of string
tokens and `y` is an LF string.
learning_rat... | fe62fa8595890431c4fcef5a3cac71969c084b4a | 3,608,632 |
def length_str(msec: float) -> str:
"""
Convert a number of milliseconds into a human-readable representation of
the length of a track.
"""
seconds = (msec or 0)/1000
remainder_seconds = seconds % 60
minutes = (seconds - remainder_seconds) / 60
if minutes >= 60:
remainder_minut... | 7cf6674d68d118c78a2953b3fef873633673bbf0 | 3,608,633 |
from typing import Optional
from typing import Iterable
from typing import Dict
from typing import List
def update(
dataset: Dataset,
*,
attributes: Optional[Iterable[str]] = None,
attribute_types: Optional[Dict[str, attribute_type.AttributeType]] = None,
attribute_descriptions: Optional[Dict[str,... | 4761ad5441fec6c617cd436c920342bd784e8c03 | 3,608,634 |
from typing import Callable
from typing import Type
from typing import Union
import pandas
import functools
def func(
__original_func=None,
*,
function: Callable[
[Type[Relation], Union["pyspark.sql.DataFrame", "pandas.DataFrame"]],
Union["pyspark.sql.DataFrame", "pandas.DataFrame"],
]... | 24bd0ab68bf9e0c62fe010393d1d01e6dda0abbd | 3,608,635 |
def remove_rests_from_track(track):
"""
Remove rests from a given percussion track.
This function also works for other types of tracks as well.
"""
for measure in track.measures:
for voice in measure.voices:
last = None
newbeats = []
for beat in voice.bea... | 90064b181a6f2198e98c9ac80b691eb91572c1f1 | 3,608,636 |
def handle_invalid_usage(error):
"""
Handle ApiException as HTTP errors and react to its specification inside
"""
log.warn("Caught ApiException. Reason: {}".format(str(error)))
response = error.to_dict()
return response, error.status_code | 9debb5014748b2ece6e569c899c99c7510d425ee | 3,608,637 |
def process_spikes(group_index, n_co_spikes=2, hdu_only=False):
"""
Get the paths to all files belonging to the group numbered by group_index.
There are typically 7 files per group
:param group_index: group number as given by grouping the database by unique group indices.
:param hdu_only: set to ... | 2c3666befee1ebdbdb87a9aa567d1c4d399db7f5 | 3,608,638 |
def sales(from_, to, hashids=None, tz=None, format_=None, **opts):
"""
Returns the total price for sales checkouts in a period, where session_id
identifies every sale.
"""
query_params = parse_query_params({
'from': from_,
'to': to,
'hashid': hashids,
'tz': tz,
... | 879f98498bb93e31acb413cc69b301308c7f5b7a | 3,608,639 |
from typing import Dict
from typing import Any
from typing import Callable
def get_reader(data: Dict[str, Any]) -> Callable[[str], nbf.NotebookNode]:
"""Returns a function to read a file URI and return a notebook."""
if data.get("type") == "plugin":
key = data.get("name", "")
reader = get_entr... | 6e9d273f83d0fceba21f734bfe853491c3b26b64 | 3,608,640 |
def retrieve_context_topology_node_owned_node_edge_point_connection_end_point_name_name(uuid, node_uuid, owned_node_edge_point_uuid, connection_end_point_uuid): # noqa: E501
"""Retrieve name
Retrieve operation of resource: name # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:param node_uuid... | 29660c6a1f6421f477e416b20e53befa8233ddec | 3,608,641 |
def raw_to_sec_df(raw_df):
"""
Convert a 100 millisecond apart raw match dataframe to a second apart
match dataframe by only considering the 1st snapshot of all 10 snapshots
for a second.
Parameters
----------
raw_df : pandas.DataFrame
100 ms apart raw match dataframe.
Returns
... | 7c9c3ddae1f1b0496071f12a64645fd6796e8a4d | 3,608,643 |
def var(a=0, b=1):
"""
Variance of the uniform distribution.
"""
with _mpmath.extradps(5):
a, b = _validate(a, b)
return (b - a)**2 / 12 | ad9369616ff4dc6be903ce7fd19e8a5bc310487c | 3,608,644 |
import unicodedata
import string
def safe_file_name(filename, replace=' '):
"""Make safe filename"""
valid_filename_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
char_limit = 150 # 255 replaced by 150 to be onsafe side
# replace spaces
for r in replace:
filename = filenam... | 594de592a72b924e64b3b9bb90d58c5f65c255d7 | 3,608,645 |
def get_E_E_CG_gen_d_t(E_E_gen_PU_d_t, E_E_TU_aux_d_t):
"""1時間当たりのコージェネレーション設備による発電量 (kWh/h) (2)
Args:
E_E_gen_PU_d_t(ndarray): 1時間当たりの発電ユニットの発電量 (kWh/h)
E_E_TU_aux_d_t(ndarray): 1時間当たりのタンクユニットの補機消費電力量 (kWh/h)
Returns:
ndarray: 1時間当たりのコージェネレーション設備による発電量 (kWh/h)
"""
return E_E_ge... | 46870e6ca7739d34027fa8ac3c2f57b2f27e9a6c | 3,608,646 |
def make_all_plaq_observables(source: cirq.GridQubit, ancilla: cirq.GridQubit, circuit: cirq.Circuit):
"""Generate a list of observables like
<X_i (X + iY)_ancilla >
for every location `i` in the grid.
Args:
source, ancilla: "special" qubits for this correlator circuit
circuit: Co... | 47be350f90ec6c86f1dfa00aee051719b3c547eb | 3,608,647 |
def main(myhostname, cnfpath, logpath):
"""Worker process's entry point.
:param myhostname: hostname of the node in which workers are being launched
:param cnfpath: path to config file
:param logpath: path to log file
:returns: exit status of worker process
"""
_run_worker_servers(myhostnam... | 35bdb8db65829477f407c9695c9b1feae2ed9a39 | 3,608,648 |
import math
def stamp(analysis_type, analysis_instance, MNA, RHS):
"""
Generating MNA and RHS to Represent the Circuit
This function retrieve information from the internal structure to constitute MNA and RHS. It also collects neessary information for doing iterate and converge operations.
:param analysis_type: ... | ae378200102885ab6b21aad0823daeb99fcbc488 | 3,608,650 |
import random
def _is_review_needed(task):
"""
Determine if `task` will be reviewed according to its step policy.
Args:
task (orchestra.models.Task):
The specified task object.
Returns:
review_needed (bool):
True if review is determined to be needed according ... | 429c49e8a32826c9f60aeed0ef886f755de1d79c | 3,608,651 |
def num_lines(file):
"""Return # of lines in file
Args:
file: Target file.
Returns:
# of lines in file
"""
return sum(1 for _ in open(file)) | 6c65455c7b16dd4956b68c8cb60f647946ba1fb7 | 3,608,652 |
def TW_WA_WP_BA_Calculation(Depth, RiverLength, Volume, SAlist, dh):
"""Calculate channel top width, wet area, wetted perimeter, and
bed area
"""
Volume = Volume - Volume[0]
DDepth = np.diff(Depth)
TotalArea = Volume/RiverLength/1000
TWlist = SAlist/RiverLength/1000
WAlist = list(TotalAr... | 6332154ad17e5573b8cbfa6b12e5f408dbb3685f | 3,608,653 |
def build_model(opt, data):
"""Builds model and optimiser nodes
opt: dict of options
data: dict of numpy data
Returns a dict containing: 'learning_rate', 'train_phase', 'loss'
'accuracy', 'train_op', and IO placeholders 'x', 'y'
"""
n_GPUs = len(opt['deviceIdxs'])
print('Using Multi-GPU Model with %d devices... | 7f4381e7ddbcb4b2d553b63f48c35beef89acf8d | 3,608,654 |
def get_dirpath(name=None):
"""
Get a pipe directory as Pathlib.Path
Args:
name (str): name of pipe
"""
return get_pipe(name).dirpath | b28a042275e936492ed5e5bea14c826a8c5d66e3 | 3,608,655 |
def tuple_from_ase(asecell: ase.Atoms):
"""
Convert an ase cell to a structure tuple.
"""
cell = asecell.cell.tolist()
# Wrap=False to preserve the absolute positions of atoms
rel_pos = asecell.get_scaled_positions(wrap=False).tolist()
numbers = [
ase.atom.atomic_numbers[symbol] for ... | 05936e417a5e9aa6c17083cbf8e7a04dc70757cb | 3,608,656 |
def plot_cov_ellipse(cov, pos, nstd=2, ax=None, **kwargs):
"""
Plots an `nstd` sigma error ellipse based on the specified covariance
matrix (`cov`). Additional keyword arguments are passed on to the
ellipse patch artist.
Parameters
----------
cov : The 2x2 covariance matrix to base the... | 241259bc7d4679a9f72183ce1b3898623d9be1da | 3,608,657 |
import socket
from datetime import datetime
def build_response_data():
"""
Build a dictionary with timestamp, server ip,
server name, secret and requester ip.
"""
hostname = socket.gethostname()
return {
'now': datetime.now().isoformat(sep=' '),
'local_ip': socket.gethostbyname... | 2ef8476cc6dc195733bc922703ed370c42aba8d1 | 3,608,658 |
def failure_message(message: str, code: str) -> dict:
"""
Return a dict that is a standard failure message.
Args:
code (str): Mnemonic that never changes for this message
message (str): Human-readable message text explaining the failure
Returns:
(dict): A message template.
"... | 791fc4dd22862c592af139aa956e0a0664931115 | 3,608,659 |
def row_sum(lst):
""" Sum of non-missing items in `lst` """
return sum(int(x) for x in lst if x > -1) | 5fabe4d3487e502dcb82dd452854de3777e1a5a8 | 3,608,660 |
import itertools
def cartesian_power(lhs, rhs, ctx):
"""Element ÞẊ
(any, num) -> cartesian_power(a, b)
(num, any) -> cartesian_power(b, a)
"""
ts = vy_type(lhs, rhs)
if NUMBER_TYPE not in ts:
return rhs
else:
lhs, rhs = (lhs, rhs) if ts[-1] == NUMBER_TYPE else (rhs, lhs)
... | d21522a32404f715f82d0cc6c8d120f89697be32 | 3,608,661 |
def plot_per_experiment(**kwargs):
"""
This function creates one figure per experiment defined, with plots of all dependent variables
and their fit in it.
:param kwargs:
- | `model`: to specify the data model to be used (if not specified
| the one from :func:`.get_current_model` will be take... | bb6608bb6ac55458691dc23cc59502d0f3f87e07 | 3,608,662 |
from datetime import datetime
def get_weather_data(requested_date, location):
""" get weather data for date & location - main function.
Args:
requested_date (date) - date requested for forecast.
location (str) - location name.
Returns: dictionary with the following entries:
Status ... | 0f323e776d1ddd50c6e9a018f6f92d04b595c30d | 3,608,663 |
def twoGMMcalib_lin(s, niters=20):
"""
Train two-Gaussian GMM with shared variance for calibration of scores 's'
Returns threshold for original scores 's' that "separates" the two gaussians
and array of linearly callibrated log odds ratio scores.
"""
weights = np.array([0.5, 0.5])
means = np... | 9fe7f796f14ead0643167b1fc14d4e0929a3720a | 3,608,664 |
def route_chess():
"""load game specific resources here"""
return render_template("games/garbo/chess.html"), 200 | a4e5e69bb57dd05972e3088f30247f60590196d8 | 3,608,665 |
def edit_distance_train(encoder_method, vector_distance, texts, distance_labels, plot=False):
"""
The goal of the training procedure is to find the scaling parameter alpha that minimizes (for i along the dataset)
\sum_i (r_i - alpha * p_i)^2 where r_i is the real distance and p_i the predicted one.
... | 9496c937c9ddecf6a46c2699b9dc077409ce2a39 | 3,608,667 |
def compress_dataframe_time_interval(processed_df, interval):
"""
Resamples dataframe according to time interval. If data is originally in 1
minute intervals the number of rows can be reduced by making the interval 15 minutes.
To maintain data quality, an average is taken when compressing the dataframe.... | ffbb35719e33f445ba4b5c91acf8a069cd4902a6 | 3,608,668 |
from typing import Sequence
def create_colormap(color_list: Sequence[str], n_colors: int) -> NDArrayFloat:
"""Create hex colorscale to interpolate between requested colors.
Args:
color_list: list of requested colors, in hex format.
n_colors: number of colors in the colormap.
Returns:
... | 24f4a0b6dfe4c396cdbde5c79ec9bf88378cd441 | 3,608,670 |
def update_file(filename: str, url: str) -> bool:
"""Check and update file compares with remote_url
Args:
filename: str. Local filename, normally it's `__file__`
url: str or urllib.request.Request object. Remote url of raw file content. Use urllib.request.Request object for headers.
Returns... | 10cde22c7a34ca9fb453557e1a6bfb8270d662e3 | 3,608,671 |
def iseast(bb1, bb2, north_vector=[0,1,0]):
""" Returns True if bb1 is east of bb2
For obj1 to be east of obj2 if we assume a north_vector of [0,1,0]
- The min X of bb1 is greater than the max X of bb2
"""
#Currently a North Vector of 0,1,0 (North is in the positive Y direction)
#i... | 9764d373d14530fca2d26d8c7855cc0620e14496 | 3,608,672 |
def GetHashAddr(variable):
""" Get address of a hash as $H_(var_name) """
if type(variable) == INSTRUCTION.Entity:
return "$H_" + str(variable.value)
else:
return "$H_" + str(variable) | cc1004ff7f8b544222342cbd03cb33a1ee4dcd0c | 3,608,673 |
def getObjId(s3key):
""" Return object id given valid s3key """
if len(s3key) >= 44 and s3key[0:5].isalnum() and s3key[5] == '-' and s3key[6] in ('g', 'd', 'c', 't'):
# v1 obj keys
objid = s3key[6:]
elif s3key.endswith("/.domain.json"):
objid = '/' + s3key[:-(len("/.domain.json"))]
... | d1220bae1ab4934f41b683143ace94d388db7beb | 3,608,674 |
def vq5(a_z, a_t):
""" a_z: nx1, visible area of polygon z
a_t: float, projected area of the model
"""
prob = a_z[a_z!=0]/float(a_t)
v = -np.sum(np.multiply(prob, np.log2(prob)))
#prob = tf.truediv(a_z,a_t)
#v = tf.sum(tf.multiply(prob, np.log2(prob)))
return v | 9719429d6d51f936af3dcb3e927944b2e43253e5 | 3,608,675 |
def StandardDialogLayoutAdapter_DoFitWithScrolling(*args, **kwargs):
"""StandardDialogLayoutAdapter_DoFitWithScrolling(Dialog dialog, ScrolledWindow scrolledWindow) -> bool"""
return _windows_.StandardDialogLayoutAdapter_DoFitWithScrolling(*args, **kwargs) | b8bcbf9fd57ba94648bcdec54296fb5df421cfc2 | 3,608,676 |
def timesheet_index_view(request):
"""Redirects the logged-in user (not superuser) to their timesheet for the current month, while
for an superuser display all timesheets available for each of the users
"""
# Redirect none super users to their timesheet.
if not request.user.is_superuser:
re... | a3f891d513dbcaa84b1deeed4a801c420a627913 | 3,608,677 |
from typing import Set
def get_fastq_read_ids(ref_path: str) -> Set[str]:
"""Extracts the read ids from a fastq file."""
read_ids = set()
with pysam.FastxFile(ref_path) as fastq:
for entry in fastq:
read_ids.add(entry.name.strip())
return read_ids | a77b25238851cadf9fff9e4a26272478c4b26d2e | 3,608,679 |
def after(target_event_source: t.Callable):
"""Call decorated function before target function.
:param target_event_source: Target method decorated with @event_source
"""
def _outer(advisor_method):
wrapped = getattr(target_event_source, "__wrapped__", None)
assert wrapped, "The target... | 952c92fbda81bbcefffb9f788d2daad92e677bf3 | 3,608,680 |
import itertools
def concat_list(in_list: list) -> list:
"""Concatenate a list of list into a single list."""
return list(itertools.chain(*in_list)) | 5a58e8e1899fce99f8dabe681206507ae8ad4b8c | 3,608,682 |
def testenv_deposit_pending_almost_filled_auction(
testenv_almost_filled_auction, accounts, chain
) -> TestEnv:
"""A testenv with auction awaiting deposit transfer with a number of bidders below the maximal number of bidders"""
time_travel_to_end_of_auction(chain)
testenv_almost_filled_auction.close_auc... | a28b91cbbf7b63deb59c36b40fe3d89abb8958a7 | 3,608,683 |
def notificationMarkAllRead(request):
"""
Mark all the notifications for this user as read.
"""
Notification.objects.markAllReadForUser(request.user.id)
return HttpResponseRedirect("/notifications") | efc3c4b9ac5adcb227293681e27c470024611c56 | 3,608,684 |
def is_sale(line):
"""Determine whether a given line describes a sale of cattle."""
return len(line) == 5 | e4ff4ae2ea7ea14a2975eaf87852eed2fad0abff | 3,608,685 |
from typing import List
from typing import Generator
from typing import Tuple
from typing import Optional
from typing import Iterable
import tqdm
def match_contexts(
contexts: List[str],
candidates: Generator[Tuple[str, str], None, None],
threshold: float = 65.0,
show_progress: bool = False,
num_p... | f939e715839ff7347e780212dd7b16c095ce43de | 3,608,686 |
from datetime import datetime
def floor_datetime(
dt: datetime.datetime,
precision: spec.DatetimeUnit,
) -> datetime.datetime:
"""take floor of datetime down to a given level of precision
## Inputs
- dt: datetime object
- precision: str name of precision unit to take floor to
"""
if ... | 9c50f40e170672d03d4d750b0b5b342865f617ad | 3,608,687 |
def apology(message, code=400):
"""Render message as an apology to user."""
def escape(s):
"""
Escape special characters.
https://github.com/jacebrowning/memegen#special-characters
"""
for old, new in [("-", "--"), (" ", "-"), ("_", "__"), ("?", "~q"),
... | dbb577b79d76200fc3c8624b3c4679286c3ce33d | 3,608,688 |
def calc_swsh_eq(phi, aa, omega, ell, em, ess=-2):
"""
Finds Slm(pi/2) based on a spectral decomposition
Normalization is that from Glampedakis and Kennefick (2002)
Inputs:
aa (float): spin parameter (0, 1)
omega (float): gravitational wave frequency
ell (int): swsh mode
... | 00bb7c38463ce210a6fbf14fcda39d7d88837b2f | 3,608,689 |
import numpy
import math
def log(inputArray, scale_min=None, scale_max=None):
"""Performs log10 scaling of the input numpy array.
@type inputArray: numpy array
@param inputArray: image data array
@type scale_min: float
@param scale_min: minimum data value
@type scale_max: float
@param sca... | a6f6ef5a5f964cadc05ae6b9f93747eb8de691e0 | 3,608,690 |
def all_daemons_healthy(instance, curr_time_seconds=None):
"""
True if all required daemons have had a recent heartbeat
Note: this method (and its dependencies) are static because it is called by the dagit
process, which shouldn't need to instantiate each of the daemons.
"""
statuses = [
... | 32834006bb08b37a6c64623bea6aefbdcac6a377 | 3,608,693 |
def build_nngp_with_dataset(dataset, kernel_type, num_coeffs, dist_type):
""" Builds a GP using the training set in dataset. """
mean_func = lambda x: np.array([np.median(dataset[1])] * len(x))
noise_var = (dataset[1].std() ** 2)/20
kernel_hyperparams = get_kernel_hyperparams(num_coeffs, kernel_type, dist_type)... | 5a8f05fa1acf27bd24ce85df542d8246d1564900 | 3,608,694 |
def parse_type_reference(lexer: Lexer) -> TypeNode:
"""Type: NamedType or ListType or NonNullType"""
start = lexer.token
if skip(lexer, TokenKind.BRACKET_L):
type_ = parse_type_reference(lexer)
expect(lexer, TokenKind.BRACKET_R)
type_ = ListTypeNode(type=type_, loc=loc(lexer, start))... | a0169a80afc8378041f64ed0c9fb67d5968d854f | 3,608,695 |
from functools import reduce
def phash(img):
"""
:param img: 圖片
:return: 返回圖片的局部hash值
"""
img = img.resize((8, 8), Image.ANTIALIAS).convert('L')
avg = reduce(lambda x, y: x + y, img.getdata()) / 64.
hash_value = reduce(lambda x, y: x | (y[1] << y[0]),
enumerate(map(... | bf298ecf82965283ce2a61828a32852017988f00 | 3,608,696 |
def _is_recipe_fitted(recipe):
"""Check if a recipe is ready to be used.
Fitting a recipe consists in wrapping every values of `fov`, `r`, `c` and
`z` in a list (an empty one if necessary). Values for `ext` and `opt` are
also initialized.
Parameters
----------
recipe : dict
Map the... | 77e438dd00ac5606c52c88518c6932a09dff75df | 3,608,698 |
def identify_company_name(target_name):
""" Identify company name by JCL dictionary
Arg:
target_name (str): target name
Return:
dict: Identified unique name or candidate names from JCL dictionary into BigQuery
"""
fmt_name_str = fmt_string(target_name)
bq_resp = fetch_company_na... | b55a9fe54214019616720ce90162d8c135ef0b4a | 3,608,699 |
def dims_for_qty(data):
"""Return the list of dimensions for *data*.
If *data* is a :class:`pandas.DataFrame`, its columns are processed;
otherwise it must be a list.
genno.RENAME_DIMS is used to rename dimensions.
"""
if isinstance(data, pd.DataFrame):
# List of the dimensions
... | aa05712be2d23765cf50728b6482eb7bcf20335a | 3,608,701 |
from shlex import split
def split(s,separator=None):
"""'this is "a test"' -> ['this', 'is', 'a test']"""
if separator is None:
return split(s)
else: return s.split(separator) | a28bfd53d38afe8492c6fecc47c72bf0fcd5cd4c | 3,608,702 |
def view_event(user, event):
"""
Check whether a user may view a specified event.
:param User user:
:param Event event:
:return: bool
"""
if event is None:
return None
return user.has_perm("booking.view_hidden_events") or event.visible is True | 0aca52c9a60449ab0711a2291c5f12f42c8b3f96 | 3,608,703 |
def is_serial_synchronised(database_handler: DatabaseHandler, source: str, settings_only=False) -> bool:
"""
Determine whether a source should use / is using serial synchronisation
from the NRTM mirror source.
If settings_only is set, only look at whether serial synchronisation should
be enabled bas... | dbc540b67f143117d7848d7f7fb03d03b339c7e5 | 3,608,704 |
def micro_fmeasure(y_true, y_pred):
"""This metric return a micro-averaged F-score"""
precision_value = micro_precision(y_true, y_pred)
recall_value = micro_recall(y_true, y_pred)
return ((Beta ** 2 + 1) * precision_value * recall_value) / (Beta ** 2 * precision_value + recall_value) | 99eabd636a3934c95d0ad3035241ff10fdbe7001 | 3,608,705 |
def setProjParameter(self, name, value):
""" Set an individual paramater for a projection """
checkName(self, name, value)
param = self.parameters
ok = proj_ok_parameters
for nm in list(ok.keys()):
vals = ok[nm]
oktypes = vals[0]
position = vals[1]
nms = vals[2]
... | ea8f1a809713e8d1b86d33b26d376474b0dd647a | 3,608,706 |
def parse_filename(fname, return_ext=True, verbose=False):
"""
Parses `fname` (in BIDS-inspired format) and returns dictionary
Parameters
----------
fname : str os os.PathLike
Filename to parse
return_ext : bool, optional
Whether to return extension of `fname` in addition to key... | 1512b50fa6d07a0bcbb69831418a935f28abe2d8 | 3,608,707 |
def split_to_patch(arr, target_shape=(8, 8)):
"""
shape: (t, 112, 112, 1) -> (-1, t, 8, 8, 1)
"""
hs, ws, _ = arr.shape
ht, wt = target_shape
hp = hs // ht
wp = ws // wt
patch = []
for w in range(wp):
for h in range(hp):
patch.append(arr[(ht*h):(ht*(h+1)), (wt*w)... | 4d7f609d02807e8a3eee5e21dfdbc713ae3ebe7e | 3,608,708 |
import numpy
def inverse_time_decay(learning_rate, global_step, decay_steps, decay_rate, decay_delay=0, decay_power=1,
staircase=False):
"""Applies inverse time decay to the learning rate.
decayed_learning_rate = learning_rate / (1 + decay_rate * t)
learning_rate: A Python number.
... | a62b0d8ecdb0e422483489b33a1e8eb1af557734 | 3,608,709 |
def input_fn(path):
"""
Function to load the LIBSVM Data from the path & tranform the feas into a dictionary [0]
and the response [relevance of the current option] into a tf.Tensor [1]
Response: Size: - as many rows as we have BATCH_SIZE
- as many cols as we have LIST_SIZE
Val... | fd2dc408d7738652faf59a1568c8abbd5bc50d11 | 3,608,710 |
def not_found(error):
"""404 page"""
return render_template('errors/404_notfound.html', error=error), 404 | 6efb3f92ebb87b534ae8deaa5d3bd19189869ba9 | 3,608,711 |
def get_ls(omega_list):
"""Return the array of the Solar longitude of each OMEGA/MEx observation in omega_list.
Parameters
==========
omega_list : array of OMEGAdata
The input array of OMEGA observations.
Returns
=======
ls : ndarray
The array of the omega_list Ls.
... | c8be1927a55ff9aac0134d52691b3b2bdd049724 | 3,608,712 |
def np_mean(a):
"""
Returns the mean from the array, NaN if length is 0.
:param a: the array to use for the calculation
:type a: np.array
:return: the mean or NaN if failed to calculate
:rtype: float
"""
if len(a) == 0:
return float("NaN")
try:
return float(np.mean(a... | 8b2739b2205d24158871a777395ed6acd34d26a0 | 3,608,714 |
def run_intcode(memory, noun, verb):
"""Assign noun and verb then run intcode program on memory."""
memory[1] = noun
memory[2] = verb
pointer = 0
while True:
opcode = memory[pointer]
if opcode == 99:
return memory[0]
param_one = memory[pointer + 1]
param_... | b4f0c6762a9a27021ce1cabd03b950fb8fabcd48 | 3,608,715 |
def update_city(city_id: int, data) -> City:
"""
Update a city record in the database.
:param city_id: The city record identifier.
:type city_id: int
:param data: Updated JSON data for an existing City object.
:return: City
"""
city = City.query.filter(City.id == city_id).one()
city... | 72e88ac2c9d0568b4cb61c96e97db964f5f49355 | 3,608,716 |
import re
def read_memory_graph(target_file):
"""Reads memory percentages from the memory graph."""
percentage_expression_string = r'\d{1,3}\.\d\%'
mem_used_search = re.search(percentage_expression_string, target_file.readline())
if mem_used_search is None:
mem_used = "0.0%"
else:
... | 5c838ff8b3ff1bb5902472879594ac014b18b0c5 | 3,608,717 |
def weights(shape):
"""Create a weight variable.
"""
input_size = shape[0]
var = tf.Variable(tf.truncated_normal(
shape, stddev=tf.sqrt(2.0 / input_size)
))
return var | 1c5eecaa0884403643a9a86708c64dc14ec753ef | 3,608,718 |
def regression_tree(input_dict):
""" Creates a Decision tree classifier """
criterion = input_dict['criterion']
splitter = input_dict['splitter']
max_depth = input_dict['max_depth']
min_samples_leaf = input_dict['min_samples_leaf']
max_depth = max_depth.strip()
if max_depth == '':
... | 6b697a2afab08ea96b54a818471b8fd4541566a7 | 3,608,719 |
def sample_name(data):
"""Return `name` of `Sample` that given `Data` object belongs to."""
return get_sample_attr(data, 'name') | 7400e22cccf72b8f23f7a06df442e3494a6087a5 | 3,608,720 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.