content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)
... | 5d85f71a1c904009f73ef0a8b5cf3f9aa4c6302b | 72,980 |
import time
def eof(scheme, tests=10000, prob=None):
"""
:param scheme: Input scheme.
:param tests: Number of tests.
:param prob: Probability of error in single element. If None, prob will be set on 1 / scheme.elements().
:return: Probability of scheme failure.
"""
if prob is None:
... | 313a9bd2616199065ece9bfcf7ab192fc6863b26 | 72,982 |
def str2ms(s):
"""
Convert the time strings from an SRT file to milliseconds.
Arguments:
s: A time value in the format HH:MM:SS,mmm where H, M, S and m are
digits.
Returns:
The time string converted to an integer value in milliseconds.
"""
s = s.strip()
time, ms ... | 552f9ffbd557cc0729c035901dc1a1a1bfae66d8 | 72,984 |
import warnings
def nan_circmean(samples, high=2.0*np.pi, low=0.0, axis=None):
"""NaN insensitive version of scipy's circular mean routine
Parameters
-----------
samples : array_like
Input array
high: float or int
Upper boundary for circular standard deviation range (default=2 pi)... | 1634d72d3b0a1447aafb8d2f00453c8b8af7c25d | 72,986 |
from typing import Dict
from typing import List
from datetime import datetime
async def compose_upcoming(start_date: str, end_date: str) -> str:
"""
Get the list of episodes between start_date and end_date and format them as a list, grouped by day, highlighting current day and file-status of episodes
:par... | 70e82c17e89252758a5f921c170ee16e71e413fa | 72,987 |
def getEscalation(E, arg=None) :
"""Return escalation of event's primary alert."""
if isinstance(E, dict) : E = Event.objects.get(pk=E['id'])
A = E.get_primary_alert()
if A is None : return None
R = A.reference
if R : return R.escalation_contact
else : return None | 9d04a92440eeb0a45ec900f3b42dd3bad34e6620 | 72,988 |
from .Interactive import Interactive as interactive
def interactive():
"""
An application shell based on {script} that enters interactive mode after the application
is finished running
"""
# grab the component class record
# and return it
return interactive | cc00b4ced10b43268de6cc7d580a368ff2b50030 | 72,991 |
def pipeline_function(fn):
"""Create a pipeline step from a function.
The provided function must receive `self` as its first argument, and
then the pipeline fields it needs (the variable names are inspected
by the pipeline to determine what values to give this step).
"""
class PipelineStepFunct... | 9c33e46aac4cb799d9ab4c3ddab76f3ec96c4201 | 72,992 |
import warnings
def peth(sts, w, t_start=None, t_stop=None, output='counts', clip=False):
"""
Peri-Event Time Histogram (PETH) of a list of spike trains.
Parameters
----------
sts : list of neo.core.SpikeTrain objects
Spiketrains with a common time axis (same t_start and t_stop)
w : Q... | 3d8e95b599fdfdb06068b3f37016e21fff111dc8 | 72,993 |
def create_corresponds_to_df(leads_to_df):
"""
Creates the dataframe for the corresponds_to relationship and the nodes for the intents table.
Eliminates duplicate nodes from the leads_to table
and reassigns new IIDs to these nodes. Labels nodes with their node type {root, internal, terminal}.
Also a... | 204dfb9d581e5f0ac2de94bec59d0ba492b4d1a1 | 72,995 |
def get_threecommas_account(accountid):
"""Get account details."""
error, data = api.request(
entity="accounts",
action="",
additional_headers={"Forced-Mode": "real"},
)
if data != {}:
for account in data:
if account["id"] == accountid:
market... | 3d48a24e09cfe81f09e61657452fdb6076108b27 | 72,996 |
import collections
def find_apache_memory_usage(exe_name='apache2'):
"""
Find the memory usage of Apache workers.
:param exe_name: The base name of the Apache executable (a string).
:returns: A tuple of two values:
1. A :class:`StatsList` of integers with the resident set size
... | 6b239650452e465ee6cf5033a953e64f085aed10 | 72,997 |
def modify_error(lc, error_floor=0.):
"""Add an error floor of `error_floor` times the maximum flux of the band
to each observation
"""
data = sncosmo.photdata.photometric_data(lc).normalized(zp=25., zpsys='ab')
new_lc = {'time': data.time,
'band': data.band,
'flux': data... | ca6291ba94819cd295d4d8a4f98eb19b213916dc | 72,998 |
def __get_delta_jg(spectrum, sig_matrix):
"""
Initialize the probability matrix of each mutation in the spectrum originating from the given signature.
:param spectrum: Original spectrum to decompose. (numpy.array)
:param sig_matrix: The matrix containing the weights of each mutational type in each ref... | 23327ec7b47404d7531bb68f473439969eece50f | 72,999 |
def admin_get_user(action):
""" Gets a user by email; login must be included in the POST. Calls the
response method of the User Object associated with <action>. """
utils.check_api_key()
# try to get the 'login' var from POST JSON; fallback to form content
try:
user_login = flask.request.g... | 8a244978b6e0fb499b02545f6243d438a07ec0ac | 73,000 |
def homography_adaptation(image, net, config):
"""Perfoms homography adaptation.
Inference using multiple random warped patches of the same input image for robust
predictions.
Arguments:
image: A `Tensor` with shape `[N, H, W, 1]`.
net: A function that takes an image as input, performs i... | 86766a0656c960bf71b7fb08d08c03d9f34ae8ed | 73,001 |
def get_most_recent_bundle(key):
"""
Returns the most recent bundle for the given key.
:param key:
:return:
"""
max = {'updated': '01-01-1965 00:00:00Z'}
for version in bundles[key].keys():
bundle = bundles[key][version]
if parse(bundle['updated']) > parse(max['updated']):
... | bbecb4c576e5046dbc331358a247653a824a0174 | 73,002 |
def get_image_dimensions(img_file):
""" return width, height """
shape = load_image_as_numpy_array(img_file).shape
width = shape[1]
height = shape[0]
return width, height | 9b96d79e6f3a16d84093b3174ab25f155fcae8bf | 73,003 |
def create_record():
"""Creates a record from user input.
Asks the user for name, age, and height. Then prints the possible record.
Only if the user accepts with 'y' or 'Y', the record is returned.
Otherwise, the user is asked again.
Returns:
A dictionary representing a person.
"""
... | a916ef25b63e9cfee2788bcae2c16db3719f5e3f | 73,004 |
def euler_curve(diagram, m=101, k_max=None, f="linear", **kwargs):
"""
Return an m-dimensional array of Euler characteristic up to dimension k_max.
Parameters
----------
diagram: list of ndarrays
list of arrays of k-dimensional persistence diagram
m: int or list of floats or ndarray of ... | 727e0de5a6ab5a268f37b7740ea40a8678568c35 | 73,006 |
import json
def read_config():
"""Retrieve config."""
with open(CONFIG) as f:
config = json.load(f)
return config | 0c628424d3e3a7726ac607cb02ccb25dcab89482 | 73,007 |
import re
async def eval_command(ctx: lightbulb.context.Context) -> None:
"""
Dynamically evaluate a script in the bot's environment.
This can only be used by the bot's owner.
Example:
;eval ```py
for x in range(5):
print('Hello World')
```
"""
assert ctx.event.message is ... | 9001d4fbb05bed7fdbc8eb85129f3d784c8ed7fb | 73,008 |
def diameter(G, e=None, usebounds=False):
"""Return the diameter of the graph G.
The diameter is the maximum eccentricity.
Parameters
----------
G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
Returns
-------
... | f5a1a3238fb8ab2f236d2ddd355bb0d030f5f2fb | 73,009 |
def remove_redundant_objs(objs, cmp_f):
"""Remove redundant objects from objs and return non-redundant objects.
objs --- a list of sorted objects.
cmp_f --- cmp_f(aobj, bobj) return 0 if aobj 'equals' bobj and -1 if aobj is less than bobj, and 1 otherwise.
"""
ret = []
for obj in objs:
i... | 405d2193b74e46e65637563bb664d3a7c0dd8740 | 73,010 |
def make_sg_rules(cidrs=None, group_ids=None, ports=None, proto="tcp"):
"""
Args:
cidrs: (list): List of cidr blocks to add to the security group
rules.
group_ids: (list): List of group_uds to add to the security group
rules.
port_ranges: (list): List of ports to ... | f0da2b108ebd82bf20777a2c870c5d211f809e6a | 73,011 |
from datetime import datetime
def create_article(title, text, days):
"""
Create a article with the given `title` and `text`. Published the
given number of `days` offset to now (negative for articles published
in the past, positive for articles that have yet to be published).
"""
time = timezon... | b63ddc9a60f5d1ccad0d188f6be2e360777cf1c1 | 73,012 |
def surface_fit(struct,order=3, mask=True, minlevel=0):
"""Fit a surface to an image
return struct
"""
# Determine the number of extensions
nextend=len(struct)
#flat field the data
for i in range(nextend):
if struct[i].name=='SCI' or len(struct)==1:
#create the med... | a7f122901fd2562816eb8574c16a099d1486d7ae | 73,013 |
def tensor_polar2cartesian(x):
"""
x: tensor of the shape [size, 2] (polar coordinate)
return: tensor of the shape [size, 3] (cartesian coordinate)
"""
return tf.stack(
[tf.cos(x[:, 0]) * tf.sin(x[:, 1]),
tf.sin(x[:, 0]) * tf.sin(x[:, 1]),
tf.cos(x[:, 1])],
... | a4f86da197f0ff8d3e1d75269bfbdbd3d0633ed8 | 73,015 |
def build_numpy_array(fnames):
"""return numpy array built from data read from list of filenames"""
arr = np.empty((0, 1), dtype=np.float32)
print 'building array...'
for fname in fnames:
# read data from file
a = padread(fname, columns=1)
a[:, 0] = a[:, 0] - a[:, 0].mean(axis=0)... | 27a4487439ef0145570005d9eb0870222134b5b9 | 73,017 |
from sherpa.astro.data import DataARF
from sherpa.astro.instrument import ARF1D
def derive_identity_arf(name, arf):
"""Create an "identity" ARF that has uniform sensitivity.
*name*
The name of the ARF object to be created; passed to Sherpa.
*arf*
An existing ARF object on which to base this o... | ab9c0666a100fd9c4b67c09d82a6ec3669f9e3d2 | 73,018 |
from typing import Dict
from typing import Optional
def visitor(request: HttpRequest) -> Dict[str, SimpleLazyObject]:
"""Add visitor context to template context (if found on the request)."""
def _get_val() -> Optional[dict]:
if request.visitor:
return request.visitor.serialize()
r... | a09f718f918ae1c7b95f0d94fb4a7273f176c1b1 | 73,019 |
def parse(file):
"""parse out information from data_text and get information about image size, and class names"""
(str_height, str_width, str_names) = file.readlines()[0].split("*")
(height, width) = (int(str_height), int(str_width))
names = str_names.strip("][").replace("'", "").split(", ")
return... | 554bc1bf07671aecbe7da2ba2cfbb0bd51aa511c | 73,020 |
def ISTEXT(*args) -> Function:
"""
Checks whether a value is text.
Learn more: https//support.google.com/docs/answer/3093297
"""
return Function("ISTEXT", args) | a20bf55e4c15d88a7312e54d799bef94bf43f364 | 73,021 |
def CityscapesConfig(argument_parser):
"""
Set CLI arguments
:param argument_parser: argument parser
:type argument_parser: ```ArgumentParser```
:return: argument_parser
:rtype: ```ArgumentParser```
"""
argument_parser.description = """`Cityscapes <http://www.cityscapes-dataset.com/>`_... | 3908c2a7e19495775cea0ac5e15ff745545e961d | 73,022 |
def get_game(i: int, cfg: Config = None):
"""
Create a game-object.
:param i: Game-ID
:param cfg: Config object
:return: Game or GameCy object
"""
config = cfg if cfg else Config()
return Game(game_id=i,
config=config,
silent=True) | 59c8a530ae3c71557f49309d1eb1b1d2e4ee6bc6 | 73,023 |
def rsync_project(remote_dir, local_dir=None, exclude=[], delete=False,
extra_opts=''):
"""
Synchronize a remote directory with the current project directory via rsync.
Where ``upload_project()`` makes use of ``scp`` to copy one's entire
project every time it is invoked, ``rsync_project()`` uses th... | 276a9d71382915f319a644aba1a28665cd6b504f | 73,024 |
def burninConvergence(lnprob, tol=0.25, slice_size=100, cutoff=0):
"""Checks early lnprob vals with final lnprob vals for convergence
Parameters
----------
lnprob : [nwalkers, nsteps] array
tol : float
The number of standard deviations the final mean lnprob should be
within of the ... | 70bace0b3fa38fb891b8c17acf6007c7c6bc5082 | 73,025 |
from typing import Optional
def solve(program: MPQP_Program, active_set=None, num_cores=-1) -> Optional[Solution]:
"""
This solved the multiparametric program using the geometric algorithm described in Spjotvold et al.
https://www.sciencedirect.com/science/article/pii/S1474667016369154
:param progra... | a257cefd25811f9c7fb484b76d50cf522a12f4a2 | 73,026 |
def generate_and_embed_metadata(music_file, id, clientKey, clientSecret):
"""Fetch a song's metadata from Spotify."""
# token is required to grab metadata
token = generate_token(clientKey, clientSecret)
spotify = spotipy.Spotify(auth=token)
try:
meta_tags = spotify.track(id)
except:
... | 5503090d8dc7e242746b7d6f38628e34312e5f81 | 73,027 |
def unify(left, right, substitution):
"""unify is a helper function and the core for eq. unify will
recursively look up both `left` and `right` in substitution using the `walk`
function.
After getting each of their associated values, they are compared.
If they are equal either as variables or li... | 71c8be6c189e8beac8afc7cb6271844e9870373c | 73,028 |
def get_data(name: str, override: bool=True) -> str:
"""
Obtiene el contenido del archivo SVG que coincida con el nombre.
Si override es False, se lanzará una excepción en caso de no encontrar el
archivo con el nombre indicado.
"""
if "/" in name:
name = name.split("/")[-1]
if not ... | 68bd843f250c13c53ed1466b38c5ea43572cdf1f | 73,029 |
def hamiltonian(position, velocity, energy_function):
"""Computes the Hamiltonian of the current position, velocity pair
H = U(x) + K(v)
U is the potential energy and is = -log_posterior(x)
Parameters
----------
position : atreus_ml.Variable
Position or state vector x (sample from the ta... | f4fba2d856a43c726e14f656f069a0505fe94846 | 73,030 |
def hardmax(data, axis):
"""hardmax operator.
Parameters
----------
data : tvm.te.Tensor
input data
Returns
-------
out : tvm.te.Tensor
Tensor with shape same as input data.
"""
def _hardmax(data, out_buf, axis):
ib = tir.ir_builder.create()
input_... | 0117681ad87ab3687dfe8817ff34aebdfa724d54 | 73,031 |
from typing import Dict
import math
def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float:
"""Compute the distance between two positions."""
return math.sqrt((a['x'] - b['x'])**2 + (a['y'] -
b['y'])**2 + (a['z'] - b['z'])**2) | c6b29c8e84c4d8f15c27f32e7f9d2a13ecf6fd45 | 73,032 |
import torch
def get_device(inputs):
""" Get used device of a tensor or list of tensors. """
if isinstance(inputs, torch.Tensor):
device = inputs.device
elif isinstance(inputs, (tuple, list)):
device = inputs[0].device
else:
raise TypeError(f'Inputs can be a tensor or list of t... | eb67cb3a5ae226c4136bc172d37225ba6a64b45f | 73,033 |
import uuid
def _wrapper(wrapped, instance, args, kwargs):
"""
General wrapper for requests instrumentation.
:param wrapped: wrapt's wrapped
:param instance: wrapt's instance
:param args: wrapt's args
:param kwargs: wrapt's kwargs
:return: None
"""
# Inject header to support tracin... | 079962c0e43f469ed9f104c47933dd221d6be2a4 | 73,034 |
from typing import List
def get_nested_fieldnames(csv_entries: List[dict]) -> set:
"""Fieldnames with '.' should be converted to nested dictionaries. This function will return a set of
fieldnames for nested dictionaries from the highest to second lowest levels.
E.g these fieldnames: dc.date.available, dc.... | c1e4b7ff1349200eda43b82c36ca682862b48260 | 73,036 |
def cvSplit(*args):
"""cvSplit(CvArr src, CvArr dst0, CvArr dst1, CvArr dst2, CvArr dst3)"""
return _cv.cvSplit(*args) | dab91ff4994592a4d8d2ab0f9a56cbf1378ca9af | 73,037 |
def pythagorean_distance_equation(path1, path2):
"""Pythagorean Distance Equation.
Function for counting distance,
derived from the Pythagorean theorem.
"""
# point path dot X1
dotX1 = path1[0]
# point path dot X2
dotX2 = path2[0]
# point path dot Y1
dotY1 = path1[1]
# p... | a16f9d2a3f4ba824ebeb020ed2e5b1bb4068cc0e | 73,038 |
import re
def cleaning(token):
""" This function will remove unnecessaries values in the sentence i.e links, emails, and punctuations
"""
link = r'(https?:\/\/[^\s]+)|(www\.[^\s]+)|(meet\.google\.[^\s]+)|(bit\.ly[^\s]+)'
email = r'([a-zA-Z0-9\.\_\-]+@+[a-zA-Z0-9.]+)'
punct = r'[^a-zA-Z0-9\[\]]'
... | 63eabc07eb69238f34a7d98a397aa41b2dbb2624 | 73,039 |
def _many_z_to_single_z(focal_qubit, pauli_sum):
"""Convert many Z's to single Z.
Returns the gate set required for transforming an arbitrary tensor product
of pauli-z's into a product of all identites and a single pauli-Z.
Args:
focal_qubit: central qubit among CNOT gates.
pauli_sum: `c... | d65e1db0c9ea1a7912630d6810ed03ef4b7c312e | 73,040 |
def _pack_with_tf_ops(dataset, keys,
length):
"""Helper-function for packing a dataset which has already been batched.
Helper for pack_dataset() Uses tf.while_loop.
Args:
dataset: a dataset containing padded batches of examples.
keys: a list of strings
length: an dict from fea... | 94b7896f64381bcf17eaa73213e52ad107f45a0f | 73,042 |
def vendor_view(request):
"""
Render main view for vendors.
:rtype: HttpResponse
"""
user = request.user
if user.is_authenticated():
vendor = Vendor.get_vendor(user)
items = Item.objects.filter(vendor=vendor)
else:
items = []
context = {
'user': user,
... | 91996baeecf38cf74cde9b55d305bbb879d54abb | 73,043 |
from typing import Dict
def create_column_translation(path: str) -> Dict:
"""Translates an excel sheet of column name links to a dict of column name translations"""
link_dataframe = read_excel(path)
translated_columns = {}
# Transform dataframe to dict
data_dict = link_dataframe.to_dict("index")
... | b01ec956df1e745b8597c4d4f0ee2f6884dea9c1 | 73,044 |
def G3_prime(crystal, i, e_type, ni, functional='Cosine',
Rc=6.5, k=10, p=1, q=0):
"""
Calculate derivative of the G3 symmetry function.
Parameters
----------
crystal: object
Pymatgen crystal structure object.
i: int
The index of core element.
e_types: str
... | 3b3fd994201dcdfd9be2a34deea27d021bb68d35 | 73,045 |
def _read_pdas(filename, **kwargs):
"""
Reads a PDAS file and returns an ObsPy Stream object.
.. warning::
This function should NOT be called directly, it registers via the
ObsPy :func:`~obspy.core.stream.read` function, call this instead.
:type filename: str
:param filename: PDAS ... | 503422c1959bb28c4b6972baffd189a724bcd2a1 | 73,047 |
from typing import Sequence
from typing import Optional
from typing import Tuple
def welch_ttest(first_set: Sequence[Trace], second_set: Sequence[Trace], dof: bool = False, p_value: bool = False) -> Optional[Tuple[CombinedTrace, ...]]:
"""
Perform the Welch's t-test sample wise on two sets of traces `first_se... | 240a6afae15d9f93b0f344710d9338c98b1aa9d6 | 73,049 |
def ga_optimise_from_args(func_caller, worker_manager, max_capital, mode, mutation_op,
is_rand=False, crossover_op=None, options=None,
reporter='default'):
""" GA optimisation from args. """
if options is None:
reporter = get_reporter(reporter)
options = l... | af0bf2e7cec99618ccc306086eeea2949b1c5b8c | 73,050 |
def MaybeGetKmsKeyFromDict(args, messages, current_value):
"""Gets the Cloud KMS CryptoKey reference for a boot disk's initialize params.
Args:
args: A dictionary of a boot disk's initialize params.
messages: Compute API messages module.
current_value: Current CustomerEncryptionKey value.
Returns:
... | ba930480f1442a96acb3899faee65241ee89a9ba | 73,051 |
def parse_module_lines(lines, net_manager):
"""
Parse lines that make up a module. Add the module to the proper nets using
the specified NetManager.
Returns an IvlModule object.
"""
module_meta = lines[0]
module_data = lines[1:]
name, supertype, module_type_raw, inst_type = module_meta.... | 5e848da7d2d785eccb675c68380d7c383a350b47 | 73,052 |
def read_data(input_path):
"""Read nasdaq stocks data.
Args:
input_path (str): directory to nasdaq dataset.
Returns:
X (np.ndarray): features.
y (np.ndarray): ground truth.
"""
df = pd.read_csv(input_path)
df_no_date = df.drop(["Close", 'Date'], axis=1)
X = df_no_date... | 85fb3091f5e07d83b2aece682aef634f2dba1212 | 73,055 |
def test_configurable__get_partial():
""" Test if `@configurable#get_configured_partial` is able to export a partial with expected
configuration.
"""
@configurable
def configured(arg):
return arg
expected = ''
add_config({configured: HParams(arg=expected)})
partial = configured... | 2b4c744a425bfe5fa0dd0ff4f4342b6808c17bc7 | 73,056 |
def parse_xform_instance(xml_str):
"""
'xml_str' is a str object holding the XML of an XForm
instance. Return a python object representation of this XML file.
"""
xml_obj = minidom.parseString(xml_str)
root_node = xml_obj.documentElement
# go through the xml object creating a corresponding p... | 73be29233b5c54b1aaf76cead029cc82fe2889b8 | 73,057 |
def generate_output_filename(file_name, suffix, file_type="csv"):
""" Adds a suffix to the input csv to track progress through data pipeline. """
parts = file_name.split('.')
if len(parts) == 2:
output_filename = parts[0] + suffix + '.' + file_type
return output_filename | 20352bb31b4e56202b85f88f15c2eefcbb76d9c7 | 73,058 |
from sklearn.externals.joblib import Parallel, delayed
import copy
def mcc_rgb(
data,
scales=[0.5, 1, 1.5],
tols=[0.3, 0.3, 0.3],
threshs=[1, 0.1, 0.01],
training_scales=None,
training_tols=None,
n_train=int(1e3),
max_iter=20,
n_jobs=1,
seed=None,
use_las_codes=False,
v... | d210a73363e8f7c47061118708ad2cd0cdbaaf49 | 73,059 |
def broadcast(tensor, src, group=None, async_op=False):
"""
Broadcasts the tensor to the whole group.
``tensor`` must have the same number of elements in all processes
participating in the collective.
Args:
tensor (Tensor): Data to be sent if ``src`` is the rank of current
proc... | b81eae02c8b14e1d349e503e1426c45c6c1eca0a | 73,060 |
import base64
def get_chubby_bat_img_base64():
"""
:return: bytes
"""
with open(CHUBBY_BAT_IMAGE_PATH, 'rb') as fp:
return base64.b64encode(fp.read()) | 00da9bc3498283ea172db866fddd9e2779bb0354 | 73,062 |
def get_county_hospitals():
"""
Get county hospital inpatient v outpatient statistics
"""
mysql = MySQL.MySQL(MYSQL_URL, MYSQL_USER, MYSQL_PASS)
data = mysql.get_county_hospitals()
return_package = {
'data': data
}
del mysql
return jsonify(return_package) | f5886b3ab13812c296e70ccb2ec58a397c537ab4 | 73,063 |
from typing import Tuple
from typing import Any
from typing import Set
def neighbors(quilt: Tuple[Tuple[Any, ...], ...], x: int, y: int) -> Set[Any]:
"""
Get the color of all neighbors.
.. note::
The color of block (`x`, `y`) is included in the colors returned.
:param quilt: The quilt conta... | 3237e86d2beaeefb8b76dfeed10720b1ee37bf43 | 73,064 |
from typing import Union
from typing import Dict
from typing import Any
import typing
def Checkbox(
description: str = "",
description_tooltip: str = None,
disabled: bool = False,
indent: bool = True,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
style: ... | 06c9d8a0a32eecff56e06cbe5647615bdd3a44f5 | 73,065 |
import json
def directory_researches_group(request):
"""GET: получение списка исследований для группы. POST: добавление новой или выбор существующей группы и привязка исследований к ней"""
return_result = {}
if request.method == "GET":
return_result = {"researches": []}
gid = int(request.G... | 0a1821ee1ccf8c8167ac81d6950cd3c4a722715a | 73,066 |
def get_model_list(session):
"""Return a list of all models, for advanced search."""
model_list = (session
.query(Model.bigg_id)
.order_by(Model.bigg_id)
)
list = [x[0] for x in model_list]
list.sort()
return list | 02d19214fc91161ecfe546ebbea51f25cc01c6a2 | 73,067 |
def score_multithreshold(pred, gt, shore_root, distance_tolerance=200, shore_tolerance=2, costly_dist=False) -> pd.DataFrame:
"""Compute xView3 aggregate score from
Args:
pred ([pd.Dataframe)): contains inference results for all scenes
gt (pd.Dataframe): contains ground truth labels for all sce... | 23518eb95e2f6fc8c1f37e224dd4db14e166e7b3 | 73,068 |
def quick_sort(sequence: list) -> list:
"""Simple implementation of the quick sort algorithm in Python
:param sequence: some mutable ordered collection with heterogeneous comparable items inside
:return: the same collection ordered by ascending
"""
if len(sequence) < 2:
return sequence
... | 73470224b8f149568b84c7b723097fc0c2ef353f | 73,070 |
import csv
from datetime import datetime
def get_weather_modifications(csv_file):
"""
Given a CSV file like:
DATE,PRCP,TAVG
01/01/2001,0,-6
01/02/2001,0,-7
01/03/2001,0,-8
where PRCP is in CM and TAVG is in C, converts it into a JSON
modifications object that can override gis_data. A... | 31cd78a67ff1f511b46cf510318e570b83013c3b | 73,071 |
def _is_gradient_task(task_id, num_tasks):
"""Returns True if this task should update the weights."""
if num_tasks < 3:
return True
return 0 <= task_id < 0.6 * num_tasks | 11d37b1095e40ef0be840c63a0c184e63630e945 | 73,072 |
from typing import Dict
from typing import Any
from typing import Union
from typing import List
def pt_whois_search_command(client_obj: Client, args: Dict[str, Any]) -> Union[List[CommandResults], str]:
"""
Gets WHOIS information records based on field matching queries
:param client_obj: client object wh... | 9d825ca96832b61dceb81b5a2f9de977a6d83b41 | 73,073 |
def __getcoordinatearrays__(rotate=True, representation='Cylindrical',
**kwargs):
""" This function will create a 2D/3D array from the requested shape in
kwargs['shape']. It can either return this array into cartesian,
polar/cylindrical or spherical coordinates. Using the option... | cf61d32caade1f453480b6fe38ac862452bd08ec | 73,074 |
def cct(pvals, weights=None):
"""
Python port of the CCT function as defined in the STAAR R-package (https://github.com/xihaoli/STAAR/blob/2f67fafec591a45e81a54eca24564b09ce90e252/R/CCT.R)
An analytical p-value combination method using the Cauchy distribution.
takes in a numeric vector of p-values, a ... | 31d898744048b5c5b89b9b69f0d93d41233a8816 | 73,075 |
def score_tup(t):
"""
Score an ngram tuple returned from a database ngram table. A higher scoring
term is more deserving of inclusion in the resulting acrostic
:param t: (Term string, initials string, Corpus count, Used count)
:return: Fitness score for this term
"""
term = t[0]
inits = ... | eea34dbf2d6a7dec37dc95cde289560a77c72f7e | 73,076 |
import pathlib
def fits_file():
"""
Return the path of an example FITS file.
The FITS file whose path is returned shows a 10 arcsecond by 10 arcsecond sky area
centered on the right ascension 10 degrees and the declination -60 degrees.
Returns
-------
`pathlib.Path`
The path to t... | 095d582e5a8b6127cf273c610219ba984fdbb48a | 73,078 |
import torch
def get_optimizer(parameters, lr, weight_decay):
"""
Initiate Adam optimizer with fixed parameters
Args:
parameters: filter, parameters to optimize
lr: float, initial learning rate
weight_decay: float, between 0.0 and 1.0
Return:
a torch.optim.Adam optimizer
"""
return torch.optim.Adam(p... | 54b4c6a4cd02672ebfc8ff9c850f0d601fc6510f | 73,079 |
def reissue_notification(alert, definition, notification):
""" Create another (re-issue notification) as a part of esclation process (for alerts only)
"""
result = None
try:
ticket_id = 0
# If red mine enabled:
if notification.use_redmine:
ticket_id = reissue_notific... | b08dde81906cf2816cf40970762e27787544a5f3 | 73,080 |
import warnings
def check_weather_data(weather_df):
"""
Check weather Data Frame.
- Raise warning if there are nan values.
- Convert columns if heights are string and not numeric.
"""
# Convert data heights to integer. In some case they are strings.
weather_df.columns = pd.MultiIndex.fro... | 58c63897b9820ea5af2166c7eba4ae9837a3db13 | 73,081 |
def DoesMoleculeContainsPAINSPattern(Mol, PAINSPatternMols):
"""Check presence of PAINS pattern in the molecule"""
MolMatched = False
for PatternMol in PAINSPatternMols:
if Mol.HasSubstructMatch(PatternMol, useChirality = True):
MolMatched = True
break
retu... | 15b8684b69c02508f24b075db654efcb4c903188 | 73,082 |
from re import T
def rmsprop(cost, params, lr=0.001, alpha=0.2, beta=0.2, epsilon=1e-6, decay_rate=0.0, data_part=0.0):
"""RMSprop and AdaGrad"""
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
acc = shared(p.get_value() * 0.)
acc_new = acc - beta * ... | d1932641b34937b4644935f414ef141e389807d2 | 73,084 |
def read_forces_2d(op2, se):
"""Read forces for a 1D structural element
Parameters
----------
op2 : PyNastran's OP2 results
OP2 result class from PyNastran.
se : :class:`.SE` object
The structural element for which the forces should be read.
"""
se_forces = {}
for vec... | f4bfdbc497ea2ec7f9a5bee155ee0d943b4e0778 | 73,085 |
def _retentionsFromCSV(csv):
"""Parse the command separated ints in `csv` into a list of tuples
Used to deserialise the retention policy.
"""
ints = map(int, csv.split(','))
return zip(ints[::2], ints[1::2]) | 85047d64a152ab9b65116e0b9539e4f5950fc0b0 | 73,086 |
def dropbox_factory(request):
""" expects the id of an existing dropbox and returns its instance"""
try:
return request.registry.settings['dropbox_container'].get_dropbox(request.matchdict['drop_id'])
except KeyError:
raise HTTPNotFound('no such dropbox') | 236b759e47cf98c387e66e31614d1c97ed8e3b60 | 73,088 |
def _get_affine_inv_wmae(prediction,
depth,
depth_conf,
irls_iters=5,
epsilon=1e-3):
"""Gets affine invariant weighted mean average error."""
# This function returns L1 error, but does IRLS on epsilon-invariant L1 er... | 46871b38bca4a45866b4c274040f04c5604093b8 | 73,089 |
def add(arr):
""" Exercise 4.1 """
"""
Answer in book
def sum(list):
if list == []:
return 0
return list[0] + sum(list[1:])
"""
if arr is None: # base case
return 0
if len(arr) == 1: # base case
return arr[0]
return arr[0] + add(removeFirst... | b880e4a997f370138b26566e85d78ec62b259a41 | 73,090 |
import logging
def update_status_in_database(workspace_repo: WorkspaceRepository, message: DeploymentStatusUpdateMessage):
"""Updates the deployment sub document with message content
Args:
workspace_repo ([WorkspaceRepository]): Handle to the workspace repository
message ([DeploymentStatusUpd... | 9670d581086ff5bdf20a787ef874dbc96609ea6b | 73,091 |
import timeit
def list_dequeue(N, num):
"""Run a single trial of num dequeue requests. Make sure that num < N."""
return 1000*min(timeit.repeat(stmt='''
for i in range({}):
q.pop(0)'''.format(num),
setup = 'q = list(range({}))'.format(N), repeat=5, number=1)) | b6b4c5dbdb153b6aff13357cc707243d8e2c5175 | 73,092 |
import copy
import torch
def mutate(net, seed, noise_std, copy_net=True):
"""
Mutates the given network parameters. Based on the applied seed a normal distributed noise is added to the network parameters
"""
# copy current net
mutated_net = copy.deepcopy(net) if copy_net else net
# set see... | e67ad3778be8a27734cee3056fc0ff1a2c956669 | 73,093 |
def encrypt_decrypt():
"""Decide whether to encrypt or decrypt."""
while True:
choice = input("Enter E for encryption or D for decryption:")
if choice == "E":
return "E"
elif choice == "D":
return "D"
else:
print("Wrong input! Please try again.... | 1361e86939cf333680ba9c640487bf246a8faf2d | 73,094 |
import numpy
def MAtoSeries(Series):
"""
Convert a masked array to a numpy ndarray with masked elements set to c.missing_value.
Useage:
Series, WasMA = MAtoSeries(Series)
where:
Series (input) is the data series to be converted.
WasMA (returned) is a logical, True if the input se... | 17cae7eea68fdec5f9b8ec5d295c2106cbd36ac0 | 73,095 |
def get_P_Elc_toilet_seat_heater(theta_ave_d, P_Elc_toilet_seat_heater_rtd):
"""暖房時の消費電力を計算する
Parameters
----------
theta_ave_d : float
日付dにおける平均外気温度(地域、季節によらず 11.23), ℃
P_Elc_toilet_seat_heater_rtd : float
便座暖房時の定格消費電力, W
Returns
----------
P_Elc_toilet_se... | 48ca59bbf2ca88e4e93febb4c83c80564050757b | 73,098 |
def shepp_logan(shape):
"""
Creates the Shepp Logan Phantom.
Args:
shape: Shape (in [Y, X]) of Shepp Logan phantom to create.
Returns:
Shepp Logan of shape as np.array
"""
# Definition of Shepp Logan Phantom
# Ellipse Center Major Axis Minor Axis Phi ... | d92789ca5b8ceef6c4b8929b4a9ddb56168f6120 | 73,099 |
def generate_author_degree_tuples(
report: tp.Union[BlameReport, BlameReportDiff],
commit_lookup: CommitLookupTy
) -> tp.List[tp.Tuple[int, int]]:
"""
Generates a list of tuples (author_degree, amount) where author_degree is
the number of unique authors for all blame interaction, e.g., the number of... | 7865ccb3115731d6c3987b769af3ac99dab5ff02 | 73,100 |
import email
def noheaders():
"""Return an empty email Message object."""
global _noheaders
if _noheaders is None:
_noheaders = email.message_from_string("")
return _noheaders | 27a3aeb78263bc86c70fe3306fca359a7a3d0bd2 | 73,101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.