content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def responsive(cls: type) -> type:
"""Mix :class:`ResponsiveMixin` with the given class
Args:
cls (type): Class to mix
Returns:
type: Child class"""
return type(
"Responsive{}".format(cls.__name__),
(ResponsiveMixin, cls), dict()
) | 46193878a2501366b7b6856606cd01b7df45d0f0 | 77,377 |
import ctypes
def GetTokenInformation(token, information_class):
"""
Given a token, get the token information for it.
"""
data_size = ctypes.wintypes.DWORD()
ctypes.windll.advapi32.GetTokenInformation(token, information_class.num,
0, 0, ctypes.byref(data_size))
data = ctypes.create_string_buffer(data_size.val... | 1302df514ffb040d54cccf2f2e4a5d7b1859c252 | 77,378 |
import toml
from typing import OrderedDict
def load_config(providers=builtin_providers, file_path=''):
"""
Reads and loads the configuration file containing fantasy football
league information.
The return value is a dictionary mapping provider name (e.g.,
`yahoo`) to a list of leagues for that pr... | faf9bc7ccf82f4277261b1c446e01b53d8d9bff3 | 77,380 |
def _next_hull_pt_pair(hulls, pair):
"""
Returns the (hull, point) index pair of the next point in the convex
hull.
"""
p = hulls[pair[0]][pair[1]]
next = (pair[0], (pair[1] + 1) % len(hulls[pair[0]]))
for h in (i for i in xrange(len(hulls)) if i != pair[0]):
s = _rtangent(hulls[h], ... | 7673a4ced897544f55535af5e6b05cf26015c69d | 77,381 |
def get_reduced_contribution_matrix_covid(R0,
variant='alpha',
data_dir=None,
vaccination_statuses=default_vacc,
populations=default_pop,
... | decdd22b621f78ef092696ae829595c682dd5bf9 | 77,383 |
def _get_batch_dim_helper(v: TensorStructType) -> int:
"""Tries to find the batch dimension size of v, or None."""
if isinstance(v, dict):
for u in v.values():
return _get_batch_dim_helper(u)
elif isinstance(v, tuple):
return _get_batch_dim_helper(v[0])
elif isinstance(v, Rep... | 952465499388bc20d7ab154fd43f1711d8375f9b | 77,384 |
def read_acf_stat_files(acfstatfiles, N_acf_types=9):
"""
return dataframe of length (N_stars*N_lag_times per star) with evaluated
autocorrelation functions for each aperure and detrending step.
"""
if not acfstatfiles:
raise AssertionError('cannot assess run if there are no ACF statfiles')... | 70808ccf2329dd45b7da5c84e4574730481920cb | 77,385 |
from django.core.exceptions import ImproperlyConfigured
from django.conf.urls import include as original_include
import django.conf.urls
import django.urls
def fix_behaviour_django_conf_urls_include_3tuples(utils):
"""
Keep accepting a 3-tuple (urlconf_module, app_name, namespace) as first argument of include... | bfe7203dfbd7d671f06572a6c831649242ba20d4 | 77,386 |
def constructFunctionElevation(funcName):
"""Constructs a string for elevating a function from exports to top-level"""
template = Template(
"this.${funcName} = this.instance.exports.${funcName};"
)
return template.substitute(funcName=funcName) | 26ca4332a4b815ff16468504ebd0fcb271929d0f | 77,387 |
def sum_box(box1, box2):
"""
return the sum of two bounding boxes
"""
return tuple(tuple(sum(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2)) | 789b34e1721a66f3f5b1765bfe5e57ba2fb718b1 | 77,388 |
import torch
def discounted_cumsum(rewards, discount):
"""Calculates the cummulative sum of discounted rewards
Arguments:
rewards {torch.Tensor} -- rewards
discount {float} -- discount factor
Returns:
[type] -- cummulative sum of discounted rewards
"""
discount **= torch.a... | b0e2cd45c4cb6882a84784c64a20ae64995f26a6 | 77,389 |
def histogram(content):
""" Takes a source_text contents of the file as a string and
return a histogram data structure that stores each unique
word along with the number of times the word appears in the source text."""
words = content.split()
# Dictionary
histogram_dic = {'one': 1, 'fi... | 28af6161b05472fef9632bfb0df7e0672ed9359c | 77,390 |
def is_wep_password_in_hex(password, bit_length):
"""Tells whether we're using HEX or ASCII for the specified password."""
if password is None:
return False
# the password could be either HEX or ASCII
# HEX is valid ASCII too
try:
password = password.decode('ascii')
except (Unico... | 35c1c4f2803e267904c3b3a393bbbaac0efc777e | 77,391 |
def _getSelectedLines():
"""Gets all the selected lines on all layers"""
return list(filter(
lambda x: x.geometry().type() == QgsWkbTypes.LineGeometry,
_getSelectedFeatures()
)) | e99ab9177a60ce4e81678fa0465b85ce76a8eb4d | 77,392 |
import numpy
def AnalyzeSparseVects(bitVects, actVals):
""" #DOC
**Arguments**
- bitVects: a *sequence* containing SBVs
- actVals: a *sequence*
**Returns**
a list of floats
**Notes**
- these need to be bit vects and binary activities
"""
nPts = len(bitVects)
if nPts != len(a... | f3a0b6f667057aedeca66773c99b2e91f518715f | 77,393 |
import collections
def statistics_to_df(all_pathways_statistics):
"""Build a data frame with graph statistics.
:param dict all_pathways_statistics: pathway statistics
:rtype: pandas.DataFrame
"""
pathways_statistics = collections.defaultdict(list)
rows = []
column_types = set()
colum... | f506ec7a647d959f390970ba1353fa2bcc006e22 | 77,394 |
from pathlib import Path
def _strip_dbx(path: str) -> str:
"""Removed Dropbox path from beginning of file."""
prefix = str(Path.home() / 'Dropbox (Springboard)')
if prefix not in path:
show_status_message(f'{prefix} not found in {path}', timeout_secs=3)
return path
for unwanted in (p... | 88edae635ca09ae267912a1263b8ec0d914ca288 | 77,395 |
def _StripPC(addr, cpu_arch):
"""Strips the Thumb bit a program counter address when appropriate.
Args:
addr: the program counter address
cpu_arch: Target CPU architecture.
Returns:
The stripped program counter address.
"""
if cpu_arch == "arm":
return addr & ~1
return addr | 9127f10cbbeb71814f6c9f30e7446d5f8233bb67 | 77,396 |
def dict_to_string(output_format=None, default='---'):
"""
This function creates formatter which joins list of dicts
into single line.
"""
def _formatter(dict_o, obj: DataGetter = None):
if not dict_o:
return default
if output_format is None:
return str(dict_o... | 2f1a213ad6db4e40f634f682e4454c19283cfc4f | 77,397 |
def get_templates_in_category(lang, category_name):
"""Get all templates in a category."""
session = mwapi.Session('https://{0}.wikipedia.org'.format(lang), user_agent="Reuse analysis - isaac@wikimedia.org")
params = {'action': 'query', 'list': 'categorymembers', 'cmtitle': category_name, 'cmnamespace': 10,... | ebbddc8b25288e4d85348ac6684356ef2ad3a744 | 77,398 |
import json
def new_target_form(request):
"""
new_target_form function renders a form to add new
targets by clicking 'Add Target' on the left side panel
ticket pcp-68
:param request: user request
:return: New Target Form
"""
template = loader.get_template('pcp_app/target_form.html')
... | 0d9f7a56f4bf1023305f18629f75b9fe498fd2fd | 77,399 |
from pathlib import Path
import pickle
def fetch_data(name):
"""Fetches data with the given name.
Data is stored in a file namemed name.pickle in the current directory.
"""
filename = Path(__file__).parent / (name + ".pickle")
with open(filename, 'rb') as f:
return pickle.load(f) | 2bc908ec29555f3d7dd4263b816cb9727c7f8f85 | 77,400 |
def vectors(
points,
vectors,
c="k",
alpha=1,
shaftWidth=0.05,
text=None, vmax=None, vmin=None, cmap='jet', values = None):
"""
Routine for creating vectors.
:param list points: Mid point for vector [number of vectors x 3]
:param list vectors: Vector components [number of vector... | 7e3146dd81b484903aa545866b054474785195e1 | 77,401 |
def augment(components):
"""
Augmenting of images.
:param components: components
:return: updated components.
"""
meta = components[0]
aug_center = meta.center.copy()
aug_joints = joints_to_point8(meta.all_joints)
for aug in AUGMENTORS_LIST:
(im, mask), params = aug.augmen... | 3192d2d98418ffb38d33fb8c9e6aefcdad70a2b9 | 77,402 |
import random
def get_random_replicates(well_df, replicate_cardinality):
"""This function return a list of random replicates that are not of the same compounds
or found in the current cpd's size list
"""
while (True):
# Randomly sample replicate names
random_replicates = random.sample(... | 294d7c431d9e80baca25cc8cb6022558874c3674 | 77,403 |
import curses
def set_window_parameters():
"""
Function to set all the window sizes and placements on the screen.
Returns a dictionary of all curses windows where key is a string
that is the title of the window (eg 'twitter'), and the value is the
curses window object.
"""
max_y, max_x =... | 9be542c065665ab22afdb692a635fa31adfa9a32 | 77,404 |
from .main import EnviroCat
def classFactory(iface): # pylint: disable=invalid-name
"""Load CanadianWebServices class from file CanadianWebServices.
:param iface: A QGIS interface instance.
:type iface: QgisInterface
"""
#
return EnviroCat(iface) | 9e2e4b0918103df7a875890a48da8cc5bb14b686 | 77,405 |
def convert(string: str) -> int:
"""Calculate the corresponding integer for a given roman numeral.
Raises `ValueError` if the string does not represent a valid roman numeral.
"""
sum = 0
start = 0
for regex, values in zip(BOUNDARY_FINDER, LETTERS):
sum *= 10
match = regex.searc... | 9321f4fc8f7f0f6a19d9abc78f7cbdb01b0b6f0a | 77,407 |
def bgc_units(cube, name):
"""
Convert the cubes into some friendlier units.
This is because many CMIP standard units are not the standard units
used by the BGC community (ie, Celsius is prefered over Kelvin, etc.)
"""
new_units = ''
if name in ['tos', 'thetao']:
new_units = 'celsi... | 5a41042b7a4fdd747c989a61a531f887f599b7bc | 77,408 |
def calculate_XT_X_Neg1_XT(X):
"""
#Calculate term that can be multiplied with
#Y to calculate the beta weights for least
#squares regression. X should be of shape
#(n x d) where n is the number of observations
#and d is the number of dimensions/predictors
#uses inverse transform
""... | 7bc9a46c866172af5aae11920684897bdb2376f2 | 77,409 |
def compare_generator(x, y):
"""
Returns a textual description of the differences between the two
supplied generators.
This is done by first unwinding each of the generators supplied
into tuples and then passing those tuples to
:func:`compare_sequence`.
"""
x = tuple(x)
y = tuple(y)... | fb413853c17095ef21478b66774125e1e2e79c59 | 77,410 |
def is_right_angle_triangle(triangle: Triangle) -> bool:
"""Check if a given triangle is a right angle triangle."""
sorted_sides = sorted(triangle)
return sorted_sides[0]**2 + sorted_sides[1]**2 == sorted_sides[2]**2 | ff509c5211b863b76496196469d2ffe562a689d1 | 77,411 |
def signal2noise(*, rx_power, noise_power, **kwargs):
"""
Computes Signal-to-Noise ratio. Input parameters are in logarithmic scale.
:param rx_power:
:param noise_power:
:param kwargs:
:return:
"""
return db2lin(rx_power - noise_power) | 75aa09f72e64903dfe21043730d4372c20a04be3 | 77,412 |
import torch
def acos(x: Tensor):
"""Computes the element-wise arccos (inverse cosine)
Args:
x (Tensor): input tensor.
Returns: element-wise arccos
Examples:
>>> acos(to_tensor([[1,0.5],[-0.25,-0.75]])).cpu()
tensor([[0.0000, 1.0472],
[1.8235, 2.4189]])
... | 2947a30dbfd8d3e1247b81cecb838151330c020d | 77,413 |
import numpy
def stSpectralFlux(X, Xprev):
"""
Computes the spectral flux feature of the current frame
ARGUMENTS:
X: the abs(fft) of the current frame
Xpre: the abs(fft) of the previous frame
"""
# compute the spectral flux as the sum of square distances:
sumX = n... | 62fa26a029a79ea2c17d067eef98a458752df8da | 77,414 |
def iterparse_pi_xml(
fname,
ObsClass,
translate_dic=None,
filterdict=None,
locationIds=None,
return_events=True,
keep_flags=(0, 1),
return_df=False,
tags=("series", "header", "event"),
skip_errors=False,
):
"""Read a FEWS XML-file with measurements, memory efficient.
Pa... | b6867f35684d3d6a3159dfe957372735ddd057da | 77,415 |
def conv1d(x, w, stride=1, b=None):
"""Computes a 1-d convolution given 3-d input and weight arrays.
Parameters
----------
x : numpy.ndarray
Input data of shape `(batch_size, in_width, in_channels)`
w : numpy.ndarray
Weights array of shape `(filter_width, in_channels, out_channels)`... | 705dfec1f370c6313d52772c8e213b11a8e0b086 | 77,416 |
def get_Q_gen_x_d(exhaust, exhaust_priority, Q_PU_gen_d, r_DHW_gen_PU_d, r_HWH_gen_PU_d, L_DHW_d, L_HWH_d):
"""1日当たりの給湯・温水暖房の排熱利用量 (MJ/d) (9)(10)(11)
Args:
exhaust(bool): 温水暖房への排熱利用がある場合はTrue
exhaust_priority(str): 温水暖房への排熱利用がある場合の排熱の優先先
Q_PU_gen_d(ndarray): 1日当たりの発電ユニット排熱量 (MJ/d)
r_HWH... | dd5a9af99b1c19ea4f1531dc7f6401f5d637a96e | 77,417 |
def apply_palette256(image):
""" Get PIL to generate and apply an optimum 256 color palette to the given image and return it
"""
return image.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=256, dither=Image.NONE) | 19a6a640ebeff538bba8b7050a2ed30c79af591f | 77,418 |
def step_logistic_gradient(X, Y, learning_rate):
"""
One step of the gradient descent in logistic regression case
:param X: features matrix
:param Y: label array
:param learning_rate: learning rate of interest
:return: weights, bias, cost of the actual state
"""
global weights, bias # p... | b89c6baeb3170597df03e1e8cb6090ea79a6f0f3 | 77,419 |
def select_action_e_greedy(env, Q_values, epsilon = EPSILON):
"""
It selects a random action with probability epsilon, otherwise the best learned until now.
"""
if np.random.rand() < epsilon:
return np.random.randint(env.action_space.n)
else:
return np.argmax(Q_values) | 906dd04a120f2c28f6fc2571076eb9d7aff856e6 | 77,420 |
def convert_key_to_wf_metric(key):
"""A Wavefront metric name can be: 'Any lowercase, alphanumeric,
dot-separated value. May also include dashes (-) or underscores (_)'
For the purposes of sending data from Zabbix to Wavefront we replace any
whitespace or punctuation other than dash and underscore from the Zabbix ... | af60635ae04e8c13f56fda3de579b3b4f9b9b244 | 77,421 |
def is_sorted(iterable, key=lambda i: i, reverse=False):
""" Returns True if the iterable is sorted. """
i1, i2 = tee(iterable)
for a, b in zip(i1, sorted(i2, key=key, reverse=reverse)):
if a is not b:
return False
return True | 6f9146802e32075203114f06222ba3397f005e03 | 77,422 |
def broadcast_mul(lhs, rhs):
"""Binary multiplication with auto-broadcasting
Parameters
----------
lhs : tvm.Tensor
rhs : tvm.Tensor
Returns
-------
ret : tvm.Tensor
"""
return broadcast_binary_op(lhs, rhs, lambda a, b: a * b, "mul") | 6d2717926d2e9768532decf761508ff85d2f7479 | 77,423 |
def compute_weighted_profile_average(profile, attribute):
"""
:param profile:
:param attribute:
"""
return sum([getattr(entry, attribute) * weight for
entry, weight in profile]) / \
sum([weight for entry, weight in profile]) | 9bed1ff173c9cda9a88458ff1484d903a5ee2696 | 77,424 |
def gradient_n_pal(colors, values=None, name='gradientn'):
"""
Create a n color gradient palette
Parameters
----------
colors : list
list of colors
values : list, optional
list of points in the range [0, 1] at which to
place each color. Must be the same size as
`... | f109ba0479d7ae5fb05fdc7271f8f00ba64c7515 | 77,425 |
def shows_monthly_average_score_heatmap():
"""Monthly Average Score Heatmap Graph"""
database_connection.reconnect()
all_scores = show_scores.retrieve_monthly_average_scores(database_connection)
if not all_scores:
return render_template("shows/monthly-average-score-heatmap/graph.html",
... | dde4cbcd99a1184853fe770739ea60aadf27ac9d | 77,427 |
def add_redis(rname, ape=1):
"""Add to redis int."""
r.sadd('ape', int(ape))
r.set(ape, 1000)
r.set(rname, 'a nice value here')
return "added successfully".format(**locals()) | 21fa6a12cc62cfddc2408fef39e459df48096bc8 | 77,429 |
def prune(set_list):
"""
Prunes combinations that are not identical in symbols.
:param set_list: the list of sets containing nodes.
:return the pruned list
"""
symbol_set_list = [{symbol for _, _, symbol in current_set} for current_set in set_list]
return [sl for _, sl in list(filter(lambda... | 530c6be1df860bed87540ba2080096f2c318e9bf | 77,430 |
def biconnected_components(G, vertex_indices=None, edge_indices=None):
"""Partition by biconnected components.
Partition Type: Edge
Description: Given graph G and sets of both vertex and edge indices,
induce subgraph and partition vertices by biconnected components.
Args:
G (graph_tool... | 75a4ce36c95893d33f4f2be5e938db641c1182b1 | 77,431 |
def build_action(o, display, data, slot):
""" """
action = QtWidgets.QAction(display, o)
action.setData(data)
action.triggered.connect(lambda checked: slot(action))
return action | f19b5931e14a6eae07fa5caedb4ec2bad78f2949 | 77,432 |
def domains_to_xyt(xyt, domains):
"""
This function takes in xyt data and a list of domains and converts the list of domains into a list of
xyt points within those domains. This list can then be used to graph the domains onto the entire worm
path, for visualization.
:param xyt: A list of xyt points.... | 56bb2614d3f612913b19c550ed042e6a635ae4fa | 77,433 |
from typing import Union
from typing import Optional
def add_image(
session: Session,
dcm: Union[str, Dataset],
institution: str = None,
filepath: str = None,
) -> Optional[Image]:
"""Insert an image to the database. If the image belongs to a new patient, study, or
series, the relevant tables ... | 6c2106766435f945627308ef6e2f89183369fe30 | 77,434 |
def _get_gatk_opts(config, names, tmp_dir=None, memscale=None, include_gatk=True):
"""Retrieve GATK memory specifications, moving down a list of potential specifications.
"""
if include_gatk:
opts = ["-U", "LENIENT_VCF_PROCESSING", "--read_filter",
"BadCigar", "--read_filter", "NotPr... | ed2d30e8d6da86d4596234fdcf336a0ae9981e43 | 77,435 |
def _suspendWow64RedirectionForFileInfoRetrieval(func):
"""
This decorator checks if the file provided as a `filePath`
is placed in a system32 directory, and if for the current system system32
redirects 32-bit processes such as NVDA to a different syswow64 directory
disables redirection for the duration of the fun... | 49eaa59608ea35e5d0b5179de6c7f9ffa51de7ba | 77,436 |
def reaction(
depends_on_fn,
then_react_fn,
*,
fire_immediately=False,
include_previous=False,
):
"""a reaction takes two arguments: depends_on_fn and then_react_fn
the depends_on_fn is used to determine the dependcies that the then_react_fn depends on
when ever an atom attribute accesse... | 18c83cb584b188de2e318e0ce4039f4b03e6906c | 77,438 |
def replicaset_status(client, module):
"""
Return the replicaset status document from MongoDB
# https://docs.mongodb.com/manual/reference/command/replSetGetStatus/
"""
rs = client.admin.command('replSetGetStatus')
return rs | eb46cd1e28ecb1f2c6c5a222d176438677bd8e8c | 77,440 |
def decorator(arg):
"""Decorator with one argument."""
return lambda: list(arg) | 0a398352a99aeec22fab2c09e5ec9acce0c15e8e | 77,441 |
def user_activities(events: EventLog) -> UserActivity:
"""Calculate the set of activities UA performed by each user from the eventlog."""
UA: UserActivity = {}
for caseid in events:
for i in range(0, len(events[caseid])):
ai = events[caseid][i][0]
ui = events[caseid][i][1]
... | 229571ee3ee936c1d989b35af6facd63dc358797 | 77,442 |
def square_area(side):
"""Returns the area of a square"""
# You have to code here
# REMEMBER: Tests first!!!
return pow(side, 2) | ec00eca3752ad6394e47fd98d5c60b5427ed4142 | 77,443 |
import copy
import itertools
def param_generator():
"""
An iterable that returns a dictionary with training parameters at each
iteration.
"""
def setup_training(values, to_search):
parameters = copy.deepcopy(DEFAULT_KWARGS)
for key, val in zip(to_search.keys(), values):
... | ae88000bf52e7ee800b1488c2982e93dfa2a67ce | 77,444 |
from datetime import datetime
def datetime_to_ripple_time(dt: datetime) -> int:
"""
Convert from a `datetime
<https://docs.python.org/3/library/datetime.html#datetime-objects>`_ object
to an XRP Ledger 'Ripple Epoch' time.
Args:
dt: The datetime to convert
Returns:
The equiva... | 079ea9c2e7fae255f31e9a6d4552e141a8066734 | 77,445 |
import torch
def update_substruct(data, root_substruct, partial_charge, k):
""" Update substructures by adding contexts.
Args:
data (PyG Data object): the object to search context from.
substrcut (list): list of int, indices of atoms in the substructure.
mol (RDKit Mol)
parita... | 8ec8a82185989ca901e09e8b6decf9f650ba3d00 | 77,446 |
def _include_image_content(data):
"""Save the and build latex to include it."""
image_processors = [
('image/png', _process_png),
('image/svg+xml', _process_svg),
]
for mimetype, function in image_processors:
if mimetype in data:
fname = function(data[mimetype])
... | 3014cb848c64d9b633e9501ac3f5f5e04c51e4ac | 77,447 |
def new_user_form():
"""Display an HTML form for user creation."""
return """
<form action='/users' method='POST'>
Username: <input name='username' type='text'/>
Password: <input name='password' type='password'/>
Bio: <textarea name='bio'></textarea>
<button type='submit'>Su... | 1aeb4ba99ec5aa91bdc9c064da020e3eebb6b9ed | 77,449 |
from textwrap import dedent
def minimal_html_page(
body: str, css: str = "", title: str = "Standalone HTML", lang: str = "en"
):
"""Return a template for a minimal HTML page."""
return dedent(
"""\
<!DOCTYPE html>
<html lang="{lang}">
<head>
<meta charset="utf-8">
<title>{title... | 71397e60fefab240dbd0b173e437ef90be4b8493 | 77,450 |
def handle_chat(request):
"""HTTP Cloud Function that handles all chatbot requests."""
request_json = request.get_json(silent=True)
request_args = request.args
if request_json and 'name' in request_json:
name = request_json['name']
elif request_args and 'name' in request_args:
name ... | e5b1e9dc75b8e2c76c2b4bdc1a93315b6e9d0f43 | 77,451 |
from typing import Dict
def load_txt_community_file(edge_path: str, label_path: str, flag: str = ' ') -> Dict:
"""
Load edge list in .txt file and community label in .txt file
Args:
edge_path: the path of an edge list
label_path: the path of community labels
flag: the segment flag ... | 9f3614f25c37e0f2c07fdb6555c66d93ce697694 | 77,452 |
def load(filename, mesh=None):
"""
Load a skeleton from a json rig file.
"""
skel = Skeleton()
skel.fromFile(filename, mesh)
return skel | 66054d7f0e06e0f3d185db6ef45b9b1cf0422ca4 | 77,453 |
def rfft(tod, ft=None, nthread=0, axes=[-1], flags=None):
"""Equivalent to fft, except that if ft is not passed, it is allocated with
appropriate shape and data type for a real-to-complex transform."""
tod = asfcarray(tod)
if ft is None:
oshape = list(tod.shape)
oshape[axes[-1]] = oshape[axes[-1]]//2+1
dtype ... | d9b42d6f47dc8eb639b5b019d8e5aa53684a09ba | 77,454 |
def dicomweb_delete_study(
base_url, project_id, cloud_region, dataset_id, dicom_store_id, study_uid
):
"""Handles DELETE requests equivalent to the GET requests specified in
the WADO-RS standard.
"""
url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region)
dicomweb_path =... | 154e07eb8769c64f33c25abf6356360439890821 | 77,455 |
def req_req_drivers(row):
""" Show the driver(s) details """
if hasattr(row, "req_req"):
row = row.req_req
try:
req_ref = row.req_ref
type = row.type
except AttributeError:
return None
if type == 1:
s3db = current.s3db
stable = s3db.inv_send
... | 1ba14164fc761c83efaa6cfb61367233614bf0d1 | 77,456 |
def getChanprofPCrec(testDir):
""" Return a list of lists of ints containing the reconstructed channels for PCs
(same channels for each profile)
"""
chans = readIntList(testDir + '/in/channels_rec.txt')
if not chans:
return
profs = readIntList(testDir + '/in/lprofiles.txt')
# Add... | 2ba47878f653023fecbbf33c93be70cea163c09a | 77,457 |
def _common_strategies(choices):
"""Generate some common strategies to deal with multiple references."""
return {'min': min(choices),
'max': max(choices),
'avg': sum(choices) * 1. / len(choices)
} | ffe0070667aabe2ab8072bb39a6e452341780c41 | 77,458 |
def determine_transport(transports, url):
"""
Given a URL determine the appropriate transport instance.
"""
url_components = urlparse.urlparse(url)
scheme = url_components.scheme.lower()
netloc = url_components.netloc
if not scheme:
raise exceptions.NetworkError("URL missing scheme ... | 54fa4f430134d0de34b6786481af5e76ccc325bb | 77,459 |
def add_date_features(df, date_col, prefix="", drop=True, extra_features=None):
"""Extracts date features from a column in a dataframe and adds them to it.
Parameters
----------
df : pd.DataFrame
Pandas data frame to add the features.
date_col : str
Name of the column that holds the... | 2b0e977cee6355a57828fbe4b931b2721ef53390 | 77,460 |
def switch(key, funcs, *, default=None):
"""
Combine a dict of keyed functions to form a new function.
The result is a function ``f(*args, **kwargs)`` that returns
``apply(funcs[key(*args, **kwargs)], *args, **kwargs)``.
If ``key(*args, **kwargs)`` is not in ``funcs`` but ``default`` is present,
... | d4e67633347da5261c4bfa92313477605ba7cebf | 77,461 |
def _visualize_attention_map(attention_map_tensor, name):
"""
:param attention_map_tensor:
:param name
:return:
"""
with tf.variable_scope(name_or_scope=name):
max_val = tf.reduce_max(attention_map_tensor, axis=[1, 2], keepdims=True)
min_val = tf.reduce_min(attention_map_tensor,... | b8c0287554c676b28457af4ff3f6238fa9045040 | 77,462 |
import struct
def doubleToRawLongBits(value):
"""
:param value: A float value
:return: The IEEE 754 biit representation of the given double-precision floating-point value.
"""
return struct.unpack('Q', struct.pack('d', value))[0] | 8c5c525e481a50225a6bd99fffbd7fb0555aba79 | 77,463 |
def _conv3p_grad(op, grad_from_next_layer):
"""The derivatives for convolution.
Args:
op: the convolution op.
grad_from_next_layer: the tensor representing the gradient w.r.t. the output
Returns:
the gradients w.r.t. the point tensor, input tensor, and the filter
"""
points =... | bb651772dc63333f66e8b62c9591aca086aa3d80 | 77,464 |
def get_enrolled_students(course_id):
"""
Given a course_id, returns a QuerySet of all the active students
in the course.
"""
objects = UserProfile.objects
course_key = CourseKey.from_string(course_id)
students = objects.filter(user__courseenrollment__course_id=course_key,
... | 8c7d7db70716e8b8bbf5f695d5bc22294c7d0ae3 | 77,465 |
def see_enzyme_misc_info_list():
"""
Get's the data about all miscellaneous info in the DB to put on a table:
- ID
- topic
- enzyme
- reaction
- organism
Returns:
render_template to see_data with tab_status set to enzyme_misc_info.
"""
tab_status = {"enzymes": "#",... | 1a358a50e28d38e07f40e502e24729b05a388b03 | 77,466 |
def emit_futil(program) -> str:
"""Lowers a Relay function to a FuTIL program."""
relay_program = relay_transforms(program)
visitor = Relay2Futil()
main, func_defs = visitor.visit(relay_program)
return '\n'.join((
Program(
imports=[Import("primitives/std.lib")],
compo... | b617db2ec2178f57f4c16e897565185f3812a154 | 77,467 |
def FullyConnected(x, out_dim,
W_init=None, b_init=None,
nl=tf.identity, use_bias=True):
"""
Fully-Connected layer, takes a N>1D tensor and returns a 2D tensor.
It is an equivalent of `tf.layers.dense` except for naming conventions.
Args:
x (tf.Tensor): a t... | 9d0b6a4213a9099e7e1e1516f228fcea0cfc7fdd | 77,469 |
import re
def tokenize(text, regex=r'[a-zA-z]+'):
"""Split text into tokens using a regular expression
:param text: text to be tokenized
:param regex: regular expression used to match tokens using re.findall
:return: a list of resulting tokens
>>> tokenize('the rain in spain')
['the', 'rain', 'in', 'sp... | c7daee14ec14ff4a22d42883f3b3e3827924389e | 77,470 |
def UPGMA_cluster(matrix, node_order, large_number):
"""cluster with UPGMA
matrix is a numpy array.
node_order is a list of PhyloNode objects corresponding to the matrix.
large_number will be assigned to the matrix during the process and
should be much larger than any value already in the matrix.
... | 6afacd5f8223243b4f5f89853ed1e7b8a8218e0c | 77,471 |
def getAddressFromNetwork(testnetAddr, mainnetAddr):
"""
Checks if network is in the list of testnets
If so, returns testnet address
If not, returns mainnet address
"""
testnets = [
'arbitrum-rinkeby',
'rinkeby'
]
if network.show_active() in testnets:
return test... | 56e3d9608b24cfbcb09ebe59d9a74466d69961ee | 77,472 |
import json
def run(
experiment,
*,
trials: int = DEFAULT_TRIALS,
device: str = "cpu",
force: bool = False,
model: str = "PairRE",
metric: str = DEFAULT_METRIC,
):
"""Run a single benchmark experiment."""
digest = get_digest(experiment)
model = model_resolver.normalize(model)
... | 5be975993da2fa919a3cb020235e139b287d03e4 | 77,473 |
import numpy as np
def collection_process_fl(nrtd,method='avg'):
""" makes a 'dircube, which is a 3-d dataset corresponding to
(laser_dimension, wavenumber dimeion, imaging_x_position dimension)
laser_dimension: this is the number of usable pixels in the laser line.
each corresponds roughl... | de5c55b4dac288ea42a955f1735f8a7f952548d8 | 77,474 |
import types
def is_integer(n):
"""
Returns True if n is an integer type of any kind
"""
return type(n) in (types.IntType, int32, int64, int0, int16, int8, types.LongType) | 577e92307c464fe156750892fcfe8ee8f4379ab0 | 77,475 |
def generate_id(length=10, split_every=5, checksum=True) -> str:
"""Generate random base32 string: a user-shareable ID for a database entity.
Uses Douglas Crockford Base32 encoding: <https://www.crockford.com/base32.html>
Default is 8 characters (5-bits each) plus 2 digit characters for ISO 7064 checksum,... | a3fd986299aa3f780eb271b3dc0d2d6492c6bfaf | 77,476 |
import math
def round_up(x, sig=2):
"""Round up to a given number of significant digits."""
dig = pow(10., sig - int(math.floor(math.log10(abs(x)))) - 1)
return math.ceil(x * dig) / dig | f881d82958f6b331a5e6b46ddc17e1abdc6ad37d | 77,477 |
def str_to_border_mode(s):
"""
http://docs.opencv.org/modules/imgproc/doc/filtering.html
Various border types, image boundaries are denoted with '|'
BORDER_REPLICATE: aaaaaa|abcdefgh|hhhhhhh
BORDER_REFLECT: fedcba|abcdefgh|hgfedcb
BORDER_REFLECT_101: gfedcb|abcdefgh|gfedcba
BOR... | 5bee686a18e0340fc1b059ccc4044ff0b78b0e1e | 77,478 |
import re
def get_importances(alphas, betas, patient_data, model_parameters, dictionary, path_icdpath='data/CMS32_DESC_LONG_DX.txt', code_prefix='D_'):
"""Construct dataframes that interpret each visit of the given patient"""
icd9dict = read_icd9dict(file=path_icdpath, widths=[5, 10000])
importances = []... | 81f116a8302e28b2eafef128080f6f19143ad1dd | 77,479 |
import scipy
def spiral_to_trimesh(radii, unitspiral, origin):
"""Spiral to mesh via a triangulation of the unitspiral's rays"""
# Convert radii to xyz points
point_cloud = spiral_to_point_cloud(radii, unitspiral, origin)
# How would we mesh the original unit-circle spiral?
faces = scipy.spatial.C... | 910c1271df1199c99fb65449ebe9a57cfe2dc041 | 77,480 |
def signal_integral(sampled_signal):
"""Calculates the integral of the signal using the composite Simpson's rule
Parameters
:param sampled_signal: ndarray
The signal used to calculate the area under the curve
:return: float
Area under the curve
"""
return integrate.simps(sampled_... | ba79f2d83223c3b1bd615d40ca939fda4ddcc79d | 77,481 |
def toOrdinal(n):
"""
Returns the ordinal name of a number
e.g. 'first'
"""
if n == -1:
retval = _("last")
elif n == -2:
retval = _("penultimate")
elif 1 <= n <= 5:
retval = _n2w(n, to="ordinal")
else:
retval = _n2w(n, to="ordinal_num")
return retval | a23afe1d9b34ecc300d01a48e118d1c3cc78b0c9 | 77,482 |
def sgld_mh_noresample_uni(u_hat_func, du_hat_func, epsilon, nt, m, M, V, theta_init, r_init, formula):
"""
This is a function to realize Stochastic Gradient Langevin dynamics with
Metropolis-Hastings correction in unidimensional cases without resampling
procedure.
"""
B = 1/2*epsilon*V
th... | bc0c3ae0c67eaf9cbc4eff83bd3259893ba78335 | 77,484 |
def cover_phone_number(no):
"""
>>> cover_phone_number('01234 567 890')
'01234 *** *** **'
"""
result = ''
for order, digit in enumerate(no):
if order < 5:
result = result + digit
else:
if order in (5, 8, 11):
result = result + ' '
... | d33d98e915135644119a66d39ac8f9fc80770d62 | 77,485 |
def apply_response_headers(response: Response) -> Response:
"""Apply response headers to all responses."""
"""Prevent UI redress attacks."""
response.headers['Content-Security-Policy'] = "frame-ancestors 'none'"
response.headers['X-Frame-Options'] = 'DENY'
return response | 3ea76eaa680d7f9cae65b81a45b21661c8f987cc | 77,486 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.