content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
import re
def _ParseException(log):
"""Searches a log for a stack trace and returns the exception string.
This function supports both default Python-style stacks and Telemetry-style
stacks. It returns the first stack trace found in the log - sometimes a bug
leads to a cascade of failures, so the first one is... | 60d518bf15e8ee883dabb008bacef32db9913367 | 33,809 |
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 |
import copy
import os
def export_detected_regions(
image_path, image, regions, output_dir: str = "output/", rectify: bool = False
):
"""
Arguments:
image_path: path to original image
image: full/original image
regions: list of bboxes or polys
output_dir: folder to be export... | 3ebcce532bdc6267c7afed027949da6d6f18c0b1 | 33,827 |
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 |
import tqdm
def multiprocess_tracking(func, iter, args=(), kwargs={}, tqdm_kwargs={}, single_process=False, max_workers=None, expand_args=False):
"""Using ProcessPoolExecutor to run *func* on multiple processes
Arguments:
func {function} -- Function to be executed
iter {iterable} -- Call ... | d1bec1e2e6dc506e6cf091e5fe2a758b32e2c467 | 33,832 |
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 highlight_symbol_in_DISASM():
"""
Select a symbol in the DECOMP view,
highlight the corresponding symbols in IDA DISASM view.
"""
# print("GhIDA:: [DEBUG] highlight_symbol_in_DISASM called")
disasm_widget = idaapi.find_widget('IDA View-A')
symbol = get_highlighted_identifier()
if not... | b952751ee613b4e962f91379f735b0be2ab524f2 | 33,838 |
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 |
import os
def make_doc(f):
""" Main routine for generating documentation.
"""
global h5gate_file
# save in global variable for Id_doc routines (so do not have to pass it as parameter)
h5gate_file = f
doc_parts = {
'header': [],
'toc': [], # table of contents
'main': [],... | 46ecae29cc6b746635de611be2e49e836e573700 | 33,841 |
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 |
import sys
def get_addresses(inp, out):
"""get_addresses(inp, out): It will search for addresses from gdb.
inp and out, are the gdb input and output respectively. Return value is
a list of tuples. The tuples contain the filename and the address the
filename was loaded."""
addr = []
nxad = 1
while nxad:
if nx... | 1b37b387fff4da88ae590d018ad34da9a27e2104 | 33,862 |
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 |
def read(channel):
"""This function returns the state of a specified GPIO pin."""
GPIO.setup(channel, GPIO.IN)
return GPIO.input(channel) | 89ac5add868935617ad7d4032fd38e91ce704622 | 33,868 |
def sortmerna_indexdb(input_fp, output_fp, params="", HALT_EXEC=False):
"""
"""
cmd = "indexdb_rna --ref %s,%s -v %s" % (input_fp, output_fp, params)
return call_cmd(cmd, HALT_EXEC) | 25c5321fc533a89b8524fe26ddcd1328d260a881 | 33,869 |
import copy
def _extract_original_opp_board(finished_board):
"""
This function removes all shots that have been fired on it, reverting sunken ships to normal. Notably, coordinates
that have hits, but no sunk ship will be set to be empty as the position of the original ship is unclear. The
motivation f... | 60a722909415ffa5bced6e6b4fb640a036dcecaa | 33,870 |
def pool():
"""Fixture that returns a Pool object."""
return MagicMock() | d9f661fb8ec67bdf1694d7d1d62603e8313fd479 | 33,871 |
def extended_gcd(a, b):
""" ----- THIS FUNCTION WAS TAKEN FROM THE INTERNET -----
Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb
"""
# r = gcd(a,b) i = multiplicitive inverse of a mod b
# or j = multiplicitive inverse of b mod a
# Neg return values for i or j are made posi... | 19cb82dcce75c60e4672ecb6de73719452952f2f | 33,872 |
def get_interp_BmV_from_Teff(teff):
"""
Given an effective temperature (or an array of them), get interpolated B-V
color.
"""
mamadf = load_basetable()
mamadf = mamadf[3:-6] # finite, monotonic BmV
mamarstar, mamamstar, mamateff, mamaBmV = (
nparr(mamadf['R_Rsun'])[::-1],
n... | ff7d2bef3daa68addcb0e3317a793d86a2ad0e57 | 33,873 |
import os
def get_upstream_pins(m, dependencies, index):
"""Download packages from specs, then inspect each downloaded package for additional
downstream dependency specs. Return these additional specs."""
dependencies = [strip_channel(dep) for dep in dependencies]
# Add _tmp here to prevent creating ... | 717e82076a3ac6932d7dfc08a33a2f027e9e0380 | 33,874 |
import logging
import os
def process_image(filepath, outpath, settings):
"""Process one image: resize, create thumbnail."""
logger = logging.getLogger(__name__)
logger.info('Processing %s', filepath)
filename = os.path.split(filepath)[1]
outname = os.path.join(outpath, filename)
ext = os.path... | 844417b9808c551186dbe65ff1c3844969f18764 | 33,875 |
import types
import importlib
async def _load_mfa_module(hass: HomeAssistant, module_name: str) -> types.ModuleType:
"""Load an mfa auth module."""
module_path = f"homeassistant.auth.mfa_modules.{module_name}"
try:
module = importlib.import_module(module_path)
except ImportError as err:
... | 115520c3c2f2cf00ae238d189817728f6129130d | 33,876 |
def model_metrics(key,codes="",nb=None,with_doc=False):
"""
param1: dictionary : AutoAI steps data
param2: string : Code syntaxs
param3: boolean : Whether to includer documentation/meta description for the following section
return: string : Code syntaxs
The function adds code syntax related to ... | 3893004b29edc53cdb780b3d6234b732365095a5 | 33,877 |
def so3_rotate_with_normal(batch_data):
""" Randomly rotate the point clouds to augument the dataset
rotation is per shape based along up direction
Input:
BxNx3 array, original batch of point clouds
Return:
BxNx3 array, rotated batch of point clouds
"""
rotated_da... | 90114e4110f0b9e54cc71a77339574ecfa98a194 | 33,878 |
def populate_from_file(filename, gap=0.1,
pool_intensity=4,
pool_capacity=None,
eps_diff=1e-7,
verbose=False):
""" Runs populate on a model file.
:param filename: the model file.
:param gap: MIP gap to use for the p... | f5e2ab7b5558a9f72593395055652b8e6d11eb94 | 33,879 |
def dihedral(p):
"""Praxeolitic formula 1 sqrt, 1 cross product"""
p0 = p[0]
p1 = p[1]
p2 = p[2]
p3 = p[3]
b0 = -1.0*(p1 - p0)
b1 = p2 - p1
b2 = p3 - p2
# normalize b1 so that it does not influence magnitude of vector
# rejections that come next
b1 /= np.linalg.norm(b1)
... | d6c1e2e0f1f4eb0fd10d34040371e1ba7dda8514 | 33,880 |
def mangle_varname(s):
"""Append underscores to ensure that `s` is not a reserved Python keyword."""
while s in _PYTHON_RESERVED_KEYWORDS:
s += "_"
return s | e679a0ff33c7df91c73f38c826c8f1a23dc185d9 | 33,881 |
def standard_prediction_error(x_data, y_data):
"""Return function to calculate standard prediction error.
The standard prediction error of a linear regression is the error when
predicting a new value which is not in the original data.
Parameters
----------
x_data : numpy.array
x coordi... | e11497c9c4385a07cdabab2b8ad72273f237fdfb | 33,882 |
import copy
def update_dict(original, new):
"""
Update nested dictionary (dictionary possibly containing dictionaries)
If a field is present in new and original, take the value from new.
If a field is present in new but not original, insert this field
:param original: source dictionary
:typ... | 1608d28321d294943f4c955e42939b054966751f | 33,883 |
from typing import Tuple
import yaml
from pathlib import Path
def parse() -> Tuple[Response, int]:
"""
Parse the inputs of a workflow.
"""
req_data = yaml.safe_load(request.get_data().decode("utf-8"))
wf_location = req_data.get("wf_location", None)
wf_content = req_data.get("wf_content", None)... | a45694c7498b36acc08353a379db665ad79480cd | 33,884 |
def try_which():
""" Locate hmmsearch on path, if possible
:return:
"""
try:
return str(local["which"]["hmmsearch"]()).rstrip("\r\n")
except ProcessExecutionError:
return "None" | 5360db37bf6f31ee560fefda8897688dcef5d739 | 33,885 |
def getCountryClubCreditMultiplier(countryClubId):
"""
Returns the skill credit multiplier for a particular mint.
mintId is the mint-interior zone defined in ToontownGlobals.py.
"""
return {
BossbotCountryClubIntA: 2.,
BossbotCountryClubIntB: 2.5,
BossbotCountryClubIntC: 3.,
... | c5ac7f3a9198beeeabd1390843449cf0dc594aef | 33,886 |
def get_world_rank() -> int:
"""Get the world rank of this worker.
.. code-block:: python
import time
from ray.air import session
def train_loop_per_worker():
for iter in range(100):
time.sleep(1)
if session.get_world_rank() == 0:
... | ab62942a269249f13c40d060fd597b62c473732f | 33,887 |
def solve():
"""
Replace this with a nice docstring
that describes what this function is supposed
to do.
:return: The answer required.
"""
return -1 | f054515e7bb23bb84ecfb1847410fa111ec431c6 | 33,888 |
def read_data(files, poscount, locidx):
"""Builds input data from a files list."""
locs = [] # One element per file; each is a list of location indexes.
vals = [] # One element per file; each is a parallel list of values.
labels = [] # One element per file: true for '.s', false for '.f'.
for fnam... | 6e64b8a445134b78498aefa9b8a87893ae16b35f | 33,889 |
def deterministic_dynamics(init_cond, dt, num_steps, init_time=0.0):
"""
Uses naive euler's method: x(t+dt) = x_k + F(x_k, t_k) * dt
"""
# prep arrays
states = np.zeros((num_steps, STATE_DIM))
times = np.zeros(num_steps)
# fill init cond
states[0, :] = init_cond
times[0] = init_time
... | 8d9ec7bc99dfb51b03d9c5844de233d59fc8945c | 33,890 |
def get_scope_and_reuse_disc(network_id, layer_id, num_separate_layers):
"""Return the scope and reuse flag.
Args:
network_index: an integer as the network index.
layer_id: an integer as the index of the layer.
num_separate_layers: an integer as how many layers are independent.
Ret... | 8a52cdf4af4a6d545c172565f8c2151176572076 | 33,891 |
import logging
def groups_list(access_token):
"""List FlexVM Groups"""
logging.info("--> List FlexVM Groups...")
uri = FLEXVM_API_BASE_URI + "groups/list"
headers = COMMON_HEADERS.copy()
headers["Authorization"] = f"Bearer {access_token}"
results = requests_post(uri, "", headers)
return ... | 7ec8a362e88349b28279f12d32319b9b1d8b5a45 | 33,892 |
import sys
def get_data_for_run(butler, run_id, **kwargs):
"""Builds a dictionary of filenames or butler dataids for
a particular run and test type, given a data access method, teststand
Parameters
----------
butler : `Butler` or `None`
The data Butler
run_id : `str`
The numbe... | d3df412dad0323f66623004582be7ef2d9e0a457 | 33,893 |
import os
def files_from_folder(path, extension):
""" Returns files within folder with given extension
Args:
path->str: path to input directory
extension->str: file type to find
Returns: List of paths
"""
files = []
for root, subfolders, some_files in os.walk(path):
for som... | cb622425fcdea085a325df5905ffd311d40560c5 | 33,894 |
def format_route(raw_route):
"""Cleans and formats route list into valid REXX input.
Arguments:
route {list} -- user input for route
Returns:
{bool} -- Flag indicating valid route.
{str} -- Error message.
{list} -- List of validated routes.
"""
raw_route_list = ... | c23708f8384d2947ad3a161bbfd33f189446f424 | 33,895 |
def gamma_lnpdf(x, shape, rate):
""" shape/rate formulation on wikipedia """
coef = shape * np.log(rate) - gammaln(shape)
dterm = (shape-1.) * np.log(x) - rate*x
return coef + dterm | 692ca281ea51f2f01ecddfb59eb16fcf6379f2c2 | 33,896 |
from functools import reduce
def get_total_variation(variable_img, shape, smoothing=1.5):
"""Compute total variation regularization loss term given a variable image (x) and its shape.
Args:
variable_img: 4D tensor representing the variable image
shape: list representing the variable image... | 83e5135bf9cba692a5fa40dae8a037f0a1749370 | 33,897 |
def dict_filter(d, keep):
"""
Remove all keys from dict except those specified in list 'keep'.
Recurses over values to remove keys from nested dictionaries
:param d: Dictionary from which to select key,value pairs
:type d: dict
:param remove: Keys to select
:type remove: list
:returns: dictionary with ke... | 20d4e5b86558be95d3b5cb31525407cbf98be3c1 | 33,898 |
def tf_depthwise_conv2d(input, w):
"""Two-dimensional depthwise convolution using TF.
Params same as in depthwise_conv2d.
"""
input_4d = tf.reshape(tf.constant(input, dtype=tf.float32),
[1, input.shape[0], input.shape[1], input.shape[2]])
# Set channel_multiplier dimension... | c8b78da33463271d3c42a401f68d09c961953972 | 33,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.