content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dcm_to_unrescaled(dcm_dict, save_path=None, show=True, return_resolution=False):
"""
just stack dcm files together
:param return_resolution:
:param show:
:param dcm_dict:
:param save_path: the save path for stacked array
:return: the stacked array in float32
"""
array_stacked, re... | b4954c4f89100093b501d6e662a8b03eb247039b | 29,469 |
def change_unit_of_metrics(metrics):
"""Change order of metrics from bpd to nats for binarized mnist only"""
if hparams.data.dataset_source == 'binarized_mnist':
# Convert from bpd to nats for comparison
metrics['kl_div'] = metrics['kl_div'] * jnp.log(2.) * get_effective_n_pixels()
metri... | 0435a4caf8c82587f84fb05ae493e43654bdf22e | 29,471 |
def step(ram: dict, regs: dict, inputs: list[int]) -> tuple:
"""Advance robot by a single step
:param ram: memory contents
:param regs: register map
:param inputs: input queue
:return: updated pc; new color and turn direction
"""
pc = regs['pc']
relative_base = regs['rb']
output_val... | 4df0395e88a5ccd9f34edd39ea0841d16df6838a | 29,473 |
def replace_start(text,
pattern,
repl,
ignore_case=False,
escape=True):
"""Like :func:`replace` except it only replaces `text` with `repl` if
`pattern` mathces the start of `text`.
Args:
text (str): String to replace.
p... | 2296503a1c97cc06fa1fcc3768f54595fbc09940 | 29,474 |
import copy
def copy_excel_cell_range(
src_ws: openpyxl.worksheet.worksheet.Worksheet,
min_row: int = None,
max_row: int = None,
min_col: int = None,
max_col: int = None,
tgt_ws: openpyxl.worksheet.worksheet.Worksheet = None,
tgt_min_row: int = 1,
tgt_mi... | b98d2dda9fa0915dcb7bc3f4b1ff1049340afc68 | 29,476 |
def index(request):
"""Home page"""
return render(request, 'index.html') | 66494cd74d1b0969465c6f90c2456b4283e7e2d3 | 29,477 |
import ast
def get_teams_selected(request, lottery_info):
""" get_teams_selected updates the teams
selected by the user
@param request (flask.request object): Object containing
args attributes
@param lottery_info (dict): Dictionary keyed by
reverse standings order, with dictionary
... | 35edfab322ce5ad039f869027552c664f9e6b576 | 29,478 |
from testtools import TestCase
def assert_fails_with(d, *exc_types, **kwargs):
"""Assert that ``d`` will fail with one of ``exc_types``.
The normal way to use this is to return the result of
``assert_fails_with`` from your unit test.
Equivalent to Twisted's ``assertFailure``.
:param Deferred d:... | 1ff967f66c6d8e1d7f34354459d169bdfe95987a | 29,479 |
def temporal_affine_backward(dout, cache):
"""
Backward pass for temporal affine layer.
Input:
- dout: Upstream gradients of shape (N, T, M)
- cache: Values from forward pass
Returns a tuple of:
- dx: Gradient of input, of shape (N, T, D)
- dw: Gradient of weights, of shape (D, M)
... | 2cf4ead02fdaa0a54f828d09166128f1b5473d0b | 29,480 |
def _make_cmake(config_info):
"""This function initializes a CMake builder for building the project."""
configure_args = ["-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]
cmake_args = {}
options, option_fns = _make_all_options()
def _add_value(value, key):
args_key, args_value = _EX_ARG_FNS[key](valu... | fdef36f0875438ed0b5544367b4cb3fb5308f43d | 29,481 |
def box_to_delta(box, anchor):
"""((x1,y1) = upper left corner, (x2, y2) = lower right corner):
* box center point, width, height = (x, y, w, h)
* anchor center point, width, height = (x_a, y_a, w_a, h_a)
* anchor = (x1=x_a-w_a/2, y1=y_a-h_a/2, x2=x_a+w_a/2, y2=y_a+h_a/2)
... | 2033c66c89a25541af77678ab368d6f30628d0f5 | 29,482 |
def mutual_information(prob1, prob2, prob_joint):
"""
Calculates mutual information between two random variables
Arguments
------------------
prob1 (numpy array):
The probability distribution of the first variable
prob1.sum() should be 1
prob2 (numpy array):
The probability distrubi... | 4d6d2738c84092470b83497e911e767b18878857 | 29,483 |
def hog(img, num_bins, edge_num_cells=2):
""" Histogram of oriented gradients
:param img: image to process
:param edge_num_cells: cut img into cells: 2 = 2x2, 3 = 3x3 etc.
:return:
"""
if edge_num_cells != 2:
raise NotImplementedError
w, h = img.shape[:2]
cut_x = w /... | d2b7eadda978896826800c7159a8e4604b150aa6 | 29,484 |
def get_graph(adj) -> nx.classes.graph.Graph:
"""
Returns a nx graph from zero-padded adjacency matrix.
@param adj: adjustency matrix
[[0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 1. 1. 0. 0. 0. 0. ... | a62f1c696111e7c4f97bb6fd858fc3bc9e011f6f | 29,485 |
def findSamplesInRage(pointIds, minVal, maxVal):
"""根据样本编号的范围[1, 10]处理ID
Args:
pointIds (ndarray): 样本的ID
minVal (Number): 样本范围的起始位置
maxVal (Number): 样本范围的结束位置
Returns:
result (ndarray): 样本的ID
"""
digits = pointIds % 100
result = (digits >= minVal) & (digits <= m... | d2f040480c6513e9b845aaaa13485ecbe3376c41 | 29,489 |
def test_results_form_average(fill_market_trade_databases):
"""Tests averages are calculated correctly by ResultsForm, compared to a direct calculation
"""
Mediator.get_volatile_cache().clear_cache()
market_df, trade_df, order_df = get_sample_data()
trade_df, _ = MetricSlippage().calculate_metric(... | 92cb07fe56f026f0b1449e07e635db50581cffa9 | 29,490 |
from operator import mod
def _prot_builder_from_seq(sequence):
"""
Build a protein from a template.
Adapted from fragbuilder
"""
names = []
bonds_mol = []
pept_coords, pept_at, bonds, _, _, offset = templates_aa[sequence[0]]
names.extend(pept_at)
bonds_mol.extend(bonds)
offsets... | da182a0dd323db2e3930a72c0080499ed643be1a | 29,491 |
def connect_thread():
"""
Starts a SlaveService on a thread and connects to it. Useful for testing
purposes. See :func:`rpyc.utils.factory.connect_thread`
:returns: an RPyC connection exposing ``SlaveService``
"""
return factory.connect_thread(SlaveService, remote_service = SlaveService) | 557dfbd7a5389345f7becdc550f4140d74cf6695 | 29,492 |
from typing import Tuple
def yxyx_to_albu(yxyx: np.ndarray,
img_size: Tuple[PosInt, PosInt]) -> np.ndarray:
"""Unnormalized [ymin, xmin, ymax, xmax] to Albumentations format i.e.
normalized [ymin, xmin, ymax, xmax].
"""
h, w = img_size
ymin, xmin, ymax, xmax = yxyx.T
ymin, yma... | d6429ca3c694e5f2fd69dba645e3d97cab4720f8 | 29,493 |
def parse_tags(source):
"""
extract any substring enclosed in parenthesis
source should be a string
normally would use something like json for this
but I would like to make it easy to specify these tags and their groups
manually (via text box or command line argument)
http://stackoverf... | 315ea121cec56a38edc16bfa9e6a7ccaeeab1dc2 | 29,494 |
def NonZeroMin(data):
"""Returns the smallest non-zero value in an array.
Parameters
----------
data : array-like
A list, tuple or array of numbers.
Returns
-------
An integer or real value, depending on data's dtype.
"""
# 1) Convert lists and tuples into arrays
if ty... | 89d466c9d739dc511cd37fd71283ae8c6b2cc388 | 29,495 |
def get_99_pct_params_ln(x1: float, x2: float):
"""Wrapper assuming you want the 0.5%-99.5% inter-quantile range.
:param x1: the lower value such that pr(X > x1) = 0.005
:param x2: the higher value such that pr(X < x2) = 0.995
"""
return get_lognormal_params_from_qs(x1, x2, 0.005, 0.995) | 2ce424a289ea8a5af087ca5120b3d8763d1e2f31 | 29,496 |
def summarize_data(data):
"""
"""
#subset desired columns
data = data[['scenario', 'strategy', 'confidence', 'decile', 'cost_user']]
#get the median value
data = data.groupby(['scenario', 'strategy', 'confidence', 'decile'])['cost_user'].median().reset_index()
data.columns = ['Scenario', ... | 9964d99ed70a1405f1c94553172fd6830371472a | 29,497 |
def gen_cam(image, mask):
"""
生成CAM图
:param image: [H,W,C],原始图像
:param mask: [H,W],范围0~1
:return: tuple(cam,heatmap)
"""
# mask转为heatmap
heatmap = cv2.applyColorMap(np.uint8(255 * mask), cv2.COLORMAP_JET)
# heatmap = np.float32(heatmap) / 255
heatmap = heatmap[..., ::-1] # gbr t... | a9d221b6d536aef6c2e2093bb20614cf682de704 | 29,498 |
def get_username(strategy, details, backend, user=None, *args, **kwargs):
"""Resolve valid username for use in new account"""
if user:
return None
settings = strategy.request.settings
username = perpare_username(details.get("username", ""))
full_name = perpare_username(details.get("full_na... | 728a0aadf9aa58369fcf791d8cccb0d9214a4583 | 29,501 |
def not_at_max_message_length():
""" Indicates if we have room left in message """
global message
return message.count(SPACE) < WORD_LIMIT | 0bd7d758c80ed272de0571b4f651fe6a24c39b58 | 29,502 |
import math
def _fill_arc_trigonometry_array():
"""
Utility function to fill the trigonometry array used by some arc* functions (arcsin, arccos, ...)
Returns
-------
The array filled with useful angle measures
"""
arc_trig_array = [
-1,
math.pi / 4, # -45°
math.pi ... | 6b5c39dbacf028d84a397e2911f9c9b7241fe0f4 | 29,506 |
from typing import Optional
def get_default_tag_to_block_ctor(
tag_name: str
) -> Optional[CurvatureBlockCtor]:
"""Returns the default curvature block constructor for the give tag name."""
global _DEFAULT_TAG_TO_BLOCK_CTOR
return _DEFAULT_TAG_TO_BLOCK_CTOR.get(tag_name) | 33d002ef206aa13c963b951325a92f49c86eb202 | 29,507 |
def panel_list_tarefas(context, tarefas, comp=True, aluno=True):
"""Renderiza uma lista de tarefas apartir de um Lista de tarefas"""
tarefas_c = []
for tarefa in tarefas:
tarefas_c.append((tarefa, None))
context.update({'tarefas': tarefas_c, 'comp': comp})
return context | 3de659af41a6d7550104321640526f1970fd415c | 29,508 |
def remove_stopwords(label):
"""
Remove stopwords from a single label.
"""
tokenized = label.split()
# Keep removing stopwords until a word doesn't match.
for i,word in enumerate(tokenized):
if word not in STOPWORDS:# and len(word) > 1:
return ' '.join(tokenized[i:])
# Fo... | f15e50e5e11ecc6a0abca6b68219789e72070a69 | 29,510 |
def single_device_training_net(data_tensors, train_net_func):
""" generate training nets for multiple devices
:param data_tensors: [ [batch_size, ...], [batch_size, ...], ... ]
:param train_net_func: loss, display_outputs, first_device_output = train_net_func(data_tensors, default_reuse)
... | d94e7b552f3612d2f0fd16973612adea77de0bd0 | 29,511 |
def clopper_pearson(k,n,alpha):
"""Confidence intervals for a binomial distribution of k expected successes on n trials:
http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval
Parameters
----------
k : array_like
number of successes
n : array_like
number of trials
... | c10db17a4fb75cc0d7304aceacde9cf716a5cb77 | 29,515 |
def add_link(news_list:list) -> list:
"""
Description:
Function to remove the readmore and the add the url as a marked up link for the 'content' key in the 'articles' dictionary.
Arguments:
news_list {list} : list containing the news articles dictionaries
Returns:
news_list ... | f1339ddb8854800ae241b7cbb0badc6654c30696 | 29,516 |
import array
def taitnumber(c):
""" Return Tait number from signed edge list of Tait graph. """
c = array(c) # If type(c) != ndarray
tau = sum(sign(c[:, 0]))
return tau | b30e3d294ae4af80e5d09b7c5de0a6a0682d6d27 | 29,517 |
def _difference_map(image, color_axis):
"""Difference map of the image.
Approximate derivatives of the function image[c, :, :]
(e.g. PyTorch) or image[:, :, c] (e.g. Keras).
dfdx, dfdy = difference_map(image)
In:
image: numpy.ndarray
of shape C x h x w or h x w x C, with C = 1 or C = 3
... | deff16dbe73005d52444babf05857c2cfea25e0b | 29,518 |
import math
def force_grid(force_parameters, position_points, velocity_min, velocity_max):
"""Calculates the force on a grid of points in phase space."""
velocity_min_index = velocity_index(velocity_min)
velocity_max_index = velocity_index(velocity_max)
spacing = 2*math.pi / position_points
force = np.zeros((vel... | d8d74604c8e313904f97e97364778b0db8db801c | 29,519 |
def valueFromMapping(procurement, subcontract, grant, subgrant, mapping):
"""We configure mappings between FSRS field names and our needs above.
This function uses that config to derive a value from the provided
grant/subgrant"""
subaward = subcontract or subgrant
if mapping is None:
return ... | 1bf2dda830183d1c8289e957b83b1c0d01619160 | 29,521 |
def get_cards_in_hand_values_list(player):
"""Gets all the cards in a players's hand and return as a values list"""
return list(Card.objects.filter(cardgameplayer__player=player, cardgameplayer__status=CardGamePlayer.HAND).values('pk', 'name', 'text')) | 474ac071950857783dfd76b50ae08483a03fc8bc | 29,522 |
def get_dGdE(fp, tau_E, a_E, theta_E, wEE, wEI, I_ext_E, **other_pars):
"""
Compute dGdE
Args:
fp : fixed point (E, I), array
Other arguments are parameters of the Wilson-Cowan model
Returns:
J : the 2x2 Jacobian matrix
"""
rE, rI = fp
# Calculate the J[0,0]
dGdrE = (-1 + wEE * dF(wE... | 9a53cc9b0cadea8f8884b64d687a2397c0a973a7 | 29,523 |
def convert_data_to_ints(data, vocab2int, word_count, unk_count, eos=True):
"""
Converts the words in the data into their corresponding integer values.
Input:
data: a list of texts in the corpus
vocab2list: conversion dictionaries
word_count: an integer to count the words in the dat... | c415aea164f99bc2a44d5098b6dbcc3d723697a6 | 29,524 |
def apply_objective_fn(state, obj_fn, precision, scalar_factor=None):
"""Applies a local ObjectiveFn to a state.
This function should only be called inside a pmap, on a pmapped state.
`obj_fn` will usually be a the return value of `operators.gather_local_terms`.
See the docstrings of `SevenDiscretedOperator` ... | c4fa72f84ce241aa765416fe21ff5426758d5303 | 29,525 |
import requests
def oauth_generate_token(
consumer_key, consumer_secret, grant_type="client_credentials",
env="sandbox"):
"""
Authenticate your app and return an OAuth access token.
This token gives you time bound access token to call allowed APIs.
NOTE: The OAuth access token expires ... | 7ab44b7ba1eb569d0b498946e2936928612e3fa7 | 29,526 |
from typing import List
import shlex
def parse_quoted_string(string: str, preserve_quotes: bool) -> List[str]:
"""
Parse a quoted string into a list of arguments
:param string: the string being parsed
:param preserve_quotes: if True, then quotes will not be stripped
"""
if isinstance(string, l... | 6715778f5190445e74b8705542cbfdb1fe022ecc | 29,527 |
def scalar(name, scalar_value):
""" 转换标量数据到potobuf格式 """
scalar = make_np(scalar_value)
assert (scalar.squeeze().ndim == 0), 'scalar should be 0D'
scalar = float(scalar)
metadata = SummaryMetadata(plugin_data=SummaryMetadata.PluginData(plugin_name='scalars'))
return Summary(value=[Summary.Value(... | e31046a00dc0e2ae6c33bd041b34652c08d2a439 | 29,528 |
def filter_citations_by_type(list_of_citations, violation_description):
"""Gets a list of the citations for a particular violation_description.
"""
citations = []
for citation in list_of_citations:
filtered_citation = check_citation_type(citation, violation_description)
if filtered_ci... | 398d7cbe43761070c8b5b9117478f6fe5c985a2c | 29,529 |
def user_import_circular_database(injector, session, user_mock_circular_database) -> UserMockDataSource:
"""Return the circular data source and import its schema
to the user's project."""
facade = injector.get(DataSourceFacade)
facade.import_schema(user_mock_circular_database.data_source)
session.co... | 492b87c7cf8d5ef8306fb827620cba860677f5be | 29,530 |
import torch
def loss_fn(model, data, marginal_prob_std, eps=1e-5):
"""The loss function for training score-based generative models.
Args:
model: A PyTorch model instance that represents a
time-dependent score-based model.
x: A mini-batch of training data.
marginal_prob_std: A funct... | f42dd43d1de865ec31c7702e747852a6df04e479 | 29,531 |
from functools import reduce
from operator import mul
def nCk(n, k):
"""
Combinations number
"""
if n < 0: raise ValueError("Invalid value for n: %s" % n)
if k < 0 or k > n: return 0
if k in (0, n): return 1
if k in (1, n-1): return n
low_min = 1
low_max = min(n, k)
high_min = ... | 9d84ba8fad27860f64980fb4165f72f0a7ec944c | 29,532 |
def knowledge_extract_from_json():
"""
半结构化数据知识抽取的第二步
json <-> 数据表映射
Returns:
"""
data = request.json
result = extract_data_from_json(data)
return jsonify({"data": result}) | 361d38891a8d90d30a75e3041e082e9c60395666 | 29,533 |
import random
def vote_random_ideas(request, owner, repository, full_repository_name):
"""
Get 2 random ideas
"""
database_repository = get_object_or_404(models.Repository, owner=owner, name=repository)
jb = jucybot.from_config()
context = {}
context = jb.get_issues(full_repository_name, c... | dba4d24711e49f68e85ef6b9f5d3fb4428cb6351 | 29,534 |
def delta_EF_asym(ave,t_e,t_mu,comp,t_f,n,alpha = None,max_ave_H = 1):
"""computes the EF with asymptotic f, f(N) = f_i*H_i*N_i/(N_i+H_i)
For more information see S10
H_i is uniformly distributed in [0,2*ave_H]
Input
ave, t_e, t_mu, t_f, comp,n:
As in output of rand_par
... | 82abe7a6473b9a0b432654837fb8bffff86513e8 | 29,535 |
from scipy.signal.spectral import _median_bias
from scipy.signal.windows import get_window
def time_average_psd(data, nfft, window, average="median", sampling_frequency=1):
"""
Estimate a power spectral density (PSD) by averaging over non-overlapping
shorter segments.
This is different from many othe... | 98fb788fdec7f2a868cc576f209c37e196880edf | 29,536 |
import torch
def Variable(tensor, *args, **kwargs):
"""
The augmented Variable() function which automatically applies cuda() when gpu is available.
"""
if use_cuda:
return torch.autograd.Variable(tensor, *args, **kwargs).cuda()
else:
return torch.autograd.Variable(tensor, *args, **... | b8b0534efd0fd40966eaa70e78e6a8db41156cd4 | 29,537 |
def edit_distance(graph1, graph2, node_attr='h', edge_attr='e', upper_bound=100, indel_mul=3, sub_mul=3):
"""
Calculates exact graph edit distance between 2 graphs.
Args:
graph1 : networkx graph, graph with node and edge attributes
graph2 : networkx graph, graph with node and edge attributes
... | 550f44e91e60a7c3308d5187af3d32054cf6dffa | 29,539 |
def get_node_elements(coord,scale,alpha,dof,bcPrescr=None,bc=None,bc_color='red',fPrescr=None,f=None,f_color='blue6',dofs_per_node=None):
"""
Routine to get node node actors.
:param array coord: Nodal coordinates [number of nodes x 3]
:param int scale: Node actor radius
:param float alpha: Node act... | f6e9c2eec12c1816331651d821fa907e5ce34d42 | 29,540 |
import logging
import time
import pickle
def temporal_testing(
horizon, model, observ_interval, first_stage,
bm_threshold, ratio, bootstrap, epsilon, solve
):
"""
first stage random forest, cross validation,
not selecting a best model,
without separate testing
"""
model_name = "horizon... | c6320d2638ee98931af8523085d37981095e9f14 | 29,541 |
def _endian_char(big) -> str:
"""
Returns the character that represents either big endian or small endian in struct unpack.
Args:
big: True if big endian.
Returns:
Character representing either big or small endian.
"""
return '>' if big else '<' | 2e1a63ec593ca6359947385019bcef45cb3749c0 | 29,542 |
def planar_angle2D(v1, v2):
"""returns the angle of one vector relative to the other in the
plane defined by the normal (default is in the XY plane)
NB This algorithm avoids carrying out a coordinate transformation
of both vectors. However, it only works if both vectors are in that
plane to start... | c244ce7a2bcd27e110062dba0c88f2537e0cb7dd | 29,543 |
def test_agg_same_method_name(es):
"""
Pandas relies on the function name when calculating aggregations. This means if a two
primitives with the same function name are applied to the same column, pandas
can't differentiate them. We have a work around to this based on the name property
... | 638447c081d2a5dcf4b2377943146876b7438e2c | 29,544 |
def dispatch(request):
"""If user is admin, then show them admin dashboard; otherwise redirect
them to trainee dashboard."""
if request.user.is_admin:
return redirect(reverse("admin-dashboard"))
else:
return redirect(reverse("trainee-dashboard")) | 046107c46cbac5e7495fee19c4354a822c476a5b | 29,545 |
def log_pdf_factor_analysis(X, W, mu, sigma):
""" log pdf of factor analysis
Args:
X: B X D
W: D X K
mu: D X 1
sigma: D X 1
Returns:
log likelihood
"""
Pi = tf.constant(float(np.pi))
diff_vec = X - mu
sigma_2 = tf.square(sigma)
# phi = tf.eye(K) * sigma_2
# M = tf.... | 70eb515c3a7b7cc8ea49f6a0e79c11327629c7b5 | 29,546 |
import logging
def _assert_initial_conditions(scheduler_commands, num_compute_nodes):
"""Assert cluster is in expected state before test starts; return list of compute nodes."""
compute_nodes = scheduler_commands.get_compute_nodes()
logging.info(
"Assert initial condition, expect cluster to have {... | 6a19830caf029dd2a28cdb2363988940610bbc14 | 29,547 |
from typing import Dict
from typing import Any
def _clean_parameters(parameters: Dict[str, Any]) -> Dict[str, str]:
""" Removes entries which have no value."""
return {k: str(v) for k, v in parameters.items() if v} | b8e911674baee7a656f2dc7ba68514c63f84290c | 29,548 |
def delete(run_id):
"""Submits a request to CARROT's runs delete mapping"""
return request_handler.delete("runs", run_id) | 8f106d83ba39995f93067a3f8eb67b430b8fd301 | 29,549 |
import math
def get_tile_lat_lng(zoom, x, y):
"""convert Google-style Mercator tile coordinate to
(lat, lng) of top-left corner of tile"""
# "map-centric" latitude, in radians:
lat_rad = math.pi - 2*math.pi*y/(2**zoom)
# true latitude:
lat_rad = gudermannian(lat_rad)
lat = lat_rad * 180.0... | 6bf0e31b30930f3916112d6540e4387a72238586 | 29,550 |
def process_zdr_precip(procstatus, dscfg, radar_list=None):
"""
Keeps only suitable data to evaluate the differential reflectivity in
moderate rain or precipitation (for vertical scans)
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
... | 44b58f755a103756a2cd6726d19b3a7d958d09c3 | 29,551 |
import random
def get_initators(filepath, n_lines):
"""
Open text file with iniator words and sample random iniator for each line in the poem.
"""
with open(filepath, "r", encoding = "utf-8") as file:
# save indices of all keywords
loaded_text = file.read() # load text file
li... | 94792679a6ea4e0bb14afd5eb38b656a2cc8af67 | 29,552 |
def GSAOI_DARK():
"""
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 289 ()
1 1 ImageHDU 144 (2048, 2048) float32
2 2 ImageHDU 144 (2048, 2048) float32
3 3 ImageHDU 1... | c1cea8420ef518027d14bcf4d430c772268c6024 | 29,553 |
import traceback
import time
def wrapLoop(loopfunc):
"""Wraps a thread in a wrapper function to restart it if it exits."""
def wrapped():
while True:
try:
loopfunc()
except BaseException:
print(f"Exception in thread {loopfunc},"
... | 86c48bc850bb1cf17121130ee9349dd529acf5e3 | 29,554 |
def get_version(tp):
"""
Get Version based on input parameters
`tp` - Object of class: Transport
"""
response = None
try:
response = tp.send_data('proto-ver', '---')
except RuntimeError as e:
on_except(e)
response = ''
return response | 276dae2599ec99906ea954aae8ad9f79eb2de7d7 | 29,555 |
def _decode_feed_ids(option_feeds):
"""
>>> _decode_feed_ids('123,456')
[123, 456]
"""
return [int(x) for x in option_feeds.strip().split(',')] | 9218a170c445b3b8d83f08c39d1547c3ff6e2d20 | 29,556 |
def append_to_phase(phase, data, amt=0.05):
"""
Add additional data outside of phase 0-1.
"""
indexes_before = [i for i, p in enumerate(phase) if p > 1 - amt]
indexes_after = [i for i, p in enumerate(phase) if p < amt]
phase_before = [phase[i] - 1 for i in indexes_before]
data_before = [dat... | 1b416e5352efdff9e578e77f8a068a8f6a446a38 | 29,557 |
def timedelta2s(t_diff):
"""return number of seconds from :class:`numpy.timedelta64` object
Args:
t_diff: time difference as :class:`numpy.timedelta64` object
Returns:
scalar corresponding to number of seconds
"""
return t_diff / np.timedelta64(1, 's') | 47d3b41717c877aa9c57a0f2745b95888738523b | 29,558 |
def window(MT_seq, WT_seq, window_size=5):
"""
Chop two sequences with a sliding window
"""
if len(MT_seq) != len(WT_seq):
raise Exception("len(MT_seq) != len(WT_seq)")
pos = []
mt = []
wt = []
for i in xrange(len(MT_seq) - window_size + 1):
pos.append(i)
mt.appen... | 67fecea9ed7155a2c85e9cd7acae9ff5a17402e7 | 29,559 |
def splits_for_blast(target, NAME):
"""Create slices for BLAST
This function creates multiple slices of 400 nucleotides given an fasta
sequence. The step size is 50. This the gaps are excluded from the sequence.
Thats why sequences with less than 400 nucleotides are excluded.
Args:
target (np... | 6ad193fe494a6387fbb06d2c2a3b6a059b903a5f | 29,560 |
from io import StringIO
def test_load_items_errors() -> None:
"""
Test error cases when creating a list of classification Items from a dataframe
"""
def load(csv_string: StringIO) -> str:
df = pd.read_csv(csv_string, sep=",", dtype=str)
numerical_columns = ["scalar2", "scalar1"]
... | 649358c42db33e178a4269ed48b186999903bbdb | 29,561 |
import imghdr
def validate_image(stream):
"""
Ensure the images are valid and in correct format
Args:
stream (Byte-stream): The image
Returns:
str: return image format
"""
header = stream.read(512)
stream.seek(0)
format = imghdr.what(None, header)
if not format:
... | 1a1976f5b009c2400071ebf572d886c1f7d12ab0 | 29,562 |
def my_mean(my_list):
"""Calculates the mean of a given list.
Keyword arguments:
my_list (list) -- Given list.
return (float) -- Mean of given list.
"""
return my_sum(my_list)/len(my_list) | 2423d51bf457a85ee8a6a8f1505a729b6d1d3f6f | 29,563 |
def pr(labels, predictions):
"""Compute precision-recall curve and its AUC.
Arguments:
labels {array} -- numpy array of labels {0, 1}
predictions {array} -- numpy array of predictions, [0, 1]
Returns:
tuple -- precision array, recall array, area float
"""
precision, recall,... | 5cf18052875396483f7a76e4c6c0b55f1541803d | 29,564 |
def grouped_evaluate(population: list, problem, max_individuals_per_chunk: int = None) -> list:
"""Evaluate the population by sending groups of multiple individuals to
a fitness function so they can be evaluated simultaneously.
This is useful, for example, as a way to evaluate individuals in parallel
o... | ea43be334def0698272ba7930cc46dc84ce78de9 | 29,565 |
def ZeusPaypalAccounts(request):
""" Zeus Paypal Account Credentials """
if request.method == "GET":
return render(request, "lost-empire/site_templates/zeus/paypal_accounts.html") | 34a0fc616beac2869d501d1652ccd7c9d8ff2489 | 29,566 |
def upper_tri_to_full(n):
"""Returns a coefficient matrix to create a symmetric matrix.
Parameters
----------
n : int
The width/height of the matrix.
Returns
-------
SciPy CSC matrix
The coefficient matrix.
"""
entries = n*(n+1)//2
val_arr = []
row_arr = []... | 5fdca1868f0824d9539bd785aa99b20c6195b7c0 | 29,567 |
def sort_dnfs(x, y):
"""Sort dnf riders by code and riderno."""
if x[2] == y[2]: # same code
if x[2]:
return cmp(strops.bibstr_key(x[1]),
strops.bibstr_key(y[1]))
else:
return 0 # don't alter order on unplaced riders
else:
return strops.... | ccf20fb43df26219ce934e18b2d036e3cf6d13b7 | 29,570 |
import torch
def gen_diag(dim):
"""generate sparse diagonal matrix"""
diag = torch.randn(dim)
a_sp = sparse.diags(diag.numpy(), format=args.format)
a_pt = _torch_from_scipy(a_sp)
return a_pt, a_sp | 9ca2842553a1b6331347210bd1da049f53e67361 | 29,571 |
def one_of(patterns, eql=equal):
"""Return a predicate which checks an object matches one of the patterns.
"""
def oop(ob):
for p in patterns:
if validate_object(ob, p, eql=eql):
return True
return False
return oop | 058f1f64780760d9e996858dcfad4c0a47c07448 | 29,572 |
def convert_to_MultiDiGraph(G):
"""
takes any graph object, loads it into a MultiDiGraph type Networkx object
:param G: a graph object
"""
a = nx.MultiDiGraph()
node_bunch = []
for u, data in G.nodes(data = True):
node_bunch.append((u,data))
a.add_nodes_from(node_bunch)
ed... | bde49710bed50386bd7bb09816e6f18089ed8030 | 29,574 |
def x_to_world_transformation(transform):
"""
Get the transformation matrix from x(it can be vehicle or sensor)
coordinates to world coordinate.
Parameters
----------
transform : carla.Transform
The transform that contains location and rotation
Returns
-------
matrix : np.nd... | 718227deea6a6be4a0b24ebf4eda40d78be20fcf | 29,575 |
def protobuf_get_constant_type(proto_type) :
"""About protobuf write types see :
https://developers.google.com/protocol-buffers/docs/encoding#structure
+--------------------------------------+
+ Type + Meaning + Used For +
+--------------------------------------+
+ + + i... | 46ce7e44f8499e6c2bdcf70a2bc5e84cb8786956 | 29,576 |
def edit_delivery_products(request, delivery):
"""Edit a delivery (name, state, products). Network staff only."""
delivery = get_delivery(delivery)
if request.user not in delivery.network.staff.all():
return HttpResponseForbidden('Réservé aux administrateurs du réseau '+delivery.network.name)
... | fc734e5ded0a17d20a79d36e8ae599ee763ea73a | 29,577 |
import pprint
def format_locals(sys_exc_info):
"""Format locals for the frame where exception was raised."""
current_tb = sys_exc_info[-1]
while current_tb:
next_tb = current_tb.tb_next
if not next_tb:
frame_locals = current_tb.tb_frame.f_locals
return pprint.pform... | b5a21f42c8543d9de060ff7be2b3ad6b23065de9 | 29,579 |
def binarize_garcia(label: str) -> str:
"""
Streamline Garcia labels with the other datasets.
:returns (str): streamlined labels.
"""
if label == 'hate':
return 'abuse'
else:
return 'not-abuse' | 5cc26303e0c496d46b285e266604a38a0c88e8d7 | 29,580 |
def diagstack(K1,K2):
"""
combine two kernel matrices along the diagonal [[K1 0][0 K2]]. Use to have
two kernels in temporal sequence
Inputs
-------
K1, K2 : numpy arrays
kernel matrics
Returns
--------
matrix of kernel values
"""
r1,c1 = K1.shape
r2,c2 = K2.sh... | 6e163bf62ca2639e5bacebad6c03700b1056de2e | 29,581 |
import string
def submit_new_inteface():
"""POST interface configuration from form data"""
global unassigned_ints, interface_nums
ip = None
mask = None
status = None
descr = None
vrf = None
negotiation = None
int_num = [i for i in request.form.get("interface") if i not in string... | f746071d1f1ce2c1bdd9c0b4d4401edbb1119c36 | 29,582 |
from typing import Optional
def component_clause(): # type: ignore
"""
component_clause =
type_prefix type_specifier array_subscripts? component_list
"""
return (
syntax.type_prefix,
syntax.type_specifier,
Optional(syntax.array_subscripts),
syntax.component_lis... | cd788687645d028c39f7ad439aab1ee21e5ad495 | 29,583 |
import numpy as np
def clean_time_series(time, val, nPoi):
"""
Clean doubled time values and checks with wanted number of nPoi
:param time: Time.
:param val: Variable values.
:param nPoi: Number of result points.
"""
# Create shift array
Shift = np.array([0.0], dtype='f')
# Shift ... | 35a4cea11a0dbf33916f3df6f8aae5c508a0c838 | 29,584 |
from typing import Callable
def deep_se_print(func: Callable) -> Callable:
"""Transforms the function to print nested side effects.
Searches recursively for changes on deep inner attributes of the arguments.
Goes down a tree until it finds some element which has no __dict__. For
each element of the ... | e5c2ee57f9f5ecd992ac36a30ac6e32c7afdbd8a | 29,585 |
from pathlib import Path
def prepare_checkpoints(path_to_checkpoints:str, link_keys=["link1","link2","link3","link4"], real_data=True,*args, **kwargs)-> str:
""" The main function preparing checkpoints for pre-trained SinGANs of Polyp images.
Parameters
-----------
path_to_checkpoints: str
A ... | 4e49a495b3dd587c4b9b350d5e329f7dab36ef30 | 29,586 |
def data_count():
"""
:return: 数据集大小
"""
return 300 | 1582c3782cd77ee79727a7874afbb74539f3ff9e | 29,587 |
import logging
import re
def grid_name_lookup(engine):
"""Constructs a lookup table of Institute names to ids by combining names with
aliases and cleaned names containing country names in brackets. Multinationals are
detected.
Args:
engine (:obj:`sqlalchemy.engine.base.Engine`): connection to... | 0a0fef49c722d6c8c40e2d00f1d87d8f41efbbef | 29,588 |
def sample_vMF(theta, kappa,size=1):
"""
Sampling from vMF
This is based on the implementation I found online here:
http://stats.stackexchange.com/questions/156729/sampling-from-von-mises-fisher-distribution-in-python
(**** NOTE THE FIX BY KEVIN *****)
which is based on :
... | 1e8d327b5613d9f2e5f77c26eab86d09d9d8338b | 29,589 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.