content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def find_keyword(URL, title, keywords):
""" find keyword helper function of history_list """
for keyword in keywords:
# case insensitive
if len(keyword) > 0 and (URL is not None and keyword.lower() in URL.lower()) or (title is not None and keyword.lower() in title.lower()):
return T... | b956cc3744411a409a227cb80423dcf52ca9d248 | 33,756 |
def parsetypes(dtype):
"""
Parse the types from a structured numpy dtype object.
Return list of string representations of types from a structured numpy
dtype object, e.g. ['int', 'float', 'str'].
Used by :func:`tabular.io.saveSV` to write out type information in the
header.
**Parameters... | 6f373135f751b243104cc7222326d995048d7c93 | 33,757 |
import random
def random_flip(image):
"""50% chance to flip the image for some variation"""
if random.random() < 0.5:
image = cv2.flip(image, 1) # 1 = vertical flip
return image | 8e9898dd0a505f4db4a56e6cea8fa8631790e6c4 | 33,758 |
def sites_only(exclude_isoforms=False):
"""Return PhosphositePlus data as a flat list of proteins and sites.
Parameters
----------
exclude_isoforms : bool
Whether to exclude sites for protein isoforms. Default is False
(includes isoforms).
Returns
-------
list of tuples
... | b3c021e7e4332274c875b189b0f73f7ad3e43e0d | 33,759 |
def transform_url(url, qparams=None, **kwargs):
""" Modify url
:param url: url to transform (can be relative)
:param qparams: additional query params to add to end of url
:param kwargs: pieces of URL to modify - e.g. netloc=localhost:8000
:return: Modified URL
.. versionadded:: 3.2.0
"""
... | d19d5845e6ebe4d14579849ed937160dc71a0421 | 33,760 |
def coords_in_bbox(pose, bbox):
"""
Return coords normalized to interval's bbox as dict of np arrays. origin at box center, (.5, .5)
"""
x1, x2, y1, y2 = bbox
width = x2 - x1
height = y2 - y1
origin = np.array([x1, y1])
scale = np.array([width, height])
normalized_pose = {}
for j... | 96f98fe26bff8095311966fc640f887464c7cd4f | 33,761 |
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.... | 60bdc9b8500dc0004837a630c72c361204820328 | 33,762 |
def _find_xy(ll, T, M, maxiter, atol, rtol, low_path):
"""Computes all x, y for given number of revolutions."""
# For abs(ll) == 1 the derivative is not continuous
assert abs(ll) < 1
M_max = np.floor(T / pi)
T_00 = np.arccos(ll) + ll * np.sqrt(1 - ll ** 2) # T_xM
# Refine maximum number of re... | 09bfe02e08e7b9975f65a99cb1e706ba96ed71f9 | 33,764 |
def ligne_vivante(ligne, x_1, x_2):
""" Retourne un booléen indiquant si la ligne spécifiée contient au moins une cellule vivante """
for colonne in range(x_1, x_2 + 1):
if plateau[ligne][colonne] != CELLULE_MORTE:
return True
return False | db9be50c14458eb11ee853d15fe5997ea857d55a | 33,765 |
def changeMatchingReciprocity(G, i, j):
"""
change statistic for categorical matching reciprocity
"""
return G.catattr[i] == G.catattr[j] and G.isArc(j, i) | 30ece553661b71e8cb2674d88b0daa4905dd9039 | 33,766 |
def compare_letters(letter1, letter2, table=ambiguity_code_to_nt_set):
"""Compare two extended nucleotide letters and return True if they match"""
set1 = table[letter1]
set2 = table[letter2]
if set1 & set2 != set():
is_match = True
else:
is_match = False
return is_match | 190d00cb52890e52f58e07192227f9af7173ee35 | 33,767 |
import numpy as np
def get_swarm_yspans(coll, round_result=False, decimals=12):
"""
Given a matplotlib Collection, will obtain the y spans
for the collection. Will return None if this fails.
Modified from `get_swarm_spans` in plot_tools.py.
"""
_, y = np.array(coll.get_offsets()).T
try:
... | 2561f04243e63dfa87896e891ae337ab9be310a7 | 33,768 |
def secondes(heure):
"""Prend une heure au format `H:M:S` et renvoie le nombre de secondes
correspondantes (entier).
On suppose que l'heure est bien formattée. On aura toujours un nombre
d'heures valide, un nombre de minutes valide et un nombre de secondes valide.
"""
H, M, S = heure.split(":")... | 33d380005479d66041e747130a4451c555baf497 | 33,769 |
def central_crop(image, crop_height, crop_width, channels=3):
"""Performs central crops of the given image list.
Args:
image: a 3-D image tensor
crop_height: the height of the image following the crop.
crop_width: the width of the image following the crop.
Returns:
3-D tensor with ... | fc9ad33ad5fc9150a299328fb3c77bb662c25339 | 33,770 |
import enum
def mapper_or_checker(container):
"""Callable to map the function parameter values.
Parameters
----------
container : dict-like object
Raises
------
TypeError
If the unit argument cannot be interpreted.
Example
-------
>>> conv = mapper_or_checker({True: ... | 7c8b22fd3ef7fa52b7ebb94f7d5b5fda48a1a683 | 33,771 |
def cmd_konesyntees(bot, update, args):
"""Use superior estonian technology to express your feelings like you've never before!"""
chatid = update.message.chat_id
text = ''
for x in args:
text += f'{x} '
try:
tts = gTTS(text=text, lang='et')
tts.save('bot/konesyntees/konesynt... | 368ebd43191c219f4f0d7b3b362bb94d117d238e | 33,772 |
def tinynet_a(pretrained=False, **kwargs):
""" TinyNet """
r, c, d = TINYNET_CFG['a']
default_cfg = default_cfgs['tinynet_a']
assert default_cfg['input_size'] == (3, 224, 224)
channel, height, width = default_cfg['input_size']
height = int(r * height)
width = int(r * width)
default_cfg[... | 08bb62c45f8ed5b3eab3ec3ad2aab2d0bcb917ea | 33,774 |
import requests
def reserve_offer_request(offer_id: int, adult_count: int, children_count: int):
"""
Request order offer
"""
# call to API Gateway for getting offers
response = requests.post(
ORDER_RESERVE_REQUEST_ENDPOINT,
data={
"offer_id": offer_id,
"cust... | d3c2b1d62c7f64229dfbce3b0688f135b0c8ca1a | 33,775 |
def evaluate_nccl(baseline: dict, results: dict, failures: int,
tolerance: int) -> int:
"""
Evaluate the NCCL test results against the baseline.
Determine if the NCCL test results meet the expected threshold and display
the outcome with appropriate units.
Parameters
---------... | 3fdf3d75def46f98f971a1740f397db0b786fd7c | 33,776 |
def calculate_AUC(x_axis, y_axis):
"""
Calculates the Area Under Curve (AUC) for the supplied x/y values.
It is assumed that the x axis data is either monotonoically increasing or decreasing
Input:
x_axis: List/numpy array of values
y_axis: list/numpy array of values
Output:
... | fa474fd210ee9bb86738e9f93795dd580680c2db | 33,777 |
def next_nibble(term, nibble, head, worm):
"""
Provide the next nibble.
continuously generate a random new nibble so long as the current nibble hits any location of the
worm. Otherwise, return a nibble of the same location and value as provided.
"""
loc, val = nibble.location, nibble.value
... | a8861672b0dcc22e5aad2736d87a50f31eb0b864 | 33,779 |
def line_pattern_matrix(wl, wlc, depth, weight, vels):
"""
Function to calculate the line pattern matrix M given in Eq (4) of paper
Donati et al. (1997), MNRAS 291, 658-682
:param wl: numpy array (1D), input wavelength data (size n = spectrum size)
:param wlc: numpy array (1D), central wavelengths ... | fc5e50000ccbd7cad539e7ee2acd5767dd81c8be | 33,780 |
def pandas_join_string_list(row, field, sep=";"):
""" This function checks if the value for field in the row is a list. If so,
it is replaced by a string in which each value is separated by the
given separator.
Args:
row (pd.Series or similar): the row to check
field... | dd185fc0aad5a6247f8ea3280b18a3c910fbd723 | 33,781 |
def OpenClipboardCautious(nToTry=4, waiting_time=0.1):
"""sometimes, wait a little before you can open the clipboard...
"""
for i in range(nToTry):
try:
win32clipboard.OpenClipboard()
except:
time.sleep(waiting_time)
continue
else:
wait... | ac67eb130b2564508eb5b77176736df06032dd9b | 33,782 |
def data_change_url_to_name(subject_data: tuple, column_name: str) -> tuple:
""" Changes names instead of urls in cell data (later displayed on the buttons). """
return tuple(dh.change_url_to_name(list(subject_data), column_name)) | 43030eab85d087c6c09b7154342e60e90f97b28f | 33,783 |
from datetime import datetime
import requests
def get_run_ids(release_id, request_url, auth_token):
"""
Get the test run IDs for the given release ID - each feature will have a unique run ID
:param release_id: the release ID from Azure DevOps
:param request_url: the URL for the Microsoft API
:para... | ee8d99fbe0bdc1a937e889f5184bc854a21ab2a7 | 33,784 |
def operGet(fn):
""" this is Decoration method get opearte """
def _new(self, *args, **kws):
try:
obj = args[0]
#print obj.id
if hasattr(obj, "id") or hasattr(obj, "_id"):
key = operKey(obj, self.name)
args = args[1:]
k... | 8395496d99fc4e88599c77a30836c1d49944240d | 33,785 |
def latent_iterative_pca(layer, batch, conv_method: str = 'median'):
"""Get NxN matrix of principal components sorted in descending order from `layer_history`
Args:
layer_history : list, layer outputs during training
Returns:
eig_vals : numpy.ndarray of absolute value of eigenvalues, s... | 320408f3eec33075e808b9c92de951b7bc30c6ae | 33,786 |
import scipy
def filter_max(data,s=(1,1),m="wrap",c=0.0):
"""
Apply maximum filter to data (real and imaginary seperately)
Parameters:
* data Array of spectral data.
* s tuple defining shape or size taken for each step of the filter.
* m Defines how edges are determinded ('reflect',... | 2e701d2751f394e5a1d25355a8c5b4533972d92d | 33,787 |
def update_alarms(_):
"""
Entry point for the CloudWatch scheduled task to discover and cache services.
"""
return periodic_handlers.update_alarms() | 9e5f9bf94ed051194e502524420a0e47ac7e75f2 | 33,788 |
def create_mapping(alphabet):
"""
Change list of chars to list of ints, taking sequencial natural numbers
:param alphabet: list of char
:return: dictionary with keys that are letters from alphabet and ints as values
"""
mapping = {}
for (letter, i) in zip(alphabet, range(len(alphabet))):
... | 20ef12101597206e08ca0ea399d97af0f5c8b760 | 33,790 |
async def async_setup_entry(hass, config_entry, async_add_devices):
"""Set up the Alexa alarm control panel platform by config_entry."""
return await async_setup_platform(
hass, config_entry.data, async_add_devices, discovery_info=None
) | 0a80a5d9e2cd5ff8e39200def1d86f30cdc552aa | 33,792 |
def admin_get_all_requests(current_user):
"""Gets all requests"""
requests = admin_get_all(current_user['id'])
return jsonify(requests),200 | a3e7202e73894ab05a4575f98460d1b012c0243e | 33,793 |
import json
def git_drv_info(url, version):
"""
Retrieve the necessary git info to create a nix expression using `fetchgit`.
"""
rev = []
if version != "master":
rev = ["--rev", version]
ret = run_cmd(
["nix-prefetch-git", "--no-deepClone", "--quiet", "--url", url,] + rev
... | d08d40da42fa24c3f50ac2069d8a4b73b4d09b37 | 33,794 |
import colorsys
import random
def draw_bbox(image, bboxes, classes):
"""
[[[original function from Yun-Yuan: bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates.]]]
bboxes: [cls_id, probability, x_min, y_min, x_max, y_max] format coordinates.]
"""
num_classes = len(classe... | 8f479e8ed5ecef60195df5edc82c2b0e2c3e261c | 33,795 |
def is_admin(user):
""" Test if a user has the admin group.
This function is meant to be used by the user_passes_test decorator to control access
to views. It uses the is_member function with a predefined list of groups.
Parameters
----------
user : django.contrib.auth.models.User
The ... | 044550ec2f3aaf8f748fb823b64ba1fb099f71fd | 33,796 |
def Grid(gridtype, *args, **kwargs):
"""Return an instance of the GridBase child class based on type.
Parameters
----------
gridtype : string
Type of grid;
choices: ['cell-centered', 'x-face', 'y-face'].
var_names : list of strings
List of names for the variables to crea... | 29fc912d7cfece5a290950eb9925e99001c8a231 | 33,798 |
def read_tess_lightcurve(filename,
flux_column="pdcsap_flux",
quality_bitmask="default"):
"""Returns a `TessLightCurve`.
Parameters
----------
filename : str
Local path or remote url of a Kepler light curve FITS file.
flux_column : 'pdcsap_f... | 85dec44f2bab3724e5201110d1ec48c283468843 | 33,799 |
async def fix_issue(number: int, *, reason: str=None) -> dict:
"""Synchronously labels the specified issue as fixed, or closed.
:param number: The issue number on GitHub to fix or consider, if a suggestion
:param reason: The reason the issue was not considered.
Note: this parameter only applies to ... | aef20cc669267eabc441ca7b5102f41d3767c482 | 33,800 |
from typing import List
from typing import Tuple
from typing import Set
import re
from typing import OrderedDict
def _parse_schema(s: str) -> Schema:
"""Instantiate schema dict from a string."""
tables: List[Tuple[str, Fields]] = []
seen: Set[str] = set()
current_table = ''
current_fields: List[Fi... | 0f84b794d8ddf563083d603de578c5c646be97de | 33,801 |
def mom2(data, axis=0):
"""
Intensity-weighted coordinate dispersion (function version). Pixel units.
"""
shp = list(data.shape)
n = shp.pop(axis)
x = np.zeros(shp)
x2 = np.zeros(shp)
w = np.zeros(shp)
# build up slice-by-slice, to avoid big temporary cubes
for loc in range(n)... | 6b47cf9e9486b6631462c9dca2f4079361b4c057 | 33,802 |
def get_rdf_bin_labels(bin_distances, cutoff):
"""
Common function for getting bin labels given the distances at which each
bin begins and the ending cutoff.
Args:
bin_distances (np.ndarray): The distances at which each bin begins.
cutoff (float): The final cutoff value.
Returns:
... | 81e8e3dc217e69c504eb1b916e0d09a499228d34 | 33,803 |
import math
def tangent_point(circle, circle_radius, point, angle_sign=1):
"""Circle tangent passing through point, angle sign + if clockwise else - """
circle2d, point2d = a2(circle), a2(point)
circle_distance = dist2d(circle2d, point2d) + 1e-9
relative_angle = math.acos(Range(circle_radius / circ... | e3cbf843e893e436df1e7ad492e2bfb8a63a0bf2 | 33,804 |
def range_projection(current_vertex, fov_up=3.0, fov_down=-25.0, proj_H=64, proj_W=900, max_range=50):
""" Project a pointcloud into a spherical projection, range image.
Args:
current_vertex: raw point clouds
Returns:
proj_range: projected range image with depth, each pixel contains... | aa7efa9ab365cb3e9aaf531c799a9e9615934aac | 33,805 |
def _get_blobs(im, rois, mask=False):
"""Convert an image and RoIs within that image into network inputs."""
blobs = {'data' : None, 'rois' : None}
blobs['data'], im_scale_factors = _get_image_blob(im)
if not cfg.TEST.HAS_RPN or mask:
blobs['rois'] = _get_rois_blob(rois, im_scale_factors)
re... | 3e7dea823fd3471c939d779ee57067e0e856e069 | 33,806 |
from typing import List
def urls() -> List[str]:
"""
Returns all URLs contained in the pasteboard as strings.
"""
urls = general_pasteboard().URLs
str_urls = []
if urls is not None:
for url in urls:
str_urls.append(str(url.absoluteString))
return str_urls | 0ddf0e88ae588a5ee0ac7dbf40dc8e261296cfe7 | 33,807 |
def eager_no_dists(cls, *args):
"""
This interpretation is like eager, except it skips special distribution patterns.
This is necessary because we want to convert distribution expressions to
normal form in some tests, but do not want to trigger eager patterns that
rewrite some distributions (e.g. N... | 6f3b4e279001c929348ba7c07bdc34c45d0b32ae | 33,808 |
def euclid_dist(
arr1,
arr2,
unsigned=True):
"""
Calculate the element-wise correlation euclidean distance.
This is the distance D between the identity line and the point of
coordinates given by intensity:
\\[D = abs(A2 - A1) / sqrt(2)\\]
Args:
arr1 (ndarray... | 44f242ac21b97dea8d8e5c933e51cbbbaae80b7b | 33,810 |
def compute_redshift_path_per_line(Wobs, wa, fl,er,sl=3.,R=20000,FWHM=10,wa0=1215.67,fl_th=0,zmin=None,zmax=None):
"""Compute the total redshift path for a given line with Wobs
(could be a np.array), in a given spectrum fl (with error er)."""
#define N, number of lines
try:
N = len(Wobs)
... | f15a24e0414bb03280d197abde14073b1466cab7 | 33,811 |
import sympy
def guard(clusters):
"""
Split Clusters containing conditional expressions into separate Clusters.
"""
processed = []
for c in clusters:
free = []
for e in c.exprs:
if e.conditionals:
# Expressions that need no guarding are kept in a separat... | 9acb1aecb8423e670cb0b60747bac2b32d56dbe8 | 33,812 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Hello World from a config entry."""
# Store an instance of the "connecting" class that does the work of speaking
# with your actual devices.
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = hub.Hub(hass, entry.data... | 9a3005c02a2d665ab5cab96a15fee8d3e353f5c3 | 33,813 |
def make_viewnames(pathnames, tfm_unique_only=False, order_func=default_viewname_order):
"""
Make all view names from the paths given as arguments.
Parameters
----------
pathnames : list[str]
tfm_unique_only : bool
Default: False. If True, returns only the views that give *different* im... | 26558877ffed5d06a66b459bce64385f116fa952 | 33,814 |
def installed_packages():
"""Returns a list of all installed packages
Returns:
:obj:`list` of :obj:`str`: List of all the currently installed packages
"""
_check_for_old_versions()
return [x["name"] for x, _ in _iter_packages()] | 11aca5f8830d66961ac0af351eb5b4633a82808c | 33,815 |
def get_hponeview_client(args):
"""Generate an instance of the HPE OneView client.
:returns: an instance of the HPE OneView client.
:raises: OneViewConnectionError if try a secure connection without a CA
certificate file path in Ironic OneView CLI configuration file.
"""
ssl_certificat... | 6a667caab302815c17e84edd52cb08a375ed587b | 33,816 |
def random_binary_tree(depth, p=.8):
""" Constructs a random binary tree with given maximal depth
and probability p of bifurcating.
Parameters:
depth: The maximum depth the tree can have (might not be reached
due to probabilistic nature of algorithm)
p: Probability that any node bi... | ec44c0fa4d47f1e50ddbdaf4a2aacca988e5d57f | 33,817 |
def make_uid_setter(**kwargs):
"""
Erzeuge eine Funktion, die die UID einer bekannten Ressource setzt;
es wird nichts neu erzeugt
"""
if 'catalog' not in kwargs:
context = kwargs.pop('context')
catalog = getToolByName(context, 'portal_catalog')
else:
catalog = kwargs.pop(... | 2676ca013fcd376cf4df4a8d314cc52cd91210e8 | 33,818 |
from gi.repository import Gtk
def build_action_group(obj, name=None):
"""
Build actions and a Gtk.ActionGroup for each Action instance found in obj()
(that's why Action is a class ;) ). This function requires GTK+.
>>> class A:
... @action(name='bar')
... def bar(self): print('Say bar... | 26abe527d4e0d1e98080480e60d51e4a23be5d80 | 33,819 |
def afftdn(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#afftdn"""
return filter(stream, afftdn.__name__, *args, **kwargs) | e4a878b29f47fec06b0c6c63ae305c17361f522c | 33,820 |
def sh2vap(q, p):
"""Specific Humidity to Water vapor pressure
formula derived from ratio of humid air vs. total air
Parameters
----------
q specific humidity [kg/kg]
p total air pressure [Pa]
Returns
-------
water vapor pressure [Pa]
"""
c = eps() # Rd / Rv = ... | e205499ba1cf36a2521875f341029ae11ba55fc7 | 33,821 |
def triplets(a, b, c):
"""
Time: O(n)
Space: O(n lg n), for sorting
-
n = a_len + b_len + c_len
"""
a = list(sorted(set(a)))
b = list(sorted(set(b)))
c = list(sorted(set(c)))
ai = bi = ci = 0
a_len, c_len = len(a), len(c)
answer = 0
while bi < len(b):
while ... | d15d340d0a4b870124bbfd8ca6f40358a27f7555 | 33,822 |
import collections
def flatten_dict(d, parent_key='', joinchar='.'):
""" Returns a flat dictionary from nested dictionaries
the flatten structure will be identified by longer keys coding the tree.
A value will be identified by the joined list of node names
e.g.:
{'a': {'b': 0,
... | 5567d880287af3641dc96c7e79b81f93e9d3fbfd | 33,823 |
import torch
def face_vertices(vertices, faces):
"""
:param vertices: [batch size, number of vertices, 3]
:param faces: [batch size, number of faces, 3]
:return: [batch size, number of faces, 3, 3]
"""
assert (vertices.ndimension() == 3)
assert (faces.ndimension() == 3)
assert (vertic... | ecf99dd157044034abcc6bdf12d307a8f560bd9e | 33,824 |
def get_results(tickers=None):
"""
Given a list of stock tickers, this print formatted results to the terminal.
"""
if tickers == ['']:
return
stocks = QuarterlyReport.get_stocks(tickers)
if verbose:
string_header = '{:<10}'.format('Ticker') + '{:<17}'.format('Earnings Date')
... | 21d298df4c8fe34d055f6978cf96306fa31fcce1 | 33,825 |
def reverse_mapper_or_checker(container):
"""Callable to REVERSE map the function parameter values.
Parameters
----------
container : dict-like object
Raises
------
TypeError
If the unit argument cannot be interpreted.
Example
-------
>>> conv = reverse_mapper_or_check... | 616de1fc536af944f6a1bce23b3bdc7c867aa5d8 | 33,826 |
def smallest_boundary_value(fun, discretization):
"""Determine the smallest value of a function on its boundary.
Parameters
----------
fun : callable
A tensorflow function that we want to evaluate.
discretization : instance of `GridWorld`
The discretization. If None, then the functi... | 6a20935d86506cb4bd5d1405301edee02562615b | 33,828 |
def read_ids(idtype, idfile):
"""Read ids from idfile of type idtype."""
print "Using %s file: %s" % (idtype, idfile)
ids = read_dot_name(idfile)
print "%d %s read in." % (len(ids), idtype)
return ids | 815381ce374026c119a4789674de899439e7d76b | 33,829 |
def get_pseudo_class_checker(psuedo_class):
"""
Takes a psuedo_class, like "first-child" or "last-child"
and returns a function that will check if the element satisfies
that psuedo class
"""
return {
'first-child': lambda el: is_first_content_node(getattr(el, 'previousSibling', None)),
... | ad52b55d37f58c2628db88d7f94dcca85ef7e730 | 33,830 |
def gammaincinv(y, s):
"""
Calculates the inverse of the regularized lower incomplete gamma function, i.e.::
\gamma(x; s) = 1/\Gamma(s)\int_0^x t^{s-1}e^{-t} \mathrm{d}t
NOTE:
Inspired by: https://github.com/minrk/scipy-1/blob/master/scipy/special/c_misc/gammaincinv.c
Parameters
-----... | 5b4aa9de4c8b81a1876aafc7f3e7d49384decee4 | 33,831 |
def divide_with_zero_divisor(dividend, divisor):
"""Returns 0 when divisor is zero.
Args:
dividend: Numpy array or scalar.
divisor: Numpy array or scalar.
Returns:
Scalar if both inputs are scalar, numpy array otherwise.
"""
# NOTE(leeley): The out argument should have the broadcasting shape of
... | 80d6acae02da5155ab9d2c0c9b97d12597f79806 | 33,833 |
def str_strip(x):
"""
Apply .strip() string method to a value.
"""
if isnull(x):
return x
else:
return str(x).strip() | 1767625aaee859d506d936d3fb471f13647b9121 | 33,834 |
import mimetypes
def _guess_filetype(filename):
"""Return a (filetype, encoding) tuple for a file."""
mimetypes.init()
filetype = mimetypes.guess_type(filename)
if not filetype[0]:
textchars = bytearray([7, 8, 9, 10, 12, 13, 27]) + bytearray(
range(0x20, 0x100))
with open(f... | 356ed4180b00101a77c4424c5b75ad8a8a473559 | 33,835 |
import re
def inline_anchor_check(stripped_file):
"""Check if the in-line anchor directly follows the level 1 heading."""
if re.findall(Regex.INLINE_ANCHOR, stripped_file):
return True | f0817856f0bb4848470b6179ee59222cce3745d5 | 33,836 |
import numpy
def u_inverse(U, check=False, verbose=False):
"""invert a row reduced U
"""
m, n = U.shape
#items = []
leading = []
for row in range(m):
cols = numpy.where(U[row, :])[0]
if not len(cols):
break
col = cols[0]
leading.append(col)
U1... | 896bf3d79a790e4bae143c06dea2590f3348b800 | 33,837 |
def get_filters(component):
"""
Get the set of filters for the given datasource.
Filters added to a ``RegistryPoint`` will be applied to all datasources that
implement it. Filters added to a datasource implementation apply only to
that implementation.
For example, a filter added to ``Specs.ps_... | d6252d5ecc12ba7cc24f0f2d233d41014e34b637 | 33,839 |
import collections
def parse_traffic_congestion(traffic):
"""Return parsed traffic congestion by regions."""
regions_distances = collections.defaultdict(list)
regions_polygons = parse_regions_bounds()
for route in traffic:
trip_distance = route["trip_distance"]
point = Point((route["tr... | 298e8d8b7f77e9054ff5036184e8ac2bf219b139 | 33,840 |
from typing import Callable
import torch
def batch_mean_metric_torch(
base_metric: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
predictions: torch.Tensor,
ground_truth: torch.Tensor,
) -> torch.Tensor:
"""During training, we may wish to produce a single prediction
for each prediction ... | 7ad19c3ccaa49ea572131ae19ce47af23ad8c821 | 33,842 |
def aggregate_tree(l_tree):
"""Walk a py-radix tree and aggregate it.
Arguments
l_tree -- radix.Radix() object
"""
def _aggregate_phase1(tree):
# phase1 removes any supplied prefixes which are superfluous because
# they are already included in another supplied prefix. For example,
... | 20b73cb24d6989b3ec27706065da0a32eb1aef6c | 33,843 |
def is_dag_acyclic(root_vertex):
"""Perform an acyclicity check for a given DAG.
Returns:
True -- If the DAG contains cycles.
False -- If the DAG does not contain cycles.
"""
visited = set()
for vertex in topological_traverse(root_vertex):
if vertex in visited:
# DAG ha... | f15104e4c515b9a7ad65e6505b717e4a5fa4624d | 33,844 |
def nextPow2(length):
"""
Find next power of 2 <= length
"""
return int(2**np.ceil(np.log2(length))) | 3cab0a91795035358ce0c759f7659089e09bd1e8 | 33,845 |
def convert_parameter_to_model_parameter(parameter, value, meta=None):
"""Convert a Cosmology Parameter to a Model Parameter.
Parameters
----------
parameter : `astropy.cosmology.parameter.Parameter`
value : Any
meta : dict or None, optional
Information from the Cosmology's metadata.
... | 90029124d46514d12b554491c2430ac81a351768 | 33,846 |
import torch
def check_decoder_output(decoder_output):
"""we expect output from a decoder is a tuple with the following constraint:
- the first element is a torch.Tensor
- the second element can be anything (reserved for future use)
"""
if not isinstance(decoder_output, tuple):
msg = "Fari... | 06728dc055c3487511ee5a0f645eccb89c412ba7 | 33,847 |
def _write_segmented_read(
model, read, segments, do_simple_splitting, delimiters, bam_out
):
"""Split and write out the segments of each read to the given bam output file.
NOTE: Assumes that all given data are in the forward direction.
:param model: The model to use for the array segment information.... | e92f3d258653c3cca8a379b4f6a3f2f72d4a54d9 | 33,848 |
def sphinx(**kwargs):
""" Run sphinx """
prog = _shell.frompath('sphinx-build')
if prog is None:
_term.red("sphinx-build not found")
return False
env = dict(_os.environ)
argv = [
prog, '-a',
'-d', _os.path.join(kwargs['build'], 'doctrees'),
'-b', 'html',
... | 353479427fb434bd63af44dbfecd621973e694cf | 33,849 |
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they
want
"""
print("on_launch requestId=" + launch_request['requestId'] +
", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response(l... | 64d3854459b2a5f454607bf4de12154b342f2ace | 33,850 |
def generate_all_overhangs(overhang_length=4):
"""Generate list Overhang class instances for all overhangs of given length.
**Parameters**
**overhang_length**
> Length of overhangs (`int`).
"""
overhang_pairs = generate_overhang_pairs(overhang_length=overhang_length)
overhang_strings = [n... | 04268fd00fb5718d224e477180f6794b0144bfee | 33,851 |
import csv
def csv_to_list(filename: str) -> list:
"""Receive an csv filename and returns rows of file with an list"""
with open(filename) as csv_file:
reader = csv.DictReader(csv_file)
csv_data = [line for line in reader]
return csv_data | d7344496271de6edcb3fc1df30bb78dd00980c30 | 33,852 |
import resource
def create_rlimits():
"""
Create a list of resource limits for our jailed processes.
"""
rlimits = []
# No subprocesses.
rlimits.append((resource.RLIMIT_NPROC, (0, 0)))
# CPU seconds, not wall clock time.
cpu = LIMITS["CPU"]
if cpu:
# Set the soft limit ... | f3cf9589f9784295d620f2ff2c2b17d09a56c8df | 33,853 |
def sqrt(x):
"""
Calculate the square root of argument x.
"""
#initial gues for square root
z = x/2.0
#Continuously improve the guess
#Adadapted from https://tour.golang.org/flowcontrol/8
while abs(x - (z*z)) > 0.0001:
z = z-(z*z - x) / (2*z)
return z | 5598eb37bc56e3f514f75be0deae0b6a94c3831e | 33,854 |
def create_french_dict_from(file_path):
"""Transform a text file containing (weight, word) tuples into python dictionnary."""
with open(file_path, 'r', encoding="ISO-8859-1") as file:
lines = file.readlines()
french_dict = {}
for line in lines:
couple = line.strip().replace('\n', '').sp... | 435be928dc8e3e03e55b4e0b485ee633b21c1b3c | 33,855 |
def construct(data_dir, fname, Y=None, normalize=False, _type='sparse'):
"""Construct label class based on given parameters
Arguments
----------
data_dir: str
data directory
fname: str
load data from this file
Y: csr_matrix or None, optional, default=None
data is already ... | 397101b14b33d92921a14f43f7f4184e759a33a1 | 33,856 |
def test_NN_MUL_REDC1(op):
""" Generate tests for NN_MUL_REDC1 """
# Odd modulus
nn_mod = get_random_bigint(wlen, MAX_INPUT_PARAM_WLEN) | 1
nn_r, nn_r_square, mpinv = compute_monty_coef(nn_mod, getwlenbitlen(nn_mod, wlen))
# random value for input numbers modulo our random mod
nn_in1 = get_rand... | cc45a7970079d0f0579f1a9e97f773c9202e5674 | 33,857 |
import json
def GetAzureStorageConnectionString(storage_account_name, resource_group_args):
"""Get connection string."""
stdout, _ = vm_util.IssueRetryableCommand(
[AZURE_PATH, 'storage', 'account', 'show-connection-string',
'--name', storage_account_name] + resource_group_args + AZURE_SUFFIX)
resp... | 625fe1d0302a6ab4a29b1ec98a1cffccaabdeb93 | 33,858 |
def clean_data(answers, dupes, min_dupes, min_text, questions, show_output):
"""
:param answers:
:param dupes:
:param min_dupes:
:param min_text:
:param questions:
:param show_output:
:return:
"""
for dataframe in (questions, dupes, answers):
dataframe["Text"] = datafram... | 6d9d753bf2d8267fb517c21de2dc2a34357dfb90 | 33,859 |
def on_intent(intent_request, session):
""" Called when the user specifies an intent for this skill """
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
intent_name = intent_request['intent']['name']
print(intent_request['intent']['name'])
... | 8d7a54b5a3f83a7dc3d9923e0631646b9fc27ab6 | 33,860 |
from typing import Type
import inspect
def ta_adaptor(indicator_mixin: Type[IndicatorMixin], function_name: str, **kwargs) -> callable:
"""Wraps strategies from ta to make them compatible with infertrade's interface."""
indicator_parameters = inspect.signature(indicator_mixin.__init__).parameters
allowed_... | abf0f7851f1a47263aca4bb2e032af48d0ab5b0a | 33,861 |
def flops(program, only_conv=True, detail=False):
"""Get FLOPs of target graph.
Args:
program(Program): The program used to calculate FLOPS.
only_conv(bool): Just return number of mul-adds in convolution and FC layer if `only_conv` is true.
default: True.
detail... | 25cdfa159addfe2ef52be8aa6d3f1122df1332e0 | 33,863 |
import math
def eq11 (A):
"""Chemsep equation 11
:param A: Equation parameter A"""
return math.exp(A) | 354b33a14f17de2862e5674edc421045c3dd21a9 | 33,864 |
def extractor_to_question(extractor: str):
"""
return questions for a extractor in a tuple
:param extractor:
:return:
"""
if extractor == 'action':
return ('who', 'what')
elif extractor == 'cause':
return ('why',)
elif extractor == 'environment':
return ('where', ... | 9f32562b426b59c4e44efab32064045796ec27ed | 33,865 |
def getpage(url):
"""
Downloads the html page
:rtype: tuple
:param url: the page address
:return: the header response and contents (bytes) of the page
"""
http = httplib2.Http('.cache', disable_ssl_certificate_validation=True)
headers = {
'User-agent': 'Mozilla/5.0 (Windows NT 6... | 1bb8fa3bdc1a083826dc509723b4855d0ec41990 | 33,866 |
from typing import Union
import contextlib
def path_to_xpath(node_or_path: Union[str, ncs.maagic.Node]) -> str:
"""Get the XPath to a node (keypath or maagic Node)
The input can be either:
- string keypath (/devices/device{foo}/config/alu:port...),
- maagic Node instance.
The helper will start a ... | 5f91fccb3d32c780712e7487f06d05b55044073d | 33,867 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.