content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def map_cosh(process):
"""
"""
return map_default(process, 'cosh', 'apply') | fe853e23f8008bc5e767ef5af8b4efc6a04de407 | 24,500 |
def fs(func):
"""
This is the decorator which performs recursive AST substitution of
functions, and optional JIT-compilation using `numba`_.
This must only be used on functions with positional parameters
defined; this must not be used on functions with keyword parameters.
This decorator modifi... | 832a770e68501edb6df93c3fb7ef512be64f4e43 | 24,501 |
def cleanline(line):
"""去除讀入資料中的換行符與 ',' 結尾
"""
line = line.strip('\n')
line = line.strip(',')
return line | a4149663e2c3966c5d9be22f4aa009109e4a67ca | 24,502 |
from onnx.helper import make_node
import logging
def convert_contrib_box_nms(node, **kwargs):
"""Map MXNet's _contrib_box_nms operator to ONNX
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
input_dtypes = get_input_dtypes(node, kwargs)
dtype = input_dtypes[0]
#dtype_t = onnx.mapping.... | 22bc975bc35ebe8e50f4749f981859460f695596 | 24,503 |
def fill76(text):
"""Any text. Wraps the text to fit in 76 columns."""
return fill(text, 76) | 953ed87d8cfbee7a10c752082783469e866e8540 | 24,504 |
def current_object(cursor_offset, line):
"""If in attribute completion, the object on which attribute should be
looked up."""
match = current_word(cursor_offset, line)
if match is None:
return None
start, end, word = match
matches = current_object_re.finditer(word)
s = ""
for m i... | cba608811a2081b382a2c522bb9d0651569739dd | 24,505 |
import urllib3
import tqdm
import os
def download_zip(url: str) -> BytesIO:
"""Download data from url."""
logger.warning('start chromium download.\n'
'Download may take a few minutes.')
# disable warnings so that we don't need a cert.
# see https://urllib3.readthedocs.io/en/latest/... | 4b7ff38a529084633969ce95ea0c5bfca3fd7542 | 24,506 |
def _is_match(option, useful_options, find_perfect_match):
"""
returns True if 'option' is between the useful_options
"""
for useful_option in useful_options:
if len(option) == sum([1 for o in option if o in useful_option]):
if not find_perfect_match or len(set(useful_option)) == len... | bff60e1320744c16747926071afb3ee02022c55c | 24,507 |
def pass_aligned_filtering(left_read, right_read, counter):
"""
Test if the two reads pass the additional filters such as check for soft-clipped end next to the variant region,
or overlapping region between the two reads.
:param left_read: the left (or 5') most read
:param right_read: the right (or ... | 78849f12541510216407b7b40fb29a0befc920d7 | 24,508 |
from typing import OrderedDict
import os
def load_metaconfig(file_path):
""" Loads a single metaconfig file and returns variable to expression dictionary """
definitions = OrderedDict()
if os.path.isfile(file_path):
with open(file_path) as f:
for line in [l.strip(os.linesep).strip() fo... | 6222cf9b589ea4162c080008fd25c0df78607a07 | 24,509 |
def detect_slow_oscillation(data: Dataset, algo: str = 'AASM/Massimini2004', start_offset: float = None) -> pd.DataFrame:
"""
Detect slow waves (slow oscillations) locations in an edf file for each channel
:param edf_filepath: path of edf file to load. Will maybe work with other filetypes. untested.
:pa... | a241196b56b6fb426fc9949ee82fca40c0c854f2 | 24,510 |
def _map_channels_to_measurement_lists(snirf):
"""Returns a map of measurementList index to measurementList group name."""
prefix = "measurementList"
data_keys = snirf["nirs"]["data1"].keys()
mls = [k for k in data_keys if k.startswith(prefix)]
def _extract_channel_id(ml):
return int(ml[len... | d6d83c01baec5f345d58fff8a0d0107a40b8db37 | 24,511 |
def is_not_applicable_for_questionnaire(
value: QuestionGroup, responses: QuestionnaireResponses
) -> bool:
"""Returns true if the given group's questions are not answerable for the given responses.
That is, for all the questions in the given question group, only not
applicable answers have been provid... | a534ca5560193c81e18f4028bd032b4a8e5adf8a | 24,512 |
def _chebnodes(a,b,n):
"""Chebyshev nodes of rank n on interal [a,b]."""
if not a < b:
raise ValueError('Lower bound must be less than upper bound.')
return np.array([1/2*((a+b)+(b-a)*np.cos((2*k-1)*np.pi/(2*n))) for k in range(1,n+1)]) | 4378468aac0642f15b64dcdee75dcb970aab11f7 | 24,513 |
import sys
def delcolumn(particles, columns, metadata):
"""
With dataframes, stating dataframe1 = dataframe2 only creates
a reference. Therefore, we must create a copy if we want to leave
the original dataframe unmodified.
"""
nocolparticles = particles.copy()
#Loop through each ... | cff587aa460d0478f750a3323b66e20d9c52f85a | 24,514 |
def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | c7b689b9e6042aa84689003e2de6ffff2229eb69 | 24,515 |
def spawn_actor(world: carla.World, blueprint: carla.ActorBlueprint, spawn_point: carla.Transform,
attach_to: carla.Actor = None, attachment_type=carla.AttachmentType.Rigid) -> carla.Actor:
"""Tries to spawn an actor in a CARLA simulator.
:param world: a carla.World instance.
:param ... | 83d29b21e76f52f1928009e22cee6a635ef4d025 | 24,516 |
def partition(lst, size):
"""Partition list @lst into eveni-sized lists of size @size."""
return [lst[i::size] for i in range(size)] | af7071a5aac36a51f449f153df145d9218808a4a | 24,517 |
def form_errors_json(form=None):
"""It prints form errors as JSON."""
if form:
return mark_safe(dict(form.errors.items())) # noqa: S703, S308
return {} | d9748d5ce4578855775af24d1a758030ad3fa432 | 24,518 |
def get_semantic_ocs_version_from_config():
"""
Returning OCS semantic version from config.
Returns:
semantic_version.base.Version: Object of semantic version for OCS.
"""
return get_semantic_version(config.ENV_DATA["ocs_version"], True) | 346aa6aacff9a758cf06b4a3dc4977e98e9ca501 | 24,519 |
from typing import Optional
from typing import Mapping
import os
import logging
def train_rl(
*,
_run: sacred.run.Run,
_seed: int,
total_timesteps: int,
normalize: bool,
normalize_kwargs: dict,
reward_type: Optional[str],
reward_path: Optional[str],
rollout_save_final: bool,
ro... | fdc8c2203752038313cae79b077310b61db3b5c2 | 24,520 |
from typing import List
def get_non_ntile_cols(frame: pd.DataFrame) -> List[str]:
"""
:param frame: data frame to get columns of
:return: all columns in the frame that dont contain 'Ntile'
"""
return [col for col in frame.columns if 'Ntile' not in col] | 93970b576381aa668ce75d77f03793380445d9e4 | 24,521 |
from typing import Any
from typing import Optional
from datetime import datetime
def deserialize_date(value: Any) -> Optional[datetime.datetime]:
"""A flexible converter for str -> datetime.datetime"""
if value is None:
return None
if isinstance(value, datetime.datetime):
return value
... | 15cdd07ad4bd5873d8ed01d3eb9ce3b4e780ca44 | 24,522 |
def intersect(x1, x2, y1, y2, a1, a2, b1, b2):
""" Return True if (x1,x2,y1,y2) rectangles intersect. """
return overlap(x1, x2, a1, a2) & overlap(y1, y2, b1, b2) | 1e9c530b1d5e085df073b8c32d874ef457e2246a | 24,523 |
import functools
import sys
import logging
def BestEffort(func):
"""Decorator to log and dismiss exceptions if one if already being handled.
Note: This is largely a workaround for the lack of support of exception
chaining in Python 2.7, this decorator will no longer be needed in Python 3.
Typical usage woul... | dec08ab8fc1d367203df2e6c2f0507bf880ba503 | 24,524 |
from typing import List
def recording_to_chunks(fingerprints: np.ndarray,
samples_per_chunk: int) -> List[np.ndarray]:
"""Breaks fingerprints of a recording into fixed-length chunks."""
chunks = []
for pos in range(0, len(fingerprints), samples_per_chunk):
chunk = fingerpri... | eae1a3b882e545a8dc08f029ddb5113dcdf1bca4 | 24,525 |
def coset_enumeration_c(fp_grp, Y):
"""
>>> from sympy.combinatorics.free_group import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
>>> C = coset_enumeration_c(f, [x])
... | 0efeacfeeb2b20275378c58a3aacaed07ade57be | 24,526 |
def slr_pulse(
num=N, time_bw=TBW,
ptype=PULSE_TYPE, ftype=FILTER_TYPE,
d_1=PBR, d_2=SBR,
root_flip=ROOT_FLIP,
multi_band = MULTI_BAND,
n_bands = N_BANDS,
phs_type = PHS_TYPE,
band_sep = BAND_SEP
):
"""Use Shinnar-Le Roux algorithm to generate pulse"""
if root_flip is Fal... | 0986b6ea8adffd90c108308365ebf3172a6459d0 | 24,527 |
def policy_options(state, Q_omega, epsilon=0.1):
""" Epsilon-greedy policy used to select options """
if np.random.uniform() < epsilon:
return np.random.choice(range(Q_omega.shape[1]))
else:
return np.argmax(Q_omega[state]) | 66e36b81fdec06822ebb958611deca23bd64191b | 24,528 |
import tempfile
import time
def test_ps_s3_creation_triggers_on_master():
""" test object creation s3 notifications in using put/copy/post on master"""
if skip_push_tests:
return SkipTest("PubSub push tests don't run in teuthology")
hostname = get_ip()
proc = init_rabbitmq()
if proc is No... | bb0770cd80968d8878f0a3c379f5ce2da9863c8f | 24,529 |
import math
def weights_init(init_type='gaussian'):
"""
from https://github.com/naoto0804/pytorch-inpainting-with-partial-conv/blob/master/net.py
"""
def init_fun(m):
classname = m.__class__.__name__
if (classname.find('Conv') == 0 or classname.find(
'Linear') == 0) and... | d65dee3744daf59a2db832b5c4866bee2131b4d6 | 24,530 |
def title(default=None, level="header"):
"""
A decorator that add an optional title argument to component.
"""
def decorator(fn):
loc = get_argument_default(fn, "where", None) or st
@wraps(fn)
def wrapped(
*args,
title=default,
level=level,
... | c11a3ee7ccff5e6934fba857d438743464dd653e | 24,531 |
import os
def get_ext(path):
"""
Given a path return the file extension.
**Positional Arguments:**
path: The file whose path we assess
"""
return os.path.splitext(path)[1] | f088e63bde8924fc2bac50950e05384878f637b7 | 24,532 |
def _rect_to_css(rect):
"""
Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order
:param rect: a dlib 'rect' object
:return: a plain tuple representation of the rect in (top, right, bottom, left) order
"""
return rect.top(), rect.right(), rect.bottom(), rect.left... | e3439cc0eb30186b8fc905f518ff21883175b3e2 | 24,533 |
def client():
"""Client Fixture."""
client_obj = Client(base_url=BASE_URL)
return client_obj | bac2ccd038eb587b4dd67ce0cc63bef63af9c365 | 24,534 |
def encode_one_hot(s):
"""One-hot encode all characters of the given string.
"""
all = []
for c in s:
x = np.zeros((INPUT_VOCAB_SIZE))
index = char_indices[c]
x[index] = 1
all.append(x)
return all | e4bc2b02cea4dbf74346cbd672cb58246abe4edc | 24,535 |
from datetime import datetime
def date_to_datetime(date, time_choice='min'):
"""
Convert date to datetime.
:param date: date to convert
:param time_choice: max or min
:return: datetime
"""
choice = getattr(datetime.datetime, 'min' if time_choice == 'min' else 'max').time()
return time... | 9e429bf71288ffc3bd56b682f2e24fceb0ff49d4 | 24,536 |
def standardize_cell(atoms, cell_type):
""" Standardize the cell of the atomic structure.
Parameters:
atoms: `ase.Atoms`
Atomic structure.
cell_type: { 'standard', 'standard_no_symmetries', 'primitive', None}
Starting from the input cell, creates a standard cell according to same stan... | 4005cf7afd6f4992f3cc271608f0b8c84649d6b1 | 24,537 |
def get_biggan_stats():
""" precomputed biggan statistics """
center_of_mass = [137 / 255., 127 / 255.]
object_size = [213 / 255., 210 / 255.]
return center_of_mass, object_size | 6576e13b7a68369e90b2003171d946453bafd212 | 24,538 |
def get_input_var_value(soup, var_id):
"""Get the value from text input variables.
Use when you see this HTML format:
<input id="wired_config_var" ... value="value">
Args:
soup (soup): soup pagetext that will be searched.
var_id (string): The id of a var, used to find its value.
R... | 5a9dd65a285c62e0e5e79584858634cb7b0ece75 | 24,539 |
import os
def _create_file(path):
"""Opens file in write mode. It also creates intermediate directories if
necessary.
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
return open(path, 'w') | 448e26c24c48bf654402a9fe35ef28eb7906dd31 | 24,540 |
from typing import List
from typing import Any
import logging
def get_top(metric: str, limit: int) -> List[List[Any]]:
"""Get top stocks based on metric from sentimentinvestor [Source: sentimentinvestor]
Parameters
----------
metric : str
Metric to get top tickers for
limit : int
... | c203fcbe24ccf3d0c2253961d36ec7b556c8651c | 24,541 |
def test_add_single_entities(
reference_data: np.ndarray,
upper_bound: np.ndarray,
lower_bound: np.ndarray,
ishan: Entity,
) -> None:
"""Test the addition of SEPTs"""
tensor1 = SEPT(
child=reference_data, entity=ishan, max_vals=upper_bound, min_vals=lower_bound
)
tensor2 = SEPT(
... | 48531867a74d7267ae65d4350e82d26cae8bef44 | 24,542 |
def prob_get_expected_after_certain_turn(turns_later: int, turns_remain: int,
tiles_expect: int) -> float:
"""The probability of get expected tile after `turns_later` set of turns.
:param turns_later: Get the expected tile after `turns_after` set of turns
:param tur... | 6575c22302b73b58b2bd9aad5068ffe723fb5fe3 | 24,543 |
def get_gpcr_calpha_distances(pdb, xtc, gpcr_name, res_dbnum,
first_frame=0, last_frame=-1, step=1):
"""
Load distances between all selected atoms.
Parameters
----------
pdb : str
File name for the reference file (PDB or GRO format).
xtc : str
File ... | 3465246d610510f2976813fcc69c394e98452292 | 24,544 |
def main(yumrepomap=None,
**kwargs):
"""
Checks the distribution version and installs yum repo definition files
that are specific to that distribution.
:param yumrepomap: list of dicts, each dict contains two or three keys.
'url': the url to the yum repo definition file
... | 1caed81f53cd0dc2e1963aa1b53bc48c1ef71dd3 | 24,545 |
def zero_pad1d(inputs, padding=0):
"""Zero padding for 1d tensor
Args:
-----------------------------
inputs : tvm.te.tensor.Tensor
shape [batch, channel, length]
padding: (optional:0) int or tuple
-----------------------------
Returns:
-----------------------------
tvm.te.t... | 8135ffd8447d5fbc84988953a2bfca14b51d3f83 | 24,546 |
import torch
import math
def gelu(x):
"""gelu activation function copied from pytorch-pretrained-BERT."""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) | 35c0f45f904b2381acc95f5a2b4f28cec9fa924b | 24,547 |
import requests
def stock_fund_stock_holder(stock: str = "600004") -> pd.DataFrame:
"""
新浪财经-股本股东-基金持股
https://vip.stock.finance.sina.com.cn/corp/go.php/vCI_FundStockHolder/stockid/600004.phtml
:param stock: 股票代码
:type stock: str
:return: 新浪财经-股本股东-基金持股
:rtype: pandas.DataFrame
"""
... | acde3d06b9fabd9a22223401b6b9b947a1e248ff | 24,548 |
def set_to_available(request, slug, version):
"""
Updates the video status.
Sets the version already encoded to available.
"""
video = get_object_or_404(Video, slug=slug)
status, created = VideoStatus.objects.get_or_create(video_slug=slug)
if version == 'web':
status.web_availa... | ead832327d733b82b0d1bc38efd241baab039ed2 | 24,549 |
import pathlib
import json
import requests
import sys
def run_test(test):
""" Make the request """
print(bcolors.HEADER + "Running test: "+ test + bcolors.ENDC)
results = dict()
with open(pathlib.Path(test,"test.ini"), "r") as testini:
testini_json = json.loads(testini.read())
if "IGN... | 6a5af4a5c2e964dc97f2875c60187827a4431537 | 24,550 |
def generate_solve_c():
"""Generate C source string for the recursive solve() function."""
piece_letters = 'filnptuvwxyz'
stack = []
lines = []
add = lines.append
add('#define X_PIECE_NUM {}'.format(piece_letters.index('x')))
add("""
void solve(char* board, int pos, unsigned int used) {
... | dde70d4cdbeb8b691c1ffcb61ba524b2c1df9b2c | 24,551 |
def get_permission_info(room):
"""
Fetches permissions about the room, like ban info etc.
# Return Value
dict of session_id to current permissions,
a dict containing the name of the permission mapped to a boolean value.
"""
return jsonify({k: addExtraPermInfo(v) for k, v in room.permission... | aab7aa691e1e34e1bf20e3de744f8d4352a2421e | 24,552 |
def ravel(m):
"""ravel(m) returns a 1d array corresponding to all the elements of it's
argument.
"""
return reshape(m, (-1,)) | 728204f77737750783fef9818c102522f17c472e | 24,553 |
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
# My additions
print ("Printing this unstripped text:", line)
index.append(int(line.strip()))
return index | a76c4e94c593a234fd858d369f0133a5170ec8bf | 24,554 |
import click
import socket
def init():
"""Top level command handler."""
@click.command()
@click.option('--port', type=int, help='Port to listen.', default=0)
@click.option('--tun-dev', type=str, required=True,
help='Device to use when establishing tunnels.')
@click.option('--tun... | ba660e7f6698457951e766ce402857a6a5e4bc86 | 24,555 |
def check_collision(bird_rect:object, pipes:list, collide_sound:object):
""" Checks for collision with the Pipe and the Base """
for pipe in pipes:
if bird_rect.colliderect(pipe):
collide_sound.play()
return False
if bird_rect.bottom >= gv.BASE_TOP:
return False
r... | 080c8a6142397e3c1b91b0e3a4dfbd3ed7f1acde | 24,556 |
def compute_ranking_scores(ranking_scores,
global_ranks_to_save,
rank_per_query):
""" Compute ranking scores (MRR and MAP) and a bunch of interesting ranks to save to file from a list of ranks.
Args:
ranking_scores: Ranking scores previously compute... | a25a664b67e35ff9b35327b364e84eaf9ae37aaa | 24,557 |
def AirAbsorptionRelaxationFrequencies(T,p,H,T0, p_r):
"""
Calculates the relaxation frequencies for air absorption conforming to
ISO 9613-1. Called by :any:`AirAbsorptionCoefficient`.
Parameters
----------
T : float
Temperature in K.
p : float
Pressure in Pa.
H : float
... | c8c047ed4d9a7fc62b2cdb6d19f0d3c8b1b4c570 | 24,558 |
def table_from_bool(ind1, ind2):
"""
Given two boolean arrays, return the 2x2 contingency table
ind1, ind2 : array-like
Arrays of the same length
"""
return [
sum(ind1 & ind2),
sum(ind1 & ~ind2),
sum(~ind1 & ind2),
sum(~ind1 & ~ind2),
... | 497ce6ad1810386fedb6ada9ba87f0a5baa6318a | 24,559 |
def preprocess_skills(month_kpi_skills: pd.DataFrame, quarter_kpi_skills: pd.DataFrame) -> pd.DataFrame:
"""
Функция принимает на вход два DataFrame:
- с данными по KPI сотрудников ВЭД за последний месяц
- с данными по KPI сотрудников ВЭД за последний квартал
Возвращает объединенный DataFrame по дву... | 6bcbc1b93c99acbef04bf0962678c35a3abd3faa | 24,560 |
def bias_col_spline(im, overscan, dymin=5, dymax=2, statistic=np.mean, **kwargs):
"""Compute the offset by fitting a spline to the mean of each row in the
serial overscan region.
Args:
im: A masked (lsst.afw.image.imageLib.MaskedImageF) or unmasked
(lsst.afw.image.imageLib.ImageF) afw i... | d157275dd8337b81c9f4c67efe1c033512f963d3 | 24,561 |
def read_config():
""" Returns the decoded config data in 'db_config.json'
Will return the decoded config file if 'db_config.json' exists and is a valid JSON format.
Otherwise, it will return a False.
"""
# Check if file exists
if not os.path.isfile('db_config.json'):
return False
#... | 36b0ccdbd653b654663c7a3c6cf47cb3f68bc399 | 24,562 |
import pandas
def get_sub_title_from_series(ser: pandas.Series, decimals: int = 3) -> str:
"""pandas.Seriesから、平均値、標準偏差、データ数が記載されたSubTitleを生成する。"""
mean = round(ser.mean(), decimals)
std = round(ser.std(), decimals)
sub_title = f"μ={mean}, α={std}, N={len(ser)}"
return sub_title | 45c227e7ddd203872f015e4a95532c8acb80d54f | 24,563 |
import numpy
def atand2(delta_y: ArrayLike, delta_x: ArrayLike) -> ArrayLike:
"""Return the arctan2 of an angle specified in degrees.
Returns
-------
float
An angle, in degrees.
"""
return numpy.degrees(numpy.arctan2(delta_y, delta_x)) | 14d825d9886a2a62e36748eb9660ee27e6ba6827 | 24,564 |
from typing import Union
def adjust_doy_calendar(
source: xr.DataArray, target: Union[xr.DataArray, xr.Dataset]
) -> xr.DataArray:
"""Interpolate from one set of dayofyear range to another calendar.
Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1
... | d55da217c6b6e3b2947e992611da4e1fdacf7f5f | 24,565 |
def iou(box_a, box_b):
"""Calculates intersection area / union area for two bounding boxes."""
assert area(box_a) > 0
assert area(box_b) > 0
intersect = np.array(
[[max(box_a[0][0], box_b[0][0]),
max(box_a[0][1], box_b[0][1])],
[min(box_a[1][0], box_b[1][0]),
min(box_a[1][1], box_b[... | 9722673c7cc5b636d698453224cf3f06d1aa3678 | 24,566 |
def poll():
"""
The send buffer is flushed and any outstanding CA background activity is processed.
.. note:: same as pend_event(1e-12)
"""
status = libca.ca_pend_event(1e-12)
return ECA(status) | 96052229179a0188a3bb63a6e3ab35aa3d6cc5f7 | 24,567 |
def TopLevelWindow_GetDefaultSize(*args):
"""TopLevelWindow_GetDefaultSize() -> Size"""
return _windows_.TopLevelWindow_GetDefaultSize(*args) | e9a04052461bf64b7b3e4962a7df052e1f63de4b | 24,568 |
def human_size(numbytes):
"""converts a number of bytes into a readable string by humans"""
KB = 1024
MB = 1024*KB
GB = 1024*MB
TB = 1024*GB
if numbytes >= TB:
amount = numbytes / TB
unit = "TiB"
elif numbytes >= GB:
amount = numbytes / GB
unit = "GiB"
el... | 733fdff47350072b9cfcaf72a2de85f8a1d58cc6 | 24,569 |
import argparse
import time
def parse_args():
"""
Parse command-line arguments to train and evaluate a multimodal network for activity recognition on MM-Fit.
:return: Populated namespace.
"""
parser = argparse.ArgumentParser(description='MM-Fit Demo')
parser.add_argument('--data', type=str, de... | 6be79c2b83a294dc9f34da4acdbd6c8b0e568a8b | 24,570 |
from typing import Callable
from typing import Any
def node_definitions(
id_fetcher: Callable[[str, GraphQLResolveInfo], Any],
type_resolver: GraphQLTypeResolver = None,
) -> GraphQLNodeDefinitions:
"""
Given a function to map from an ID to an underlying object, and a function
to map from an under... | 4e041edacbd7e5d6c82dd7df8616a694aa00181a | 24,571 |
def get_image_from_request(request):
"""
This function is used to extract the image from a POST or GET request.
Usually it is a url of the image and, in case of the POST is possible
to send it as a multi-part data.
Returns a tuple with (ok:boolean, error:string, image:ndarray)
"""
if reques... | 0af18d65664e1c7dc264ac112b42e001ac293fd6 | 24,572 |
def con_external():
"""Define a connection fixture.
Returns
-------
ibis.omniscidb.OmniSciDBClient
"""
omnisci_client = ibis.omniscidb.connect(
user=EXT_OMNISCIDB_USER,
password=EXT_OMNISCIDB_PASSWORD,
host=EXT_OMNISCIDB_HOST,
port=EXT_OMNISCIDB_PORT,
data... | e5a57ebdf8640bd96a2e28678fe4d0b285fe8408 | 24,573 |
def parse_risk(data_byte_d):
"""Parse and arrange risk lists.
Parameters
----------
data_byte_d : object
Decoded StringIO object.
Returns
-------
neocc_lst : *pandas.Series* or *pandas.DataFrame*
Data frame with risk list data parsed.
"""
# Read data as csv
neoc... | cf8761e46df621ffcf69dba9e2c359c25da02234 | 24,574 |
def plot_step_w_variable_station_filters(df, df_stations=None, options=None):
"""
"""
p = PlotStepWithControls(df, df_stations, options)
return p.plot() | a1faa31c90f4c00103148aa50648f040849984b1 | 24,575 |
def pick_random_element(count):
"""
Parameters
----------
count: {string: int}
A dictionary of all transition
counts from some state
we're in to all other states
Returns
-------
The next character, randomly sampled
from the empirical probabilities
determined f... | 90388526b0a3a663f4f8d2ef6530484ddcf6fde2 | 24,576 |
def do_flake8() -> str:
"""
Flake8 Checks
"""
command = "flake8"
check_command_exists(command)
command_text = f"flake8 --config {settings.CONFIG_FOLDER}/.flake8"
command_text = prepinform_simple(command_text)
execute(*(command_text.split(" ")))
return "flake 8 succeeded" | 1ffaf0ecfd5905f68a9136c597f56c6c86b8d5cb | 24,577 |
def counter_current_heat_exchange(s0_in, s1_in, s0_out, s1_out,
dT, T_lim0=None, T_lim1=None,
phase0=None, phase1=None,
H_lim0=None, H_lim1=None):
"""
Allow outlet streams to exchange heat until either the give... | e5654666a56ebd0e32fd3abcde472e138a510d6e | 24,578 |
def ReadCOSx1dsumSpectrum(filename):
"""
filename with full path
Purporse is to have other variation
of files and differnet way of reading in.
"""
wave,flux,dfp,dfm = np.loadtxt(filename,unpack=True,usecols=[0,1,4,5])
return np.array([wave,flux,dfp,dfm]) | a74a76a787ba3f0665c8f73d602e5259fa4828ac | 24,579 |
import argparse
def parse_args():
"""Use argparse to get command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument('--task', '-t', choices=['seg', 'det', 'drivable',
'det-tracking'])
parser.add_argument('--gt', '-g', help='path to ground truth')
pars... | f2478bb73f5f255d832a25800b6fddfbfd9ec734 | 24,580 |
import cmath
import math
def op_atanh(x):
"""Returns the inverse hyperbolic tangent of this mathematical object."""
if isinstance(x, list):
return [op_atanh(a) for a in x]
elif isinstance(x, complex):
return cmath.atanh(x)
else:
return math.atanh(x) | 515da3d653f9ab4df6d87f5cec7d021ac2c98da9 | 24,581 |
from typing import Mapping
from typing import Any
from typing import Callable
import warnings
def find_intersections(
solutions: Mapping[Any, Callable],
ray_direction: Array,
target_center: Array,
) -> dict:
"""
find intersections between ray_direction and target_center given a mapping
of func... | a738fd0521a853c0be52bbf26d63ef515208b37a | 24,582 |
def Circum_O_R(vertex_pos, tol):
"""
Function finds the center and the radius of the circumsphere of the every tetrahedron.
Reference:
Fiedler, Miroslav. Matrices and graphs in geometry. No. 139. Cambridge University Press, 2011.
Parameters
-----------------
vertex_pos :
The positio... | 800ee6e56088a1c4df7149e911d4acbc175e2771 | 24,583 |
def reverse_one_hot(image):
"""
Transform a 2D array in one-hot format (depth is num_classes),
to a 2D array with only 1 channel, where each pixel value is
the classified class key.
#Arguments
image: The one-hot format image
#Returns
A 2D array with the same width and height a... | 912d4a5f9fbb3711b1af9dcd9c2092e6d71869bd | 24,584 |
import torch
def get_feature_clusters(x: torch.Tensor, output_size: int, clusters: int = 8):
""" Applies KMeans across feature maps of an input activations tensor """
if not isinstance(x, torch.Tensor):
raise NotImplementedError(f"Function supports torch input tensors only, but got ({type(x)})")
... | a43c2b98239f7474bf70747f464e29f4800159d8 | 24,585 |
def get_phone_operator(phonenumber):
"""
Get operator type for a given phonenumber.
>>> get_phone_operator('+959262624625')
<Operator.Mpt: 'MPT'>
>>> get_phone_operator('09970000234')
<Operator.Ooredoo: 'Ooredoo'>
>>> get_phone_operator('123456789')
<Operator.Unknown: 'Unknown'>
"""... | 01ec72a935b6fec466ab3113a61959d316d8f4b4 | 24,586 |
def projectpoints(P, X):
""" Apply full projection matrix P to 3D points X in cartesian coordinates.
Args:
P: projection matrix
X: 3d points in cartesian coordinates
Returns:
x: 2d points in cartesian coordinates
"""
X_hom = cart2hom(X)
X_pro = P.dot(X_hom) # 像素坐标系 齐次三维坐标
x = hom2cart(X_... | a16df6083a567215b474ec29d2b065c8a200c22c | 24,587 |
import os
def getDMI():
"""
Read hardware information from DMI.
This function attempts to read from known files in /sys/class/dmi/id/. If
any are missing or an error occurs, those fields will be omitted from the
result.
Returns: a dictionary with fields such as bios_version and product_seri... | bd82c18f82a7ecf2681c5c769bee81e9127eeaef | 24,588 |
def mdot(a,b):
"""
Computes a contraction of two tensors/vectors. Assumes
the following structure: tensor[m,n,i,j,k] OR vector[m,i,j,k],
where i,j,k are spatial indices and m,n are variable indices.
"""
if (a.ndim == 3 and b.ndim == 3) or (a.ndim == 4 and b.ndim == 4):
c = (a*b).sum... | 36b8242bf8c643ff35362c4d19f3a222297a1eee | 24,589 |
def sample_duration(sample):
"""Returns the duration of the sample (in seconds)
:param sample:
:return: number
"""
return sample.duration | 9aaddb69b106ad941e3d1172c8e789b4969da99d | 24,590 |
def fetch_commons_memberships(from_date=np.NaN,
to_date=np.NaN,
on_date=np.NaN):
"""Fetch Commons memberships for all MPs.
fetch_commons_memberships fetches data from the data platform showing
Commons memberships for each MP. The memberships are ... | 0c9f72f9b2b1bdc090597a69a598ef638383fcf1 | 24,591 |
import win32com.client as win32
def excel_col_w_fitting(excel_path, sheet_name_list):
"""
This function make all column widths of an Excel file auto-fit with the column content.
:param excel_path: The Excel file's path.
:param sheet_name_list: The sheet names of the Excel file.
:return: File's col... | 57de5aa63317d4fae4c1f60b607082b8de1f5f91 | 24,592 |
import os
def load_meetings(root=public_meetings.data_root,
ext=public_meetings.file_ext):
"""
Load all meetings from `root` ending with `ext`
Args:
root(str): root meeting directory
ext(str): file extension
Returns:
meetings(dict): a... | 098def3266d699ac9b5ddfcb5b655bafe2c711d6 | 24,593 |
def padding_reflect(image, pad_size):
"""
Padding with reflection to image by boarder
Parameters
----------
image: NDArray
Image to padding. Only support 2D(gray) or 3D(color)
pad_size: tuple
Padding size for height adn width axis respectively
Returns
-------
ret: N... | eb9f00bee89cb9a13fef0aa77e2c3eb0bfc8c92c | 24,594 |
def check_if_all_elements_have_geometry(geodataframes_list):
"""
Iterates over a list and checks if all members of the list have geometry
information associated with them.
Parameters
----------
geodataframes_list : A list object
A list object that contains one or more geopandas.GeoDataF... | 4ca7bcdd405c407a0a15be81876627e88a0d9c80 | 24,595 |
def conference_schedule(parser, token):
"""
{% conference_schedule conference schedule as var %}
"""
contents = token.split_contents()
tag_name = contents[0]
try:
conference = contents[1]
schedule = contents[2]
var_name = contents[4]
except IndexError:
raise t... | 037e000488a204a9d0094ccda72067ed70e5aa53 | 24,596 |
from typing import Tuple
import http
def run_delete_process() -> Tuple[str, http.HTTPStatus]:
"""Handles deleting tasks pushed from Task Queue."""
return _run_process(constants.Operation.DELETE) | 94a8c459ed67695894c28973f4a04faa2f2782aa | 24,597 |
def annotate(f, expr, ctxt):
"""
f: function argument
expr: expression
ctxt: context
:returns: type of expr
"""
t = f(expr, ctxt)
expr.type = t
return t | d8fb524f6ca2fbddef78aa150733e768d0e3da01 | 24,598 |
def _clip_boxes(boxes, im_shape):
"""Clip boxes to image boundaries."""
# x1 >= 0
boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0)
# y1 >= 0
boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0)
# x2 < im_shape[1]
boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1)
# y2 < im_shape[0]
... | 6b0e412f4aa8d4204530ebeca8a45928213847aa | 24,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.