content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ifft_function(G,Fs,axis=0):
"""
This function gives the IDFT
Arguments
---------------------------
G : double
DFT (complex Fourier coefficients)
Fs : double
sample rate, maximum frequency of G times 2 (=F_nyquist*2)
axis : double
the axis on which the IDFT... | 901218d6c795d0ee3163496b6889899b9be16342 | 3,638,200 |
def user_tweets_stats_grouped_new(_, group_type):
"""
Args:
_: Http Request (ignored in this function)
group_type: Keyword defining group label (day,month,year)
Returns: Activities grouped by (day or month or year) wrapped on response's object
"""
error_messages = []
success_messages = []
status = HTTP_2... | e1fc3dfd96fde3f2e01822b79bd97e508982e3d4 | 3,638,201 |
import itertools
def analyse_editing_percent(pileup_file, out_file, summary_file=None, add_headers=False, summary_only=False, min_editing=0,
max_noise=100, min_reads=1, edit_tag='' ):
"""
analyses pileup file editing sites and summarises it
@param pileup_file: input pileup file... | 2e34c3e32fb8ac9d5b4dabb188d404b5cf052466 | 3,638,202 |
def login_required(func, *args, **kwargs):
"""
This is a decorator that can be applied to a Controller method that needs a logged in user.
The inner method receives the Controller instance and checks if the user is logged in
using the `request.is_authenticated` Boolean on the Controller instance
:p... | 3611bb87544ece2516d4a738e3ab68b58ee154f4 | 3,638,203 |
def preProcessImage(rgbImage):
""" Preprocess the input RGB image
@rgbImage: Input RGB Image
"""
# Color space conversion
img_gray = cv2.cvtColor(rgbImage, cv2.COLOR_BGR2GRAY)
img_hsv = cv2. cvtColor(rgbImage, cv2.COLOR_BGR2HLS)
ysize, xsize = getShape(img_gray)
#Detecting yellow and w... | ea70956bca99e28a6928867a40a3b579e2c8931b | 3,638,204 |
from typing import List
from typing import Dict
from typing import Any
import time
import json
def consume_messages(consumer: Consumer, num_expected: int, serialize: bool = True) -> List[Dict[str, Any]]:
"""helper function for polling 'everything' off a topic"""
start = time.time()
consumed_messages = []
... | 5bf5db5180222d235e08a65a4e67e6daccf9c4d7 | 3,638,205 |
def get_compressed_size(data, compression, block_size=DEFAULT_BLOCK_SIZE):
"""
Returns the number of bytes required when the given data is
compressed.
Parameters
----------
data : buffer
compression : str
The type of compression to use.
block_size : int, optional
Input... | f7c72cf7097ee9f15b9aa0b1b6d46fe060cc0c15 | 3,638,206 |
def flat_command(bias=False,
flat_map=False,
return_shortname=False,
dm_num=1):
"""
Creates a DmCommand object for a flat command.
:param bias: Boolean flag for whether to apply a bias.
:param flat_map: Boolean flag for whether to apply a flat_map.
... | 7b375c4b73686f286f07b8a327f2237e3ecb9ad0 | 3,638,207 |
def plot_graph_routes(
G,
routes,
bbox=None,
fig_height=6,
fig_width=None,
margin=0.02,
bgcolor="w",
axis_off=True,
show=True,
save=False,
close=True,
file_format="png",
filename="temp",
dpi=300,
annotate=False,
node_color="#999999",
node_size=15,
... | 333479cd0924df968f66ba328735a309a10e41a9 | 3,638,208 |
import re
def _parse_book_info(html):
"""解析豆瓣图书信息(作者,出版社,出版年,定价)
:param html(string): 图书信息部分的原始html
"""
end_flag = 'END_FLAG'
html = html.replace('<br>', end_flag)
html = html.replace('<br/>', end_flag)
doc = lxml.html.fromstring(html)
text = doc.text_content()
pattern = r'{}[::]... | d327d9561a1306f1242f1f78c01517bd2358aa0b | 3,638,209 |
def offers(request, region_slug, language_code=None):
"""
Function to iterate through all offers related to a region and adds them to a JSON.
Returns:
[String]: [description]
"""
region = Region.objects.get(slug=region_slug)
result = []
for offer in region.offers.all():
resu... | d0256abb9a1fda0fd0296dab811f3bef2091c6d3 | 3,638,210 |
def get_ellipse(mu: np.ndarray, cov: np.ndarray, draw_legend: bool = True):
"""
Draw an ellipse centered at given location and according to specified covariance matrix
Parameters
----------
mu : ndarray of shape (2,)
Center of ellipse
cov: ndarray of shape (2,2)
Covariance of G... | 639e2161819e76c485efaf22598cfcc601a10122 | 3,638,211 |
from typing import Sequence
from typing import List
import hashlib
from typing import Dict
def load_hashes(
filename: str, hash_algorithm_names: Sequence[str]
) -> HashResult:
"""
Load the size and hash hex digests for the given file.
"""
# See https://github.com/python/typeshed/issues/2928
... | 6846e39838f2017a46472826ba07bc9974e80c5a | 3,638,212 |
def ucs(st: Pixel, end: Pixel, data: np.ndarray):
"""
Iterative method to find a Dijkstra path, if one exists from current to end vertex
:param startKey: start pixel point key
:param endKey: end pixel point key
:return: path
"""
q = PriorityQueue()
startPri... | 743dbe230073bde4ba7b95e4520f097d8f7a4443 | 3,638,213 |
def tvdb_refresh_token(token: str) -> str:
"""
Refreshes JWT token.
Online docs: api.thetvdb.com/swagger#!/Authentication/get_refresh_token.
"""
url = "https://api.thetvdb.com/refresh_token"
headers = {"Authorization": f"Bearer {token}"}
status, content = request_json(url, headers=headers, ... | a1974f43ed0e314100c686545bb610be9cc910ed | 3,638,214 |
def get_data():
""" _ _ _ """
df_hospital = download_hospital_admissions()
#sliding_r_df = walkingR(df_hospital, "Hospital_admission")
df_lcps = download_lcps()
df_mob_r = download_mob_r()
df_gemeente_per_dag = download_gemeente_per_dag()
df_reprogetal = download_reproductiegetal()
df_... | 2a9b909dc53b710ce9f1729e336464857a27bb30 | 3,638,215 |
def load_bin_file(bin_file, dtype="float32"):
"""Load data from bin file"""
data = np.fromfile(bin_file, dtype=dtype)
return data | facdabb726efd66ce6e7e462aed9458d8f3dc947 | 3,638,216 |
def nearest_value(array, value):
"""
Searches array for the closest value to a given target.
Arguments:
array {NumPy Array} -- A NumPy array of numbers.
value {float/int} -- The target value.
Returns:
float/int -- The closest value to the target value found in the array.
""... | e9bf37b02bd55a0bdd9bf6f001aca6bc69895d8c | 3,638,217 |
def interpret_go_point(s, size):
"""Convert a raw SGF Go Point, Move, or Stone value to coordinates.
s -- 8-bit string
size -- board size (int)
Returns a pair (row, col), or None for a pass.
Raises ValueError if the string is malformed or the coordinates are out of
range.
Only support... | 6b15b141e9fe5fc4195133f24925672522cdcb35 | 3,638,218 |
def get_domain_name_for(host_string):
"""
Replaces namespace:serviceName syntax with serviceName.namespace one,
appending default as namespace if None exists
"""
return ".".join(
reversed(
("%s%s" % (("" if ":" in host_string else "default:"), host_string)).split(
... | 6084e299f31d9c2eb922783d0488e9672051443f | 3,638,219 |
def bbox_classify(bboxes, possible_k):
"""bbox: x, y, w, h
return: best kmeans score anchor classes [(w1, h1), (w2, h2), ...]
"""
anchors = [bbox[2:4] for bbox in bboxes]
return anchors_classify(anchors, possible_k) | 5387c1441c94f4af0633b9cf73b0e5e53ce1bc9b | 3,638,220 |
def cleanFAAText(origText):
"""Take FAA text message and trim whitespace from end.
FAA text messages have all sorts of trailing whitespace
issues. We split the message into lines and remove all
right trailing whitespace. We then recombine them into
a uniform version with no trailing whitespace.
... | ea9882e24c60acaa35cae97f8e95acb48f5fd2a6 | 3,638,221 |
def LoadModel(gd_file, ckpt_file):
"""Load the model from GraphDef and Checkpoint.
Args: gd_file: GraphDef proto text file. ckpt_file: TensorFlow Checkpoint file.
Returns: TensorFlow session and tensors dict."""
with tf.Graph().as_default():
#class FastGFile: File I/O wrappers without thread loc... | 08089910da145141df8446c1aab9d697b15a3aa6 | 3,638,222 |
from bs4 import BeautifulSoup
import re
def get_additional_rent(offer_markup):
""" Searches for additional rental costs
:param offer_markup:
:type offer_markup: str
:return: Additional rent
:rtype: int
"""
html_parser = BeautifulSoup(offer_markup, "html.parser")
table = html_parser.fi... | 8836beda16e21fe214344d647de9260195afa6a7 | 3,638,223 |
def make_known_disease_variants_filter(sample_ids_list=None):
""" Function for retrieving known disease variants by presence in Clinvar and Cosmic."""
result = {
"$or":
[
{
"$and":
[
... | 288e5a0daa254016f9c1e1ee8e3106ea532008ec | 3,638,224 |
import multiprocessing
def sharedArray(dtype, dims):
"""Create a shared numpy array."""
mpArray = multiprocessing.Array(dtype, int(np.prod(dims)), lock=False)
return np.frombuffer(mpArray, dtype=dtype).reshape(dims) | e01b20f0f21386dd2ec8e1952547fbc9fc15cb65 | 3,638,225 |
def _read_hyperparameters(idx, hist):
"""Read hyperparameters as a dictionary from the specified history dataset."""
return hist.iloc[idx, 2:].to_dict() | b2a036a739ec3e45c61289655714d9b59b2f5490 | 3,638,226 |
def row_annotation(name=None, fn_require=None):
"""
Function decorator for methods in a subclass of BaseMTSchema.
Allows the function to be treated like an row_annotation with annotation name and value.
@row_annotation()
def a(self):
return 'a_val'
@row_annotation(name=... | 443ce2c3259613352ccb6f1e9d687e89448d37d7 | 3,638,227 |
import os
def path_exists_case_insensitive(path, root="/"):
"""
Checks if a `path` exists in given `root` directory, similar to
`os.path.exists` but case-insensitive. If there are multiple
case-insensitive matches, the first one is returned. If there is no match,
an empty string is returned.
... | 0bfbc6fb91220b85e11eeed9acb23bf02fd0cc78 | 3,638,228 |
def parse_time(date_time, time_zone):
"""Returns the seconds between now and the scheduled time."""
now = pendulum.now(time_zone)
update = pendulum.parse(date_time, tz=time_zone)
# If a time zone is not specified, it will be set to local.
# When passing only time information the date will default t... | 5ca2f5dad85e3492bd9909808990aaef0587343a | 3,638,229 |
import os
def ls(request):
"""
List a directory on the server.
"""
dir = request.GET.get("dir", "")
root = os.path.relpath(os.path.join(
settings.MEDIA_ROOT,
settings.USER_FILES_PATH
))
fulldir = os.path.join(root, dir)
response = HttpResponse(mimetype="application/jso... | 6323ad4f23addf7e475744b36bb47e279e1eb2a7 | 3,638,230 |
def upper_bounds_max_ppr_target(adj, alpha, fragile, local_budget, target):
"""
Computes the upper bound for x_target for any teleport vector.
Parameters
----------
adj : sp.spmatrix, shape [n, n]
Sparse adjacency matrix.
alpha : float
(1-alpha) teleport[v] is the probability to... | 5bab951605ad5181e2fb696836219167dd78a30e | 3,638,231 |
import os
def import_layer_data(node, path):
"""Import ngLayerData from JSON file.
Args:
node (str): Name of the mesh. Used to find the JSON file.
path (str): The parent folder where the file is saved.
Returns:
str: The raw ngLayer data (somehow, this is a string!)
"""
ni... | e0421387245fe938ee644fab277d8943aa64129d | 3,638,232 |
def cramers_corrected_stat(contingency_table):
"""
Computes corrected Cramer's V statistic for categorial-categorial association
"""
try:
chi2 = chi2_contingency(contingency_table)[0]
except ValueError:
return np.NaN
n = contingency_table.sum().sum()
phi2 = chi2... | 89581fbcc306afdf34dac8cb30d3e7b316a47f48 | 3,638,233 |
def frame_comps_from_set(frame_set):
"""
A `set` of all component names every defined within any frame class in
this `TransformGraph`.
Broken out of the class so this can be called on a temporary frame set to
validate new additions to the transform graph before actually adding them.
"""
res... | 525ea19b78cb2a360165085720d42df58aa72500 | 3,638,234 |
def generate_keyframe_chunks(animated_rotations, animated_locations, animated_scales, num_frames, chunksize):
"""
This function has a very high bug potential...
"""
# These lines create lists of length num_frames with None for frames with no data
rotations = populate_frames(num_frames, animated_rota... | e45fc9b440b5ae278067c9c9f7de41e6c13f14ff | 3,638,235 |
def collection_tail(path_string):
"""Walk the path, return the tail collection"""
# pylint: disable=consider-using-enumerate
coll = None
parts = extract_path(path_string)
if parts:
try:
last_i = len(parts) - 1
coll = bpy.data.collections[parts[0]]
f... | 9a9d4e594c654b35f15870d33bc24314f1c48e5c | 3,638,236 |
from pyadlml.dataset.devices import most_prominent_categorical_values
def create_raw(df_dev, most_likely_values=None):
"""
return df:
| time | dev_1 | .... | dev_n |
--------------------------------
| ts1 | 1 | .... | 0 |
"""
df_dev = df_dev.copy()
df = ... | e6659e70bf91876a3cbfcc98aaa71e4e97837a7f | 3,638,237 |
def p1_marker_loc(p1_input, board_list, player1):
"""Take the location of the marker for Player 1."""
# verify if the input is not in range or in range but in a already taken spot
while p1_input not in range(1, 10) or (
p1_input in range(1, 10) and board_list[p1_input] != " "
):
try:
... | ea8cfd35e56d7e34efa7319667f1a655b597cf39 | 3,638,238 |
def chord(tones, dur, phrasing="", articulation="", ornamentation="", dynamics="", markup="", markdown="", prefix="", suffix=""):
""" Returns a list containing a single Point that prints as a chord with the specified tones and duration. """
tones = flatten([tonify(tones)])
return [Point(tones, dur, phrasing... | b6fc7ba5c7e8541eeea540a869b1697c15c5ea47 | 3,638,239 |
def build_gem_graph():
"""Builds a gem graph, F4,1.
Ref: http://mathworld.wolfram.com/GemGraph.html"""
graph = build_5_cycle_graph()
graph.new_edge(1, 3)
graph.new_edge(1, 4)
return graph | 4979ae5643ca44d6fb5eadd4fff18489fd3b5629 | 3,638,240 |
import select
async def get_forecasts_by_user_year_epic(
user_id, epic_id, year, month, session: Session = Depends(get_session)
):
"""Get forecast by user, epic, year, month"""
statement = (
select(Forecast.id, Forecast.month, Forecast.year, Forecast.days)
.where(Forecast.user_id == user_i... | 655863588ece0800d220386282d620d7296fc8a2 | 3,638,241 |
def face_xyz_to_uv(face, p):
"""(face, XYZ) to UV
see :cpp:func:`S2::FaceXYZtoUV`
"""
if face < 3:
if p[face] <= 0:
return False, 0, 0
else:
if p[face - 3] >= 0:
return False, 0, 0
u, v = valid_face_xyz_to_uv(face, p)
return True, u, v | 3483f918ed511c8fdf3c43e147c6cc605633754b | 3,638,242 |
import re
def cleanupString(string, replacewith="_", regex="([^A-Za-z0-9])"):
"""Remove all non-numeric or alphanumeric characters"""
# Please don't use the logging system here. The logging system
# needs this method, using the logging system here would
# introduce a circular dependency. Be careful no... | b327879a345a4236b871f824937997f6bd43d55b | 3,638,243 |
import socket
import json
def send_message(data, header_size=8):
"""Send data over socket."""
@_retry()
def _connect(socket_path):
"""Connect socket."""
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(socket_path)
sock.settimeout(SOCKET_TIMEOUT)
... | bbe9c11e5b29ac2b0f0d2d9dd357f806a682156b | 3,638,244 |
from typing import Optional
from typing import Set
from typing import Literal
from typing import Any
def _get_mapping_keys_in_condition(
condition: Expression, column_name: str
) -> Optional[Set[str]]:
"""
Finds the top level conditions that include filter based on the arrayJoin.
This is meant to be u... | 7d890e4b68aeba9caca30e5a140214072c781a66 | 3,638,245 |
import requests
from bs4 import BeautifulSoup
def make_request(method, url, **kwargs):
"""Make HTTP request, raising an exception if it fails.
"""
request_func = getattr(requests, method)
response = request_func(url, **kwargs)
# raise an exception if request is not successful
if not response.s... | 1f47b178b66efe31fd78a4affc76a87d5be428bc | 3,638,246 |
def hold(source):
"""Place the active call on the source phone on hold"""
print("Holding call on {0}".format(source.Name))
return operation(source,'Hold') | 297cef77a3630bf3b9cab6256547ec43a5ba797c | 3,638,247 |
import math
def make_grid(batch, grid_height=None, zoom=1, old_buffer=None, border_size=1):
"""Creates a grid out an image batch.
Args:
batch: numpy array of shape [batch_size, height, width, n_channels]. The
data can either be float in [0, 1] or int in [0, 255]. If the data has
only 1 channel it... | 72bbcebd121b13bce31d760b9d8890966155b603 | 3,638,248 |
def _get_patterns_map(resolver, default_args=None):
"""
Cribbed from http://www.djangosnippets.org/snippets/1153/
Recursively generates a map of
(pattern name or path to view function) -> (view function, default args)
"""
patterns_map = {}
if default_args is None:
default_args = {... | 21f149773457b075ba984b028d2c44ac41f09a6a | 3,638,249 |
def encoder_package_to_options(encoder_package, post_url=None,
extra_numerics=None,
extra_categoricals=None,
omitted_fields=None):
"""
:param encoder_package: one hot encoder package
:param post_url: url to send for... | 1286aefef87b547d7a09db8fec3b50f7082e64f8 | 3,638,250 |
def get_subset_values(request, pk):
"""Return the numerical values of a subset as a formatted list."""
values = models.NumericalValue.objects.filter(
datapoint__subset__pk=pk).select_related(
'error').select_related('upperbound').order_by(
'qualifier', 'datapoint__pk')
to... | 1bc34a534a56a7f75742f455aad5575224ce976f | 3,638,251 |
import time
def timestamp(format_key: str) -> str:
"""
格式化时间
:Args:
- format_key: 转化格式方式, STR TYPE.
:Usage:
timestamp('format_day')
"""
format_time = {
'default':
{
'format_day': '%Y-%m-%d',
'format_now': '%Y-%m-%d-%H_%M_%S',
... | dab77afb630193d45fbc5b07c08fd82c3dfa3050 | 3,638,252 |
def _save_conn_form(
request: HttpRequest,
form: SQLConnectionForm,
template_name: str,
) -> JsonResponse:
"""Save the connection provided in the form.
:param request: HTTP request
:param form: form object with the collected information
:param template_name: To render the response
:r... | ee2639e1ab354b6ca722e35167bf6ab7cc57b351 | 3,638,253 |
def client() -> GivEnergyClient:
"""Supply a client with a mocked modbus client."""
# side_effects = [{1: 2, 3: 4}, {5: 6, 7: 8}, {9: 10, 11: 12}, {13: 14, 15: 16}, {17: 18, 19: 20}]
return GivEnergyClient(host='foo') | 9d419927ebcb5a39df27e92e3a378cd5448acf1e | 3,638,254 |
def test_bus(test_system):
"""Create the test system."""
test_system.run_load_flow()
return test_system.buses["bus3"] | fea4880446059171dae5d6fffc24bdc98eede5cd | 3,638,255 |
def mask_target(y_true, bbox_true, mask_true, mask_regress, proposal, assign = cls_assign, sampling_count = 256, positive_ratio = 0.25, mean = [0., 0., 0., 0.], std = [0.1, 0.1, 0.2, 0.2], method = "bilinear"):
"""
y_true = label #(padded_num_true, 1 or num_class)
bbox_true = [[x1, y1, x2, y2], ...] #(padde... | b161178716d890721a7f3cd0bfd61fdcc3efffb4 | 3,638,256 |
from rowgenerators.exceptions import DownloadError
def display_context(doc):
"""Create a Jinja context for display"""
# Make a naive dictionary conversion
context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != 'schema'}
mandatory_sections = ['documentation', 'contacts']
# Remo... | 53d455448b37a1236e640a66436525fa9369e575 | 3,638,257 |
import torch
def _get_triplet_mask(labels: torch.Tensor) -> torch.BoolTensor:
"""Return a 3D mask where mask[a, p, n] is True if the triplet (a, p, n) is valid.
A triplet (i, j, k) is valid if:
- i, j, k are distinct
- labels[i] == labels[j] and labels[i] != labels[k]
Args:
l... | 91e4e88507979bacde12c4c2dd9725b4d52e0e90 | 3,638,258 |
import re
def analyse_registration_output(output_string):
"""Parse the registration command output and return appropriate error"""
parse_error="ERROR:Unable to parse error message:" + output_string
success=0
fail=1
status_regex = re.compile("Status\s*:\s*(?P<status>[A-Z]+).*")
try:
s... | e6e90b9a55a8631bcb1c0963c943b08df82f03f4 | 3,638,259 |
import random
def randomrandrange(x, y=None):
"""Method randomRandrange.
return a randomly selected element from
range(start, stop). This is equivalent to
choice(range(start, stop)),
but doesnt actually build a range object.
"""
if isinstance(y, NoneType):
return random.randrange(... | 5c6304f20e6e1ddcfda931278defdc0c8867553f | 3,638,260 |
import os
def difficulties(prefix="data"):
""" Helper function that returns a list of template files. """
print("Loading difficulties ...")
difficulties = [ ]
os.path.walk(os.path.join(prefix, "templ_difficulties/"), processor, difficulties)
if (len(difficulties) == 0): die("FATAL: No difficulties to use!")
re... | e1c6744f4c101418972fc0fdf9dfc140c71d337e | 3,638,261 |
from typing import Callable
def int_domains(ecoords: np.ndarray, qpos: np.ndarray,
qweight: np.ndarray, dshpfnc: Callable):
"""
Returns the measure (length, area or volume in 1d, 2d and 3d) of
several domains.
"""
nE = ecoords.shape[0]
res = np.zeros(nE, dtype=ecoords.dtype)
... | 64ebe6dea6b86b4d391064b100a159c9641dcdde | 3,638,262 |
def pg_conn(postgresql):
"""Runs the sqitch plan and loads seed data before returning db connection.
"""
with postgresql:
# Loads data from blogdb fixture data
with postgresql.cursor() as cur:
cur.execute(
"""
create table users (
... | df3245eecad1c8f0fd1228ff8f3bf8a57701dfef | 3,638,263 |
def partial_with_hound_context(hound, func, *args, **kwargs):
"""
Retuns a partially bound function
Propagates the currently active hound reason (if any)
Useful for capturing the current contextual hound reason when queueing a background action
"""
if hound is not None:
reason = hound.ge... | e2547f3c59ac4168e0961db7216903c7fdca16af | 3,638,264 |
def rssfeed_edit(request, feed, ret_path):
""" Eigenschaften des RSS-Feeds aendern """
def save_values(feed, old, new):
""" geaenderte Werte des RSS-Feeds speichern """
has_changed = False
key = 'title'
if old[key] != new[key]:
feed.title = encode_html(new[key])
has_changed = True
k... | 0643c6ca976d448bf3faf5539e90e59ea7d06bd7 | 3,638,265 |
def disassemble_pretty(self, addr=None, insns=1,
arch=None, mode=None):
"""
Wrapper around disassemble to return disassembled instructions as string.
"""
ret = ""
disas = self.disassemble(addr, insns, arch, mode)
for i in disas:
ret += "0x%x:\t%s\t%s\n" % (i.addr... | 39bddf246b880decbc84015ef20c5664f88d917e | 3,638,266 |
def detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False):
"""
Performs the detection
"""
custom_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
custom_image = cv2.resize(custom_image, (lib.network_width(
net), lib.network_height(net)), interpolation=cv2.INTER_LINEAR)
... | 7209042478457e4219c9d600790b58d5b5d54e2f | 3,638,267 |
import torch
def overlay_boxes(image, predictions):
"""
Adds the predicted boxes on top of the image
Arguments:
image (np.ndarray): an image as returned by OpenCV
predictions (BoxList): the result of the computation by the model.
It should contain the field `labels`.
"""
... | 99905ae0206d285fa878b0063f227a9152600fad | 3,638,268 |
def convert_tilt_convention(iconfig, old_convention,
new_convention):
"""
convert the tilt angles from an old convention to a new convention
This should work for both configs with statuses and without
"""
if new_convention == old_convention:
return
def _get_... | a24126a20453cf7a7c42a74e71618643215ad5c9 | 3,638,269 |
def _type_of_plot(orientation, n_var, i, j):
"""internal helper function for determining plot type in a corner plot
Parameters
----------
orientation : str
the orientation
options: 'lower left', 'lower right', 'upper left', 'upper right'
i, j : int
the row, column index
... | 9629af21f1995ccd1b582d4f9a7b1ecf2c621c84 | 3,638,270 |
def t2_function(t, M_0, T2, p):
"""Calculate stretched or un-stretched (p=1) exponential T2 curve
.. math::
f(t) = M_{0} e^{(-2(t/T_{2})^{p}}
Args:
t (array): time series
M_{0} (float): see equation
T_{2} (float): T2 value
p (float): see equation
Returns:
... | be4dabf4436832ca3dde9289610070ad41a3632b | 3,638,271 |
def ry(phi):
"""Returns the rotational matrix for an angle phi around the y-axis
"""
if type(phi) == np.ndarray:
m11 = np.cos(phi)
m12 = np.full(len(phi), 0)
m13 = np.sin(phi)
m22 = np.full(len(phi), 1)
m1 = np.stack((m11, m12, m13), axis=0)
m2 = np.stack((m1... | 06a22e478a0912ac3aeba53ba5b565690b94e652 | 3,638,272 |
def hashed_embedding_lookup_sparse(params,
sparse_values,
dimension,
combiner="mean",
default_value=None,
name=None):
"""Looks up embeddings of... | e7b4e803d04336e1d0a88d4051473b895a422f08 | 3,638,273 |
def DelfFeaturePostProcessing(boxes, descriptors, use_pca, pca_parameters=None):
"""Extract DELF features from input image.
Args:
boxes: [N, 4] float array which denotes the selected receptive box. N is
the number of final feature points which pass through keypoint selection
and NMS steps.
... | dbd55fa19085179fae3f6695c3fb529666c4550d | 3,638,274 |
def render_field(field, **kwargs):
"""Render a field to a Bootstrap layout."""
renderer_cls = get_field_renderer(**kwargs)
return renderer_cls(field, **kwargs).render() | 35a5586991072ba4772df48f5b2b649b1c2d62fd | 3,638,275 |
def bisection(a, b, poly, tolerance):
"""
Assume that poly(a) <= 0 and poly(b) >= 0.
Modify a and b so that abs(b-a) < tolerance and poly(b) >= 0 and poly(a) <= 0.
Return (a+b)/2
:param a: poly(a) <= 0
:param b: poly(b) >= 0
:param poly: polynomial coefficients, low order first
:param to... | 9ff1961a95a63af587c9469dd2f987657f1661a9 | 3,638,276 |
def decrypt_message(key, message):
""" returns the decrypted message """
return translate_message(key, message, 'decrypt') | 74b590d493b21928880e43e5f8ae55acd8265bb2 | 3,638,277 |
def IOU(a_wh, b_wh):
"""
Intersection over Union
Args:
a_wh: (width, height) of box A
b_wh: (width, height) of box B
Returns float.
"""
aw, ah = a_wh
bw, bh = b_wh
I = min(aw, bw) * min(ah, bh)
area_a = aw * ah
area_b = bw * bh
U = area_a + area_b - I
... | 92580147eac219d77e6c8a38875c5ee809783790 | 3,638,278 |
import base64
def decode_image(img_b64):
"""Decode image from base64.
https://jdhao.github.io/2020/03/17/base64_opencv_pil_image_conversion/
"""
img_bytes = base64.b64decode(img_b64)
im_arr = np.frombuffer(img_bytes, dtype=np.uint8)
img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR)
img = ... | 22547d43fe1a20032ee095f3fe16d5550a4f08c8 | 3,638,279 |
from datetime import datetime
def date_from_string(date_str, format_str):
"""
returns a date object by a string
"""
return datetime.strptime(date_str, format_str).date() | 7ba2fa5652264c62e2a6711210a39613cf565e37 | 3,638,280 |
import re
def fix_sensor_name(name):
"""Cleanup sensor name, returns str."""
name = re.sub(r'^(\w+)-(\w+)-(\w+)', r'\1 (\2 \3)', name, re.IGNORECASE)
name = name.title()
name = name.replace('Acpi', 'ACPI')
name = name.replace('ACPItz', 'ACPI TZ')
name = name.replace('Coretemp', 'CoreTemp')
name = name.r... | 6a346ece5f03c60a2b5d23d5a66c52735aef2939 | 3,638,281 |
def get_relevant_coordinates():
"""Returns a numpy ndarray specifying the pixel a lidar ray hits when shot
through the near plane."""
coords_and_angles = np.genfromtxt('coords_and_angles.csv', delimiter=',')
return np.hsplit(coords_and_angles,2) | ad814528122777c99aab13652dfb708282993374 | 3,638,282 |
def _expand_host_port_user(lst):
"""
Input: list containing hostnames, (host, port)-tuples or (host, port, user)-tuples.
Output: list of (host, port, user)-tuples.
"""
def expand(v):
if isinstance(v, basestring):
return (v, None, None)
elif len(v) == 1:
return... | 82cfc80f916ef739fc50d8d79a5e19b4aa4a8fa6 | 3,638,283 |
def noise(line, wl=11):
""" Return the noise after smoothing. """
signal = smooth_and_trim(line, window_len=wl)
noise = np.sqrt((line - signal) ** 2)
return noise | 009f05d1eeabf4d0218d78b6c41ff4877f66a5f5 | 3,638,284 |
from typing import Optional
from typing import Iterator
from typing import Tuple
import itertools
import tqdm
import torch
def _evaluate(
limit_batches: Optional[int],
train_pipeline: TrainPipelineSparseDist,
iterator: Iterator[Batch],
next_iterator: Iterator[Batch],
stage: str,
) -> Tuple[float, ... | f0550b60c3d53192acb9ddd2d5057ade118fa79d | 3,638,285 |
import re
def check_pre_release(tag_name):
"""
Check the given tag to determine if it is a release tag, that is, whether it
is of the form rX.Y.Z. Tags that do not match (e.g., because they are
suffixed with someting like -beta# or -rc#) are considered pre-release tags.
Note that this assumes tha... | 8e24a0a61bfa6fe84e936f004b4228467d724616 | 3,638,286 |
def _get_target_connection_details(target_connection_string):
"""
Returns a tuple with the raw connection details for the target machine extracted from the connection string provided
in the application arguments. It is a specialized parser of that string.
:param target_connection_string: the connection... | 5e6ee870c0e196f54950f26ee6e551476688dce9 | 3,638,287 |
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Set up an Arlo IP sensor."""
arlo = hass.data.get(DATA_ARLO)
if not arlo:
return False
sensors = []
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type == 'total_cameras':
... | 875ddac74d1e1d8dd10136214f8487d750094e61 | 3,638,288 |
from .tfr import _compute_tfr
def tfr_array_multitaper(epoch_data, sfreq, freqs, n_cycles=7.0,
zero_mean=True, time_bandwidth=None, use_fft=True,
decim=1, output='complex', n_jobs=1,
verbose=None):
"""Compute Time-Frequency Representation ... | 28a6f998fdaa9acde77a521b5e0c5c51a4709887 | 3,638,289 |
import logging
def card(id: int):
"""
Show the selected card data (by id).
"""
for card in cards["cards"]:
if card["id"] == id:
logging.info("card")
return card
logging.info("card")
return "Card not found." | 8a26ea6add0d3ebe539b8a3c0c5dcbf0a458e923 | 3,638,290 |
def build_norm_layer(cfg, num_features, postfix=""):
""" Build normalization layer
Args:
cfg (dict): cfg should contain:
type (str): identify norm layer type.
layer args: args needed to instantiate a norm layer.
requires_grad (bool): [optional] whether stop gradient u... | ef57209bfbd9ead48585ef478a0c74d74127f42f | 3,638,291 |
from ostap.core.core import Ostap, ROOTCWD
from ostap.io.root_file import REOPEN
def _add_response_tree ( tree , *args ) :
"""Specific action to ROOT.TChain
"""
tdir = tree.GetDirectory()
with ROOTCWD () , REOPEN ( tdir ) as tfile :
tdir.cd()
... | 9ad52c4d6962ea3de8beaebc1616887c4c054dd1 | 3,638,292 |
def scalarProd(v,w):
""" A sum of 2 vectors in n-space.
Params: A 2 tuple point (V)
another 2 tuple point (W)
returns: Distance of (V,W)
"""
v = x[0] + x[1]
w = y[0] + y[1]
return np.array(v*w) | 604750efbef53dfb21468fcc7d4f41bd07af502d | 3,638,293 |
def sample_summary(df, extra_values=None, params=SummaryParams()):
"""
Returns table showing statistical summary from the sample parameters:
mean, std, mode, hpdi.
Parameters
------------
df : Panda's dataframe
Contains parameter sample values: each column is a parameter.
extra_v... | 0fcedfb54f7a72c3811f7cb4c5df559b4d313383 | 3,638,294 |
from .gnat import GNAT
def classFactory(iface): # pylint: disable=invalid-name
"""Load GNAT class from file GNAT.
:param iface: A QGIS interface instance.
:type iface: QgsInterface
"""
#
return GNAT(iface) | 54036f9fa18d901426d45771409a48ab803302ef | 3,638,295 |
from aiida.common.hashing import get_random_string
def get_quicksetup_password(ctx, param, value): # pylint: disable=unused-argument
"""Determine the password to be used as default for the Postgres connection in `verdi quicksetup`
If a value is explicitly passed, that value is returned. If there is no value... | 6ec0a8548bc632bdf008ba3e8e8b8d2bfdd5244b | 3,638,296 |
from typing import List
def convert(day_input: List[str]) -> List[List[str]]:
"""Breaks down the input into a list of directions for each tile"""
def dirs(line: str) -> List[str]:
dirs, last_c = [], ''
for c in line:
if c in ['e', 'w']:
dirs.append(last_c + c)
... | fd1d683e69dbff8411cecdaa184355f2311d3e8a | 3,638,297 |
import codecs
def read(filepath):
"""Read file content from provided filepath."""
with codecs.open(filepath, encoding='utf-8') as f:
return f.read() | bff53fbb9b1ebe85c6a1fa690d28d6b6bec71f84 | 3,638,298 |
def trend_indicator(trend, style):
"""Get the trend indicator and corresponding color."""
if trend == 0.00042 or np.isnan(trend):
return '?', (0, 0, 0, 0)
arrows = ('→', '↗', '↑', '↓', '↘')
trend = min(max(trend, -1), 1) # limit the trend
trend_color = (1, 0, 0, trend * trend) if (trend > ... | 009e95e45c3ba6f4e459f024c09511a7952053e4 | 3,638,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.