content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _mad(x, axis=None):
"""Calculate median absolute deviations from the median (MAD) for an array.
Parameters
----------
x : np.ndarray
A 1-D or 2-D numeric array to summarize.
axis : {int, tuple of int, None}, optional
Axis along which MADs should be calculated. If ``None``, the M... | c712a17d1fbec07f1622e25a54cbb62bcd54cd60 | 63,182 |
def ode_plotter(name, t, ny, svars, log = False, labels = None,
xlim = None, ylim = None, plim = None, labels_strict = False):
""" Plots the ODE trajectories.
Args:
name (str): Name of the outputfile including extension (e.g. *.pdf)
t (list[flt]) : time units plotted on the x-axis.
ny... | a049b03f36e64e66a6d954e6b9c4d4b377f5c85a | 63,183 |
def Proxy(f):
"""A helper to create a proxy method in a class."""
def Wrapped(self, *args):
return getattr(self, f)(*args)
return Wrapped | 48ce69670db02691bf20b7d277af5086c76d012d | 63,184 |
def french_to_english(french_text):
"""french to English translation"""
translation= language_translator.translate(text=french_text, model_id="fr-en").get_result()
english_text=translation['translations'][0]['translation']
return english_text | 75420074fe15360c789d76a887dc6574a37fdf95 | 63,185 |
import pandas
from typing import Union
from typing import List
def calculate_metric_scores(
r: pandas.Series, metrics_to_calculate: Union[str, list] = "all",
) -> List[Result]:
"""Calculates the metric score(s) between two images and returns a list of the results.
Args:
r (pandas.Series): Row con... | 6c7a306e2c7eee42bbd2f8fcc9e5a99ddb9d7b89 | 63,186 |
def parse_results(results):
"""Break up multiline output from ls into a list of (name, size) tuples."""
return [(line.split()[8], int(line.split()[4])) for line in results.splitlines() if line.strip()]
#return [(line.split()[1], int(line.split()[0])) for line in results.splitlines() if line.strip()] | dd4eea6fc57133225e74df1d61af69b44329b636 | 63,187 |
def use_for_variety(variety, *, read=True, write=True):
"""
A class wrapper to associate a specific variety with the class.
Defaults to registering for both read and write widgets.
Parameters
----------
variety : str
The variety (e.g., 'command')
read : bool, optional
Use ... | 568e440b62336f8e88b594c6e94ae94f0897b2c9 | 63,188 |
import requests
def getListings():
"""
:param ticker: str
Returns:
"""
return requests.get(URL_LISTINGS, headers=headers).text | fd16f0ca34fdc0bf34b141c5d6c2a0bfc7bb8589 | 63,189 |
def STALTA_picker(st, nphase=2, nsta=1e-3, nlta=4e-2, fc=50, nc=2,
noise_mag=1e-25, SNR_window=5e-3):
"""The STA/LTA picker provides a first order good estimate of the arrival
times for both the P- and S- wave. The STA/LTA picker uses
:py:class:`obspy.signal.trigger.recursive_sta_lta `.
:param st: ... | 17b1e0a0c69aa9c6c9daac003747782cd8c10ff6 | 63,190 |
def underscore_to_camel(match):
"""
Cast sample_data to sampleData.
"""
group = match.group()
if len(group) == 3:
return group[0] + group[2].upper()
else:
return group[1].upper() | 4a4dafd233f420ba2066d53260e0cd8c508b2bc9 | 63,191 |
def select_tapered_estimator(debiased, direct):
"""Select the tapered estimator of the structure factor.
Args:
debiased (bool): Trigger the use of a debiased tapered estimator.
direct (bool): If ``debiased`` is True, trigger the use of the direct/undirect debiased tapered estimator.
Return... | b092e17597ba471acc7cbe318727b24ee72a25e7 | 63,192 |
import torch
def test_ae(model, dataloader, gpu, criterion):
"""
Computes the loss of the model, either the loss of the layer-wise AE or all the AEs in a big graph one time.
:param model: the network (subclass of nn.Module)
:param dataloader: a DataLoader wrapping a dataset
:param gpu: (bool) if ... | ffc55268dac0e884e7ef9594d270fb59d9fc19ec | 63,193 |
def moments(input_t, axes=None, keepdims=False):
"""
Returns (mean, variance) of input_t
input_t Tensor
axes(None) int
Iterable of ints.
None - all axes
keepdims(False) keep reduced axes
"""
mean = reduce_mean(input_t, a... | 1f30a3cb85fa21b2a7abf9e2d92cb89d1141b615 | 63,194 |
def sin():
"""
Returns class instance of `Sin`.
For more details, please have a look at the implementations inside `Sin`.
Returns
-------
Sin :
Class instance implementing all 'sin' processes.
"""
return Sin() | 9d90b5e40ae285d79bbf25498730a4728c2ed437 | 63,196 |
def parse_format(frm):
"""
Determine a struct format from a CPHD format string.
Parameters
----------
frm : str
Returns
-------
Tuple[str, ...]
"""
return tuple(_map_part(el) for el in frm.strip().split(';') if len(el.strip()) > 0) | 90503a2d6eedb9324f4668106a0f9477cb6c8f43 | 63,197 |
import boto
def needs_aws(test_item):
"""
Use as a decorator before test classes or methods to only run them if AWS usable.
"""
test_item = _mark_test('aws', test_item)
try:
# noinspection PyUnresolvedReferences
except ImportError:
return unittest.skip("Skipping test. "
... | 664b21ee8ac88640a6ebfcce75c4697e7b828f51 | 63,198 |
def dropout_layer(input_layer, nodropout_probability):
"""Dropout layer"""
output = tf.nn.dropout(input_layer, nodropout_probability)
return output | 8cb5d8d8e2719f5504bcc4634e396306f7fadb7c | 63,200 |
def isSceneDescription(logtrack_type):
"""Checks if the logtrack type indicates it is a Scene Description"""
return logtrack_type == LogTrackType.SCENE_DESC.value or logtrack_type == LogTrackType.SCENE_DESC2.value or \
logtrack_type == LogTrackType.SCENE_DESC3.value or logtrack_type == LogTrackType.S... | d4c8d1e770a8688de4021a846d3243f8022d0918 | 63,202 |
def compile_model(context, source, dtype, fast=False):
# type: (cl.Context, str, np.dtype, bool) -> cl.Program
"""
Build a model to run on the gpu.
Returns the compiled program and its type.
Raises an error if the desired precision is not available.
"""
dtype = np.dtype(dtype)
if not a... | 45be8409d14ca6c2911d9f7f566df9f6b4309e31 | 63,203 |
def common_text(stringlist, kind='prefix'):
"""
For a list of strings find common prefix or suffix, returns None
if no common substring of kind is not 'prefix' or 'suffix'
:param stringlist: a list of strings to test
:param kind: string, either 'prefix' or 'suffix'
:return:
"""
substri... | 9a85120006abb5483f3a0afd4f8df63f547eb817 | 63,204 |
def _get_literal_string_prefix_len(token_string: str) -> int:
"""
Getting the length of the literal string prefix.
Parameters
----------
token_string : str
String to check.
Returns
-------
int
Length of the literal string prefix.
Examples
--------
>>> examp... | 7138aeb77d83f26c1cc0bdb5b1333c6c27c7b72b | 63,205 |
def format_view_link(body: Json) -> Json:
"""Format view link data.
:param body: Input body.
:type body: dict
:return: Formatted body.
:rtype: dict
"""
result: Json = {}
if "analyzers" in body:
result["analyzers"] = body["analyzers"]
if "fields" in body:
result["fiel... | ad10ec025a0b69786a4ea5366ac4c3aa6f771b2c | 63,206 |
def local_head(venue, results):
"""Plot the magnitude of the local head.
Plot the grid showing the relative magnitude of the estimated local head
as color-coded markers.
"""
xtarget = np.array([row[0][0] for row in results])
ytarget = np.array([row[0][1] for row in results])
bdry = venue.... | d9564e6feea97bf35c514ed7c3bcbe869353ea14 | 63,207 |
from ..models.models import TrialMetadata
from typing import Optional
from typing import List
def _build_trial_upload_prefixes(
trial_id: Optional[str], upload_type: Optional[str]
) -> List[str]:
"""
Build the set of prefixes associated with the trial_id and upload_type
If no trial_id is given, all tr... | 768fffabf464f319ee7c6fafcc533f682ef4ff87 | 63,208 |
def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if type(h) != tuple and type(h) != list:
return Variable(h.data)
else:
return tuple(repackage_hidden(v) for v in h) | c1129b966d622c475ba74227c4e0cb9eec451bbe | 63,209 |
import warnings
def _maskClouds(
self,
method,
prob,
maskCirrus,
maskShadows,
scaledImage,
dark,
cloudDist,
buffer,
cdi,
):
"""Masks clouds and shadows in an image or image collection (valid just for Surface Reflectance products).
Parameters
----------
self : e... | d7f7e5040c98f04fbee99597c734bfede732ec29 | 63,212 |
def next_delay(t):
"""Next possible pump-probe delay to the given value"""
if "linear stage" in translate.mode: t = Ensemble_SAXS.next_delay(t)
return t | 806a222b02b3d0bb225a92a708d3d95c5a144a95 | 63,213 |
def get_hyperplane(point_one, point_two):
"""Generate a hyperplane between two points.
This is achieved by finding a line that goes through the
median segment between both points, that is also orthogonal
to the median segment.
A hyperplane in 2-dimensional space is of the form:
x1 = m*x2 + b
... | 3a821e6da56b713abd6debfc87d189914cd7044d | 63,214 |
from typing import List
def find_markdown(text: str, text_start: int = 0, text_end=-1, real_start: int = 0) -> (str, List[MessageEntity]):
"""
find nearest markdown block
:param real_start: offset in plain text
:param text_start: start pos in markdown text
:param text_end: end pos in markdown text... | 924d4a2076aece85b2052cb675a166f091afd7a4 | 63,216 |
def build_right_circular_cylinder_surface(radius, height, position, surface_num, comment):
"""Create a right circular cylinder in the z direction."""
surface_card = "{} RCC {} {} {} 0 0 {} {} {}".format(surface_num, position[0], position[1], round(position[2], 5),
... | 4e162b59f4197e0adb2236e9c1f86e04c7e7e20a | 63,217 |
def order_nodes_from_leaves(G):
"""
Returns the node of G ordered from the LEAVES to the ROOTS
"""
return __order_nodes(G, False) | 4eb9b7a8b2aa862433a7af098c3df6e3dcca06ae | 63,218 |
def recursive_integration2(f, x0, x1, S, xList, tol=1e-5, recursiveLim=1e4):
"""
f: function of f(x)
[a,b] : the interval of integration
S : the previous integration result
tol : the tolerance
This is a subfunction of adapt_simpson.
"""
Sn, xListNew = myMidpointList_Integration2(f,... | 652cd101af348f33b78a80bdf33abbf7c6820e45 | 63,219 |
import cmath
import math
import itertools
def _recognize_v(matrix):
"""
Recognizes a matrix which can be written in the following form:
V = [[-sin(c/2) * exp(j*a), exp(j*(a-b)) * cos(c/2)],
[exp(j*(a+b)) * cos(c/2), exp(j*a) * sin(c/2)]]
Args:
matrix(list): 2x2 matrix
Returns:
... | 085540fd6a81d59eae2cf12d83a7f4d4cbf93912 | 63,220 |
def vertices_text(text, angel_code):
"""Generate vertex data for a text object"""
ac = angel_code
o_c = ac["char"][str(ord('O'))]
builtin = ac["info"]["face"] == "Bfont"
scale = 0.0225 * (1.4 if builtin else 1)
unit_height = o_c["height"] * scale
verts = []
pos = 0
z = 0
for c... | 46cb6e7c937f43e80d62f5f76c246aa694bd7bcf | 63,221 |
def list_strip_prefix(l, prefix):
"""Remove prefix, if it's there."""
return l[len(prefix):] if list_startswith(l, prefix) else l | f8f337b16bd96b45d36ef47be72a5d68fcff5ecd | 63,222 |
def bullets_of(id):
"""
Counts the number of bullets of id.
"""
return lookup.bullets.get(id, 0) | a6f53531558a7ff8319bdd0589b584160be09050 | 63,223 |
def is_subcmd(opts, args):
"""if sys.argv[1:] does not match any getopt options,
we simply assume it is a sub command to execute onecmd()"""
if not opts and args:
return True
return False | 2158b83c5f1e78760d8d2947d5ab879a1dee020a | 63,224 |
def sample (x, y, c=0, e=0):
""" Performs logarithmic sampling on the given data.
Args:
x (list of float): The x-values.
y (list of float): The y-values.
c (int): The current offset in the data.
e (int): The current exponent.
Returns:
pair: The sampled x and y values,... | fbd5c9008aa2dec14b8fee5b848ad32ad774ed60 | 63,225 |
def set_batch_projection_args( \
args, fields=None, dataset_fields=None):
"""Return batch projection args dict
"""
batch_projection_args = set_basic_batch_args(args, args.name)
if args.fields_map_ and fields is not None:
if dataset_fields is None:
dataset_fields = fields
... | ed5bfd31c34fe4b3b990f09013167ac2f0d28e03 | 63,226 |
def FailPercent(threshold):
"""Tasks with FailPercent(r) will fail the DF if the task is triggered >= r percent of the
total number of records in the DF
Args:
threshold (double): the threshold after which the DF fails. value is between 0.0 and 1.0
Returns:
(DQMTaskP... | 01fa71804eeeea60d77b972dc8e7fd8fef09c90f | 63,227 |
def gauss_1(t, n, freq, pulse_delay):
"""
:param t: time sequence (s).
:type t: list of floats
:param n: time iteration index
:type n: int
:param freq: frequency of the sinusoid (Hz)
:type freq: float
:param pulse_delay: number of iteration for the delay of the signal defined
in the... | e1a138ab505ffd34c3d3cb2f10c9fcf3fd15dedd | 63,229 |
def wheel_to_variants(wheel):
"""Parse WHEEL file of `distribution` as per PEP427
https://www.python.org/dev/peps/pep-0427/#file-contents
Arguments:
wheel (str): Contents of a WHEEL file
Returns:
variants (dict): With keys {"platform", "os", "python"}
"""
variants = {
... | 6f1955a1201bf20cb38c11ac26f511dd424b83ef | 63,230 |
def dmsp_system_3_comp_mm(
c,
t,
f_total_in,
alpha_d,
alpha_c1,
alpha_cp,
kappa_32_d,
kappa_32_c1,
kappa_32_cp,
vmax_34_d,
vmax_34_c1,
vmax_34_cp,
vmax_32_d,
vmax_32_c1,
vmax_32_cp,
transcripts_d,
transcripts_c1,
transcripts_cp
):
"""
Fu... | 62bea6759c1b8c25216c9ccd9d37461792a75fb6 | 63,231 |
from openforcefield.topology import Molecule, Topology
from openforcefield.typing.engines.smirnoff import ForceField
import parmed
def generateSMIRNOFFStructure(oemol):
"""
Given an OpenEye molecule (oechem.OEMol), create an OpenMM System and use to
generate a ParmEd structure using the SMIRNOFF forcefiel... | c6e12b945b9ada3774e6e10c6b18f173bb14ca7d | 63,232 |
def build_input(tfrecord_paths):
"""Builds the graph's input.
Args:
tfrecord_paths: List of paths to the input TFRecords
Returns:
serialized_example_tensor: The next serialized example. String scalar Tensor
image_tensor: The decoded image of the example. Uint8 tensor,
shape=[1, None, None,3]... | 3b80671c0f8afabbd93b9028de0bdc999874a9de | 63,233 |
def mean_affine(mats, shapes):
"""Compute a mean orientation matrix.
Parameters
----------
mats : (N, dim+1, dim+1) array_like or list[(dim+1, dim+1) array_like]
Input orientation matrices
shapes : (N, dim) array_like or list[(dim,) array like]
Input shape
Returns
-------
... | 65de970e3ae9844bf6400f1daa0ce9d3e1cc7611 | 63,234 |
def get() -> FFCClient:
"""Returns the singleton Python SDK client instance, using the current configuration.
To use the SDK as a singleton, first make sure you have called :func:`ffcclient.set_config()`
at startup time. Then :func:`ffcclient.get()` will return the same shared :class:`ffcclient.client.FFCC... | d4d721a90712033c708eb90787646294765c2d9d | 63,235 |
def prepare_deploy(id='HEAD'):
"""
Execute all steps which can in advance of actually switching the site live
This is done to speed up activating deployments
"""
packaged_code, release_dir = _package_code(id)
execute(deploy_package, packaged_code, release_dir)
execute(install_requirements, r... | 7045830083066901bafa7dfa266df34aa29e9bd8 | 63,236 |
def ShapeAnalysis_FreeBounds_SplitWires(*args):
"""
* Extracts closed sub-wires out of <wires> and adds them to <closed>, open wires remained after extraction are put into <open>. If <shared> is True extraction is performed only when edges share the same vertex. If <shared> is False connection is performed only w... | 54cc1a07b4745f1dd86737a69d8995ad5f027d00 | 63,237 |
def iterate(func, r, iter_num):
""" function to generate the cobweb coordinates """
x = np.random.uniform(0, 1)
xs = [x]
ys = [x]
for i in range(iter_num):
xs.append(x)
y = func(x, r)
ys.append(y)
x = y
xs.append(x)
ys.append(x)
return xs, ys | 6202ba7b4edd1e40b8d798d86849bdfdda80d1c7 | 63,238 |
def start_menu():
"""
Displays menu at execution start.
Returns
-------
name: str
if provided custom environment name, else "test-env"
channel_lst: lst
if provided, contains additional conda-channels to install from
"""
print("Hello :)")
#What kind of checks to add here?
name = input("Please provide a na... | 4b651ad38e1a163fa0ed75e2b34386149ccba1f0 | 63,241 |
def min_energy_conformer_locators(cnf_save_fs, mod_thy_info):
""" Obtain the (ring-id, tors-id) filesystem locator pair and
path for the conformer of a species with the lowest energy
for the specified electronic structure method that currently
exists in the save filesystem.
:param c... | 245fc99bfc541ddc89f7cc2f2e2532fd8e21a61e | 63,242 |
def create_user(email='test@user.com', password='123'):
"""Shortcut for quick user creation"""
return get_user_model().objects.create_user(
email=email,
password=password,
first_name='Jhon',
last_name='Doe'
) | ad4033a455360db5a43bf47df3aad0f6da85172c | 63,243 |
def _shorten_fname(fname: str) -> str:
"""Reduce extraneous stuff from filenames"""
fname = fname.replace(_SP, '.../site-packages')
fname = fname.replace(_STD_LIB, '.../python')
return fname.replace(ROOT_DIR, "napari") | 72d89cca30557355779bc31dc4712329cfa194fb | 63,244 |
def anc_names(anc_id):
"""
Return formatted ANC names
"""
ancs = pd.read_csv('data/ancs.csv')
anc_upper = 'ANC' + anc_id
anc_lower = anc_upper.lower()
anc_neighborhoods = ancs[ancs['anc_id'] == anc_id]['neighborhoods'].values[0]
return anc_upper, anc_lower, anc_neighborhoods | b6cfc0bafc0a7a5e333205212735e8506fc0d21b | 63,245 |
def get_psis_from_rhos(rhos, mst):
"""
This method is specific to MSTfit reconstructions. Note that for now I have found this method to work poorly.
It seems to make the geometry more symmetric, rendering the result non-invertible.
"""
psis = np.zeros(rhos.shape)
for i, rho in enumerate(rho... | e291bcf76d9d26768bfab47d68daa171f23dd469 | 63,246 |
def probably_bool(arr):
""" dumb test for bool arrays that ahve nans """
s = pd.Series(arr)
counts = s.value_counts()
keys = list(counts.keys())
for key in keys:
if not isinstance(key, bool) and not isinstance(key, np.bool_):
return False
return True | 4a9b44f9301dcd8618d69d469d7aed677005dfd9 | 63,247 |
def img_dict_rgb2gray(img_dict, show=False):
"""
Extract a channel from the rgb image, so that a width*height*1 matrix is achieved.
:param img_dict: a dictionary with 4 key/value pairs: "features", "labels", "sizes", "coords"
:param channel: available channels: "GRAY"
:return: a dictionary with 4 ke... | ed830e62b8dbd2dc4c6eb572126a3f15bb8201d5 | 63,248 |
from typing import List
def exif_gps_date_fields() -> List[List[str]]:
"""
Date fields in EXIF GPS
"""
return [["GPS GPSDate", "EXIF GPS GPSDate"]] | e1911a4c7e79a5817fef0ddfc1a0ff7ad7083c59 | 63,250 |
def _calc_power_spectrum(phase):
"""
Helper function to assist with memory re-allocation during FFT calculation
"""
fft_phase = fft2(phase)
pspec = real(fft_phase) ** 2 + imag(fft_phase) ** 2
return pspec.astype(dtype=np.float32) | ee14a269c85619a959975cab32d3f796dc3bafa1 | 63,251 |
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, Flatten, Dense, MaxPool2D, BatchNormalization, ReLU
import typing
from datetime import datetime
def prepare_model(
stations: typing.Dict[typing.AnyStr, typing.Tuple[float, float, float]],
target_time_offsets: typing.List[da... | 51efdc766c4ba143e2a6aab32dcffeb73ae1cbdb | 63,252 |
def split_segmentation_by_intersection(a, b, min_size):
"""Computes the intersection of two segmentations.
Intersects two spatially overlapping segmentations and assigns a new ID to
every unique (id1, id2) pair of overlapping voxels. If 'id2' is the largest
object overlapping 'id1', their intersection retains ... | 1c524493bb5c0d6a7fad06ae8332a77cbf631506 | 63,253 |
from typing import Union
from typing import List
def fill_prediction_str(
y: float,
Y: Union[np.ndarray, None] = None,
classes: Union[List[str], str, None] = None,
decimals: int = 3,
) -> str:
"""Create a string describing the prediction
Args:
y (float): the prediction
Y (Unio... | 9b830b7764943a2a35844bc847d1bfbed1dfa69a | 63,255 |
def check_dtable_permission(username, workspace, dtable=None):
"""Check workspace/dtable access permission of a user.
"""
owner = workspace.owner
if dtable:
dtable_share = DTableShare.objects.get_by_dtable_and_to_user(dtable, username)
if dtable_share:
return dtable_share.pe... | e31fec9e61b2da4e4aff1a3c7247dc4ae1c87bdd | 63,256 |
def get_calculated_attributes(df, axes=None, history=None):
""" Functions to automate netCDF attribute generation from the data itself
This is a wrapper for the other four functions, which could be called separately.
:param df: data (Pandas DataFrame)
:param axes: keys (x,y,z,t) are associated with act... | eacee7f886998dfe04ce74908c406dda1d6adf03 | 63,257 |
def cron_method(handler):
"""
Decorator to indicate that this is a cron method and applies request.headers check
"""
def check_if_cron(self, *args, **kwargs):
"""
Check if it is executed by Cron in Staging or Production
Allow run in localhost calling the url
"""
... | 60f2ccb1be9b605d65324bc01984a5515098b11c | 63,258 |
def fetch_urls_from_list_of_pages(urls: list, results_number: int):
"""Extract results_number urls from given pages.
:param urls: given pages to extract urls
:param results_number: number or urls to extract
:return: list of urls
"""
all_urls = []
for url in urls:
all_urls += fetch_... | 0f87d5cce20e7e72310246a5944fa8c9d3a1cf8c | 63,259 |
def nti(note):
""" Note to index
returns the index of enharmonic note names
or False if not found
"""
return notes.get(note, False) | f9ad7e562b1ac1137f5a72424f116650921a0f38 | 63,261 |
def can_edit_project_fn(user, proj, file):
"""
Check if a user can edit a proposal. Used to show/hide editbuttons on detailproposal and
for the can_edit_project decorator.
:param user: user
:param proj: proposal
:param file: whether editing a file. This is not allowed in limited edit mode (stat... | 33b29e5d569224a25e711f627f7d61922cf7ddcc | 63,262 |
from pathlib import Path
from bs4 import BeautifulSoup
def get_exc_page_contents(html_string, current_dir_path, dig_parent_dir_path, readfile):
"""Extract the html contents linked to from within a exc_**.html file."""
full_current_dir_path = Path(dig_parent_dir_path) / ("." + current_dir_path)
frames = B... | 44b41cb571171508458023e1a3ea058e3658713f | 63,263 |
def divide_by(array_list, num_workers):
"""Divide a list of parameters by an integer num_workers.
:param array_list:
:param num_workers:
:return:
"""
for i, x in enumerate(array_list):
array_list[i] /= num_workers
return array_list | d7f1566b017fe859a2188d0efa511822f7e56b6a | 63,264 |
def lemmatizing(text):
"""
input: string
Lemmatize input using nltk WordNetLemmatizer (eg wolves -> wolf)
output: string
"""
return ' '.join([wnl.lemmatize(word) for word in text.split(' ')]) | efd9064162d4ae0ad88384b375c98449f0fc132e | 63,265 |
def _find_match(ele, lst):
"""
Find a matching element in a list.
"""
for _ele in lst:
for match_key in _MATCH_KEYS:
if _ele.get(match_key) == ele.get(match_key):
return ele | 3818051c982a395e917b183793f39a3ed169e3ce | 63,266 |
def get_grams(text, from_=1, to_=3):
"""
Takes text as an input and returns N-grams, which are consecutive strings
of N words.
:param text: Text to convert to n-grams.
:param from_: The size of the smallest n-gram.
:param to_: The size of the biggest n-gram.
:return: Generator that returns ... | a6a99b9c8d3c2b13c956a446c00bef50914097cd | 63,267 |
def make_root_node(state):
""" Construct the initial root node without parent nor action """
return SearchNode(state, None, None) | 8732e5fe944ba189a5466a46c7a7f887cab00890 | 63,268 |
def net_dashboard(request):
"""
Network vulnerability Dashboard.
:param request:
:return:
"""
all_openvas_data = scan_save_db.objects.all()
all_nessus_data = nessus_scan_db.objects.all()
all_network_data = chain(all_openvas_data,
all_nessus_data
... | 1d68d296c53e0ba40e7733f99e8a20cbfdebcff5 | 63,271 |
import copy
def merge_dicts(dict1, dict2, make_copy=True):
""" Recursively merges dict2 with dict1. Otherwise if both dict1 and dict2
have a key, it is overwritten by the value in dict2. """
if make_copy:
dict1 = copy.copy(dict1)
for key, value in dict2.iteritems():
if isinstance(dict1.get(key), dict)... | 4da004649b0abacb5213d5a13ea44e2300c88bd3 | 63,272 |
def confirm(prompt):
"""Displays the prompt, only returns true with input 'Y' or 'y'."""
confirmation = input(COLORS["yellow"] + prompt + COLORS["endc"]).lower()
return confirmation == "y" | c06000f125a692433b0587ea2b1db02ce7eb820c | 63,274 |
def comments():
"""
Full-page comments view.
"""
return make_response(render_template('comments.html', **make_context())) | 5a1dfa1bf67b8eac894f6018f1c3b33861f8ca02 | 63,276 |
def netcdf_to_pandas(file_path: str, last_x_years: int = 30) -> pd.DataFrame:
"""
Parses either the air or precip weather dataset from the University of
Delaware and outputs the not null data in a long format pandas dataframe.
Data per month is averaged over the `last_x_years`.
Parameters
-----... | 99378a0205230042faeabc76c2f61d5e7758897e | 63,277 |
def get_const_diff_ints(ints, length):
"""f(n) = an + b"""
first = ints[0]
diff = ints[1] - ints[0]
return [first + diff * n for n in range(length)] | 2b85b8fe28902239782fa85acfe7472860e639cf | 63,278 |
def remove_invalid_req_args(credentials_dict, invalid_args):
"""
This function iterates through the invalid_args list and removes the
elements in that list from credentials_dict and adds those to a new
dictionary
Returns:
credentials_dict: Input dictionary after popping the elements in
... | 0dfeaeb9c904489cf9b1deab8f3d179e7891e5c4 | 63,279 |
def pre_process(image, h_w_c_size, if_random_crop=True, if_flip=False, if_bright=False,
if_contrast=False, if_whiten=False):
"""
Do preprocessing for image data.
Atgs:
image: tensor with shape [height,width,channal].
h_w_size: integer python list.
if_random_crop: boo... | f40bc0b035044704bb2ac5aeb86c7b79eba59f9a | 63,280 |
def schulze(winning_votes: dict[tuple[str, str], int]) -> SchulzeResult:
"""Use Schulze method to find winners and strength of strongest path"""
candidates = set(chain.from_iterable(winning_votes))
strengths = {}
for a, b in permutations(candidates, 2):
if winning_votes[a, b] > winning_votes[b... | 6851df031b839c99db0a11d464605dcdbd95d175 | 63,281 |
def box_config_put(node_addon, user_addon, auth, **kwargs):
"""View for changing a node's linked box folder."""
folder = request.json.get('selected')
uid = folder['id']
path = folder['path']
node_addon.set_folder(uid, auth=auth)
return {
'result': {
'folder': {
... | a73f38bd3f87731d4041bfcfa269e3f8e2289cff | 63,282 |
def create_normal_buffer(vertices, triangles):
"""
Creates normal vectors for each vertex on the mesh.
Qt requires each vertex to have it's own normal.
:param vertices: The vertices for the mesh
:param triangles: A list of the triangles that make up each face in the mesh
:return: A list of the n... | b064ec92eb0c53c546f98711fcdc8ed1a13ca432 | 63,283 |
def _get_base_query(export_instance):
"""
Return an ESQuery object for the given export instance.
Includes filters for domain, doc_type, and xmlns/case_type.
"""
if isinstance(export_instance, FormExportInstance):
return get_form_export_base_query(
export_instance.domain,
... | 4041156b4d8f181071a685f2c8d07e331a30a65f | 63,284 |
def NormalizeFilePath(file_path):
"""Normalizes the file path.
0. Strip leading "/" or "\".
1. Convert "\", "\\", and "//" to "/"
2. Resolve ".." and "." from the file path.
3. Extract relative file path from the root src of a chromium repo checkout.
eg.:
//BUILD.gn -> BUILD.gn
../a/b/c.cc -> a/b... | 5ec5f13891970de35f9debf6b9cc71f64b8c5443 | 63,285 |
def fill_var(current_var: list or str or int or float or dict, new_var: any) -> list or any:
"""
This is another of those functions that probably already exist or what i am trying to do is not wise. Anway
it either directly returns new_var if current_var is either an empty string or None. If not it creates ... | 1c37b02e75e4b4d1744908b0772f8412254e2620 | 63,286 |
import csv
def read_csv_as_dict(path, delimiter=','):
"""Accepts a path, creates a file object, and returns a list of
dictionaries that represent the row values.
Parameters:
path (str): path to file
delimiter (str): delimiter that overrides the default delimiter
Returns:
list... | b709e1725af2e79ffc3348baa1754f859d138e1b | 63,287 |
def product_detail_view(request, id):
"""Product detail view and newsletter as context"""
product = get_object_or_404(Product, id=id)
context = {
'newsletter_form': SubscriberForm(),
"product": product
}
return render(request, "product_detail.html", context) | 1ec58ef79b54a500a22b6ed52dc201da22217a3e | 63,288 |
def tf_frequency_weight(t_inst, weight_type = 'linear', factor = 1.0):
"""
Compute a per-instruction weighting based on inverse frequency
"""
freqs = np.array([0.456536, 0.456536, 0.001150, 0.026873, 0.012083, 0.000129, 0.012083, 0.000129, 0.012083, 0.000129, 0.012083, 0.000129, 0.002053, 0.002053, 0.00... | ece0c716e9eed10ebb2ad3f50861413571c8369d | 63,289 |
def fields_for_repeated_item(field_name, fields):
"""Unpack field specifications for repeated items.
Given the following message:
message Item {
string title = 1;
}
message Something {
repeated Item items = 1;
}
We support specifying sepcific field... | 88172204c4e45897a08ee6b05ee8cd9eef84e577 | 63,290 |
def bottleneck_lstm(inputs,state,filters):
"""
Bottleneck lstm from:
https://arxiv.org/pdf/1711.06368.pdf
:param inputs:
Input featuremap [B,H,W,C]
:param state:
Previous state [B,H,W,C]
:param filters:
number of output channels
:return:
tuple containing outp... | be24b418276d7d1f367f3f1d23e39ff24cf5e9bf | 63,291 |
def data_already_scaled(data):
"""
Test if data looks like it is already standardised
"""
return abs(np.mean(np.mean(data, axis=0))) < 0.1 | 60343b3afef5b24f996c27e0f89cd4bc0a1eaab8 | 63,292 |
def calcRmsDistancesVsRef(groupView, refVisit, magRange, band, verbose=False):
"""Calculate the RMS distance of a set of matched objects over visits.
Parameters
----------
groupView : lsst.afw.table.GroupView
GroupView object of matched observations from MultiMatch.
magRange : length-2 `astr... | 5389aceeff02b8cf4fdafebfd5a0dedb37c24a6e | 63,294 |
def _area_interpolate_binning(
source_df,
target_df,
extensive_variables=None,
intensive_variables=None,
table=None,
allocate_total=True,
spatial_index="auto",
):
"""
Area interpolation for extensive and intensive variables.
Parameters
----------
source_df : geopandas.Ge... | 7662962dd828263d44baee00ca81075d6e8857b2 | 63,295 |
import random
def update_masks(pop, infectivity, risk, m, u):
"""
Grants masks to m proportion of the unmasked susceptible and infected population
Take away masks from u proportion of the masked susceptible and infected population
"""
sus_m = get_indices(pop.flatten(), 'S', True)
inf_m = g... | 2c3e0234335b78eec5f08dd2d765a4895b7b97c1 | 63,297 |
def _get_panel_cls(value):
"""return the class best suited for displaying 'value'"""
if _pandas_available:
if isinstance(value, (pa.DataFrame, pa.Series)):
return DataFramePanel
if isinstance(value, dict):
return DictPanel
elif isinstance(value, (list, tuple, deque)):
... | c4552edcb4f76c1e04058db40f7d3cfd0400c2ad | 63,298 |
from datetime import datetime
import time
def get_ttl(ttl_days, start_date=datetime.datetime.today()):
"""Get ttl value epoch format to insert into DDB TTL field
Arguments:
ttl_days {int} -- Number of days to keep the record
Keyword Arguments:
start_date {datetime} -- Starting timestamp ... | 7af4baa1e9d02f230487131ae23808496acd0ff0 | 63,300 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.