content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def glType(typ, *args):
"""return ctypes array of GLwhatever for Pyglet's OpenGL interface. (This
seems to work for all types, but it does almost no type conversion. Just
think in terms of "C without type casting".)
typ -> ctype or GL name for ctype; see pyglet.gl.GLenum through GLvoid
args -> Eithe... | 138ec67bb500e40d6e35c06a397f33cb4fb96311 | 3,624,539 |
def FisherRao_dist(X1, X2):
"""
Compute the Fisher-Rao distance between two curves in R³
...
"""
# #alignement des centres
# X2 = X2 - fs.curve_functions.calculatecentroid(np.transpose(X2))
# #rotations
# X2_new = fs.curve_functions.find_best_rotation(np.transpose(X1), np.transpose(X2))[... | 0480fa3b33944152eaef829bf17d0b7dcda75863 | 3,624,540 |
from typing import Union
from typing import Sequence
def plot_line(
line: Union[do.Line, Sequence[do.Line]],
ax: Union[mpl.axes.Axes, None] = None,
**kwargs,
) -> mpl.axes.Axes:
"""Plot a Line Dataobject
Parameters
----------
line : Union[do.Line, Sequence[do.Line]]
ax : Union[mpl.axe... | 626379d9d1d85a4c6149fc03e71047720ec12470 | 3,624,541 |
def serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
try:
return obj.__dict__
except AttributeError:
return None | 326421045ebb5990cc9079ef25fc2428cd036b52 | 3,624,542 |
def _get_monitor_value_from_hdf5(image, monitor_key):
"""Return the monitor value from an HDF5 image using an header key.
The monotor_key is a path from the image path containing:
- A dataset containing a scalar (a constant monitor)
- A dataset containing a vector of values (it must containes enougth ... | 765925e0b7c6493c8b4d86f806992c2a06c03e8d | 3,624,543 |
def create_MultiRNNCell(hidden_sizes, keep_prob, num_proj=None,
memory=None, memory_seq_lengths=None,
reuse=False):
"""
Only the last layer has projection and attention
Args:
hidden_sizes: a list of hidden sizes for each layer
num_proj: the ... | 27cd87e0a76771e250d2f83a563e8ce920e77412 | 3,624,544 |
def expand_time(data: pd.DataFrame):
"""
扩展时间纬度信息
"""
tmp = pd.DataFrame(columns=data.columns)
tmp['Time'] = pd.date_range(
data['Time'].values[0],
data['Time'].values[-1],
freq='4H'
)
tmp = tmp.merge(wipe_anomaly(data), how='outer').groupby('Time').max()
return ... | 057495e67fdc9d6264d8427c1f8639d849cce72b | 3,624,545 |
def _EffectiveActiveConfigName():
"""Gets the currently active configuration.
It checks (in order):
- Flag values
- Environment variable values
- The value set in the activator file
Returns:
str, The name of the active configuration or None if no location declares
an active configuration.
... | d8166632caf6153d1ec6d943eab902d168100678 | 3,624,546 |
def svn_repos_get_fs_build_parser2(*args):
"""
svn_repos_get_fs_build_parser2(svn_repos_t * repos, svn_boolean_t use_history, enum svn_repos_load_uuid uuid_action,
svn_stream_t * outstream, char const * parent_dir, apr_pool_t pool) -> svn_error_t
"""
return _repos.svn_repos_get_fs_build_parser2(*ar... | 3db064fd42c2fc416bb7f740e3715b0bf1c9af9a | 3,624,547 |
def plotting_context(
context: str = "notebook", font_scale: float = 1.5, rc: dict = None
):
"""
创建默认画图板样式
参数
---
:param context: seaborn 样式
:param font_scale: 设置字体大小
:param rc: 配置标签
"""
if rc is None:
rc = {}
rc_default = {"lines.linewidth": 1.5}
# 如果没有默认设置,增加... | c086aeb7e616d21a0a7789179ac06803c2d47666 | 3,624,548 |
def arc(c,rp=False,sn=False,e=False,n=False,samplereverse=False):
"""
Construct an arc by copying an eisting arc or specifying a center ``c`` and various optional parameters.
"""
if isarc(c):
return deepcopy(c)
elif ispoint(c):
cen = point(c)
w=-1
if samplereverse:
... | 5537447777ca6f9b89cc5b0a8c3751827086539b | 3,624,549 |
def factorial(num):
"""Finds the factorial of the input integer.
:arg num: an integer
"""
#If the number provided is zero then the factorial is 1
if num == 0:
fact = 1
#Otherwise set fact to 1 and begin finding the factorial r is
#used to find each num-n for n=0 to n=num each v... | 0dc8935c5d25acbc9d1d9dff1e86d5b6fcf80638 | 3,624,550 |
def MaybeEmulateMultiBleu(nltk_target_fn):
"""Includes emulate_multibleu argument into nltk_target_fn if necessary.
The signature of the NLTK functions corpus_bleu and sentence_bleu depend on
the NLTK version. This function works around version differences encountered
in the public and internal environments.
... | 476770fb9e025360ab9dbeaa71b8a0cc7bdaa96d | 3,624,551 |
import time
import json
from datetime import datetime
def incoming_cloudwatch_alarm(event, _):
"""
Standard AWS Lambda entry point for receiving CloudWatch alarm notifications.
"""
print(event)
try:
updated_timestamp = int(time.time())
ddb_table_name = ALARMS_TABLE_NAME
ddb... | 16a4a23e0679d22e9cf68e2c45f8973d1b5e0587 | 3,624,552 |
def sort_data_into_spectrum(
ions: np.ndarray, bin_start: int, bin_end: int
) -> np.ndarray: # pragma: nocover
"""Sort ion data in 1D array into an overall array and sum them up.
:param ions: Arrival time of the ions - number of time bin
:param bin_start: First bin of spectrum
:param bin_end: Last... | c6c179c00dacd166492f0df242260740ac15e0b2 | 3,624,553 |
def RX_partitioning_replicates_extended(data_arr,ind,perc,Issues=[],Skip=False,extension=0,Cap=None,ll=0):
"""
partition sequence trace using tape measure
processes involved:
find tape measure peaks (peak_finder)
extract sequencing traces between tape measure peaks
calculate bin width... | 6d055692996249df9caf643c46871e63e7c4d255 | 3,624,554 |
def has_same_sign_or_zero(data):
"""Evaluate whether the array has all elements with the same sign or zero.
Args:
data (np.array): An array.
Returns:
bool: Boolean with the evaluation.
Examples:
>>> data = np.array([(1,2,3),(2,3,4)])
>>> has_same_sign_or_ze... | a772cecfe2885460d63387ae8b09f13d7016198c | 3,624,555 |
import random
import string
def showLogin():
"""Login page view."""
state = ''.join(
random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
login_session['state'] = state
return render_template('home/login.html', STATE=state) | ab959bb5bad16375055ac83612099d1da5bd775e | 3,624,556 |
import json
def dump_svlengths_report_data(bed_ifs):
"""Given input-file-stream of BED,
return JSON string of svlengths_report_data.
"""
with BedReader(bed_ifs) as reader:
return json.dumps(get_svlengths_report_data(reader)) | 06aef228ab0ceddcd8f6ce08437a4065c7b61db6 | 3,624,557 |
def tree_left_fa_fun(t, assignment=None):
"""Given some tree node `t`, do FA assuming the left branch is the
function."""
result = tree_fa_fun_abstract(t[0], t[1], assignment)
if result is None:
raise TypeMismatch(t[0], t[1], "FA/left")
return BinaryComposite(t[0], t[1], result, source=t) | f98bd12a7733372570b4b75a1d3aed355c8f3172 | 3,624,558 |
def list_statistic_ids(
hass: HomeAssistant, statistic_type: str | None = None
) -> list[dict[str, str] | None]:
"""Return statistic_ids and meta data."""
units = hass.config.units
statistic_ids = {}
with session_scope(hass=hass) as session:
metadata = _get_metadata(hass, session, None, stat... | b7bf0deefef827e3eebf12170a2fa32c124cf79b | 3,624,559 |
import logging
def GetFirmwareBinaryVersion(path):
"""Gets the version stored in RO_FRID section of the firmware binary.
Args:
path: Path to the firmware binary.
Returns:
The extracted firmware version as a string; or None if the function fails to
extract version.
"""
result = None
try:
... | 0d66b33ec2812b9c6f5adc1db216cd7268dd7550 | 3,624,560 |
def parse_alpino_file(path: str) -> list[Proof]:
"""
Parses an Alpino file containing a single sentence and returns a list of proofs.
"""
with open(path, 'r') as f:
etree = parse(path)
name = etree.find('sentence').attrib['sentid']
trees = prepare_for_extraction(etree, name)
retu... | 3d9a7591305a6526e4eaf5505bc7282b5d26a559 | 3,624,561 |
def integrator(int_alg,timestep,pos,veloc,accel,molec,grad_method):
""" Selects the type of integration algorithm to propagate the trajectories
Only velocity Verlet implemented (date: 05/23/17 - LAC)
Parameters:
----------
string int_alg -- Integrator Algorith to be used
... | d449f4f6e77baabe8841f77d30c6a50ddc214ac5 | 3,624,562 |
from typing import Dict
def generate_detail_link_dict(instance: Dict) -> Dict:
"""
Generate a dictionary that consists of this instance's provider discriminators, so that we can convert it to a link
to the instance detail page.
:param instance: A dict representing an instance, that contains `provider... | ec57d3b9295372d49c8ade746930268c4d25154d | 3,624,563 |
def get_cookie_expiry_datetime(cookie):
"""
example cookie:
sessionid=XXXXXXXXXXXXXXXXXXXXX; expires=Wed, 16-Mar-2011 17:52:10 GMT; Max-Age=2592000; Path=/, ds_user=USERNAME; Max-Age=2592000; Path=/, ds_user_id=USERID; Max-Age=2592000; Path=/
"""
try:
start = cookie.lower().find('expires') +... | c51a603e998c5962e2fd39d472da58e4e7af1ca6 | 3,624,564 |
def colorize_groups(figure, group=None, saturations_map=None):
"""Colorize groups representations."""
nr_colors = figure.shape[0]
assert nr_colors in [4], 'color map assumes four groups.'
color_conv = 1 - GROUP_COLORS
if group is not None:
new_figure = np.dot(color_conv[[group]].T, figure.... | 81720cbff9c5a6d80d366572f20c043796d841fb | 3,624,565 |
import itertools
def combine_targets_and_zeros(target_strings, php_zero_strings, zero_strings, n_collisions):
"""Combines the zero strings with the target strings until the desired number of collisions is reached"""
i = 0
ret = []
while True:
for php_zero in php_zero_strings:
for ... | 4ba76f2b903ce3b7f6797aecd1027331631c282e | 3,624,566 |
import requests
from bs4 import BeautifulSoup
def get_all_links(url: str) -> LinksType:
"""
Sends http request to url, downloads all data,
extract links
Args:
url: url of website we want to search
Returns:
list of all links
"""
# create response object
r = requests.ge... | 9a6f0c2c2f60ee27aa5a06f2e841dd3b3758670b | 3,624,567 |
from typing import Sequence
def basic_sweep() -> Sequence[ensemble_plus.EnsembleConfig]:
"""Basic sweep over hyperparams."""
sweep = []
for num_ensemble in [1, 3, 10, 30, 100]:
sweep.append(ensemble_plus.EnsembleConfig(
num_ensemble=num_ensemble,
))
return tuple(sweep) | 23dcf9d34482a4e67d967f6a75e9b8f85529f891 | 3,624,568 |
def create_event(slope, plateau, tau, dt, alpha=1e-3, smothing_length=None):
"""
Create an artificial event.
Parameters
----------
slope: float
Slope of the rising.
plateau: float
Time of the middle plataue.
tau: float
Time constant of the capacitor behavior.
dt:... | 796edf91bde54b3cf1effc12e279d6612711d264 | 3,624,569 |
from typing import Optional
import fastapi
from typing import Union
def query_object(*,
select: Optional[str] = fastapi.Query(
None,
title='The list of fields to select.',
description='Example: `[id, login, { users: {... } }]`. JSON or YAML.',
),
join: Optio... | 3c6696065f3fe668602192b4e933d0256149abe6 | 3,624,570 |
import numpy
def get_storm_track_colours():
"""Returns list of colours to use in plotting storm tracks.
:return: rgb_matrix: 10-by-3 numpy array. rgb_matrix[i, 0] is the red
component of the [i]th colour; rgb_matrix[i, 1] is the green component
of the [i]th colour; rgb_matrix[i, 2] is the bl... | 69acc4f2a666a86045f10aefe3ffa96bea8e99d0 | 3,624,571 |
def calc_delta_lampam_mp(ss, multipanel, constraints, inner_step=-1):
"""
returns the lamination parameters associated with a group of plies of a
multi-panel structure
OUTPUTS
- delta_lampam: array storing the sublaminate partial lamination parameters
INPUTS
- ss: array storing the subla... | a3306529e5cbc74e8618a5c83aeef0b022159606 | 3,624,572 |
def load_model(model_class):
"""This function is for loading the saved model"""
# Define the file directory for each model
if model_class == 'mlp':
filedir = './mtn/mlp'
elif model_class == 'mlp_angle':
filedir = './mtn/mlp_angle'
elif model_class == 'lstm':
filedir = './mtn/... | fcb3b227f68ffb4604aaea013de07d57bdee91d4 | 3,624,573 |
def rvabs_for_orders(ww_all,ff_all,orders,v,M,v2_width=25.,plot=True,ax=None,bx=None,verbose=True,n_points=40):
"""
Same as rvabs, except loop for different orders. Useful for error estimation
EXAMPLE:
v = np.linspace(-120,120,2000)
rr1, rr2 = rvabs_for_orders(ww_all_targ,ff_all_targ,[4... | 49bca456faf5834d96263220e73ca61f88ac8d1d | 3,624,574 |
def placeholder(shape=None, ndim=None, dtype=None, sparse=False, name=None):
"""Instantiates a placeholder tensor and returns it.
# Arguments
shape: Shape of the placeholder
(integer tuple, may include `None` entries).
ndim: Number of axes of the tensor.
At least one of ... | 9b9ba94b6d597599958cf36e95a030684bccc501 | 3,624,575 |
from datetime import datetime
import json
def save_json_db_data():
"""Saves database tables containing data information, such as 'events_with_value' or 'prosensing_paf' events, to a
json file. 'num_entries' for each table specifies how many data rows are in the file for the table, making
iterative parsin... | 3f7b85c0f3ad6e3219e6bd2ed7fb04dc92a041a6 | 3,624,576 |
def replace_number_chunks(msg, tar='?'):
""" Replace digits and adjacent alphabets with the given term
@param msg: Input message
@type msg: String
@param tar: New term to replace
@type tar: String
@return: Replaced message
@rtype: String
"""
def find_first_digit(msg):
f... | 16466501a41b6f97150264e89cc999b61291be9e | 3,624,578 |
import torch
def sortino(rp: torch.Tensor, rf: torch.Tensor) -> torch.Tensor:
"""Returns the sortino ratios for p portfolios
Args:
rp (torch.Tensor): p-by-n matrix where the (i, j) entry corresponds to
the j-th return of the i-th portfolio
rf (torch.Tensor): Scalar risk-free rate (a... | c4af6ad83617976977faef28524c815f810e1f10 | 3,624,579 |
from typing import Union
from typing import Literal
from typing import Optional
from typing import Tuple
def rl_decon(
im: np.ndarray,
background: Union[int, Literal["auto"]] = 80,
n_iters: int = 10,
shift: int = 0,
save_deskewed: bool = False,
output_shape: Optional[Tuple[int, int, int]] = No... | bc0e0a0472b7476a2839e616f66539224a60dfb6 | 3,624,580 |
def all_gates(QuantumCircuit, nr_qubits, initial):
"""This function determines the matrix which corresponds to applying the whole circuit.
Input
-----
QuantumCircuit: np.array
The quantum circuit in the form of a numpy array
nr_qubits: int
... | dfe35f1945a8c3cee1dec640153353d0b2e923ae | 3,624,582 |
from typing import Iterable
import torch
def fuse_single_qubit_operators(
qubits: Iterable[int],
operators: Iterable[torch.Tensor],
):
"""Multiply together gates acting on various single qubits.
Suppose that we have a sequence of single-qubit gates that
should act, one after the other, on... | 640541a3b0a79deb819bafad5734aca3e0dde23d | 3,624,583 |
def make_message(subject="", body="", from_email=None, to=None, bcc=None,
attachments=None, headers=None, priority=None):
"""
Creates a simple message for the email parameters supplied.
The 'to' and 'bcc' lists are filtered using DontSendEntry.
If needed, the 'email' attribute can ... | 301fad714f59767c21f433e2da37bf5b241cc739 | 3,624,584 |
def noneof(*items):
""" noneof(*items) → Return the result of “not any(…)” on all non-`None` arguments """
return negate(any)(item for item in items if item is not None) | 0a6dbb5d6328df7cd7f8870707a92a4d7a2d5059 | 3,624,585 |
def parse_visitor_score(d):
""" Used to parse score of visiting team.
"""
string_value = d.get("uitslag", " 0- 0")
(_, v) = string_value.replace(" ", "").split("-")
return int(v) | df286924774823ca250b71fcb060278093a7611b | 3,624,586 |
def ring2nest(nside, ipix):
"""Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`."""
ipix = np.atleast_1d(ipix).astype(np.int64, copy=False)
return ring_to_nested(ipix, nside) | ba13a7c5d89cd20f5f0b389b5fe63a21464fcc16 | 3,624,588 |
def tag_index(idx):
"""Return a mapping of tag names to index items.
"""
tagidx = dict()
for i in idx:
for t in i.tags:
if t not in tagidx:
tagidx[t] = set()
tagidx[t].add(i)
return tagidx | df3ee2a934bfe3c814a9c1ded8d83314064f38bd | 3,624,590 |
def node_text(node):
"""Needed for things like abstracts which have internal tags (see PMID:27822475)"""
if node.text:
result = node.text
else:
result = ""
for child in node:
if child.tail is not None:
result += child.tail
return result | 076967e644cc99b7339f0cce9f8396a713e61999 | 3,624,591 |
def read_stc(filepath):
"""Read an STC file from the MNE package
STC files contain activations or source reconstructions
obtained from EEG and MEG data.
Parameters
----------
filepath: string
Path to STC file
Returns
-------
data: dict
The STC structure. It has the... | 8af56bb4ee9784a9af1511a3e126f85c05732ce4 | 3,624,592 |
def opd_drift_nogood(opd, drift, nterms=8, defocus_frac=0.8):
"""
Add some WFE drift (in nm) to an OPD image.
Parameters
------------
opd : ndarray
OPD images (can be an array of images).
header : obj
Header file
drift : float
WFE drift in nm
Returns
-------... | 67d479e27e9332de505f02c3bfc65afe21cf0387 | 3,624,593 |
def created_health_check_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.create_health_check` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: ... | 669e5151a90492105c854b33f0bf6e3d424bbf41 | 3,624,594 |
def map_nn(names):
"""
A function used to wrap choices as nn.Module for non-one-shot space definition
Parameters
----------
name : list of anything
the names of module, can be any type
"""
return [StrModule(x) for x in names] | cf1c41260e470faa742bfafc5eb4922bd9fbf3b5 | 3,624,595 |
from typing import Iterator
from typing import Tuple
def channels(N: int, radix: int) -> Iterator[Tuple[int, Iterator[int]]]:
"""Given a 1-d contiguous array of size N, and a FFT of given radix,
this returns a map of iterators of the different memory channels."""
parity_r = partial(parity, radix)
retu... | aef218ffa257f859a9d19ed2608992e2a0c15b1c | 3,624,596 |
def positive_float(value):
"""An argparse type method for accepting only positive floats"""
try:
fvalue = float(value)
except (ValueError, TypeError) as e:
raise ArgumentTypeError(
"Expected a positive float, error message: " "{}".format(e)
)
if fvalue <= 0:
r... | 6abe34452efb17aa10c1239e9f40bf819f2fb3f0 | 3,624,597 |
def readfile(space, fname, use_include_path=False, w_ctx=None):
""" readfile - Outputs a file """
fname, read_filters, write_filters = _parse_wrapper(fname)
if fname == "" or fname is None:
space.ec.warn("readfile(): Filename cannot be empty")
return space.w_False
if not _valid_fname(fn... | 2378fcfa0cf05be2f3d57310e35d12e3bcc88865 | 3,624,598 |
from functools import reduce
import operator
def _match_tags_to_names(tag_names):
"""
INPUT: tag1,tag2,tag3
OUTPUT: <Tag: tag1>, ..., <Tag: tag3>
NOTE: Tags NOT created BEFORE being added to new_machine_tags are ignored.
"""
matches = [Q(name__iexact=name.strip()) for name in tag_names.split('... | 472ac9fdcd113bae2d1975c522e34fc1c374ea16 | 3,624,599 |
def eval_ws(in_data, ws_labels, n_map, label=None, re_all=False):
"""Evaluate and return the best watershed prediction result
Parameters
----------
in_data : np.array or list
data matrix
ws_labels : np.array
predicted cluster labels from watershed segmentation
n_map : np.array
... | 01120016e3f4975d6eaace31b7b24adc6c07b3e2 | 3,624,600 |
def team_width(positions, points=False):
"""Returns the maximum string width of a team."""
width = 0
for position in positions:
if points:
player_names = [PICKS_FORMAT.format(
player.name, player.gameweek_points,
player.role) for player in position]
... | 168ff4c047728730f87e8f5337841f7eb6340cab | 3,624,601 |
def construct_bbox(all_points):
"""
Construct the bounding box based on all points from the
road and buildings that were discretised.
"""
maximum = list(map(max, zip(*all_points)))
minimum = list(map(min, zip(*all_points)))
bbox = [(minimum[0], minimum[1]),
(minimum[0], maximum... | 77f01466bbef500c7c79eee39ad3a69926ec8fc3 | 3,624,602 |
def OpenDocument(filePath) -> NexDoc:
"""Opens a data file with the specified path. Returns a reference to the opened document."""
return NexRun("OpenDocument", locals()) | 69d4cae74d0525d78cb08fee04e5f62de3c9eabf | 3,624,603 |
def solver_rho_complete_nonorm(dp):
"""
Returns rho.
dp is full param dict (with "k_Gp_rho" and "kGp_myo"
"""
dp["Gt"] = dp["Gt_res"]
dp["k_Gp"] = dp["k_Gp_rho"]
dp["Gpt"] = dp["Gpt_rho"]
r = solver_dict_complete_nonorm(dp)
return r[:,1] | bc044daa721fd4b71a5639ecf5baaed59d9b7e07 | 3,624,604 |
from datetime import datetime
def my_review(book_id):
"""
Check to see whether the user is logged in.
Find a book by the supplied book_id.
Find the review related to that book,
written by the logged-in user.
Render the view_book page with that information.
"""
# Check to see whether th... | 0abd66a76b613459d2123466b9ae13b258c3834d | 3,624,605 |
def base64encode(byte_arr):
"""
Encodes an array of binary values to a base64 string.
Args:
byte_arr - the array of bytes to encode
Returns:
A base64 encoding of the given binary data
"""
length = len(byte_arr)
paddingAmount = length % 3
base64_string = ""
# blocks o... | ca0201ad7eaf8d1e9db361ce183e1e424a81fa85 | 3,624,607 |
import math
def dist(p1, p2):
"""
Determines the straight line distance between two points p1 and p2 in euclidean space.
"""
d = math.sqrt(math.pow(p1[0] - p2[0], 2) + math.pow(p1[1] - p2[1], 2))
return d | 8a72ba5966452e7ac2e44f4c1f61d78071423ace | 3,624,608 |
def resize(x, p=2):
"""Resize heatmaps."""
return x**p | b39b25e3c35b1bfa4e76deb638b77ba3fca8c781 | 3,624,609 |
def varifocal_loss(pred,
target,
alpha=0.75,
gamma=2.0,
iou_weighted=True,
reduction='mean',):
"""`Varifocal Loss <https://arxiv.org/abs/2008.13367>`_
Args:
pred (torch.Tensor): The prediction with shape (N, ... | ee707342ea414307613b5875e40078b91dfaa5c5 | 3,624,610 |
def pointIsInside(x,y):
"""pointIsInside
Arguments:
x,y -- x and y coordinates of the point.
returns true if it is inside of the Circumference.
"""
return x**2 + y**2 <= 1. | 16e32c8705e08e868355f3bda5a9b5ae6d6a6f8c | 3,624,611 |
def most_probable_words(vocab, topic_word_distrib, doc_topic_distrib, doc_lengths, n=None):
"""
Order the words from `vocab` by marginal word probability from most to least probable. Optionally only
return the `n` most probable words.
.. seealso:: :func:`~tmtoolkit.topicmod.model_stats.marginal_word_di... | a5f266497659127c64c835cd94ae57f34c8635af | 3,624,612 |
def subscribe_to_responsys(campaign, address, format='html', source_url='',
lang='', country='', **kw):
"""
Subscribe a user to a list in responsys. There should be two
fields within the Responsys system named by the "campaign"
parameter: <campaign>_FLG and <campaign>_DATE.
... | ce38dc0402afdab4dcec224b360d81fdac872f50 | 3,624,613 |
from typing import Optional
def _get_vt_api_key() -> Optional[str]:
"""Retrieve the VT key from settings."""
prov_settings = get_provider_settings("TIProviders")
vt_settings = prov_settings.get("VirusTotal")
if vt_settings:
return vt_settings.args.get("AuthKey")
return None | 977843b5d66eac66f5c9c9d084e06201ba2865ab | 3,624,614 |
def test_qubefit_single():
""" This test will load a thin disk data set which includes gaussian noise
and it will try to fit this data set using the qubefit procedure.
"""
# load the thin disk model
Cube = create_thindiskmodel()
# define the mask to use for the fitting
Cube.create_maskarr... | af0353ebcb9105cb93832b5ab58e3519a235c0ad | 3,624,615 |
def create_qso(con, qso):
""" Function for actually writing qso entries, called by getqso()"""
sql = ''' INSERT INTO qso(utcdate, utctime, band, mode,
ocall, ocat, osec, tcall, tcat, tsec)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?) '''
cur.execute(sql, qso)
con.commit()
ret... | af68e06445fe2dbc16af4bf489820f64fe45fec4 | 3,624,616 |
def smooth(mat, kernel):
"""
Function that produce a smoothed version of the 2D array
:param mat: Array to smooth
:param nPix: kernel array (output) from the function kernel_square()
:return: smoothed array
"""
r = cv2.filter2D(mat, -1, kernel)
print("Smoothing done ...")
return r | a6f1bb5b371286ff2b89bee836976c03ca924726 | 3,624,617 |
def get_pcs(X, n_pcs, **kwargs):
"""
Assumes X has shape (...,n_features)
"""
shape = X.shape
X = X.reshape((-1,shape[-1]))
max_n_pcs = min(X.shape) # min(n_data_points, n_features)
if n_pcs == -1:
n_pcs = max_n_pcs
assert n_pcs <= max_n_pcs # Can't have more than max_n_pcs
p... | 2b33eb96146929d8ad44f564212d2d6f203c907b | 3,624,618 |
import optparse
def parse_commandline():
"""
returns (files, test_mode) created from the command line arguments
passed to pytddmon.
"""
usage = "usage: %prog [options] [static file list]"
version = "%prog " + '1.0.8'
parser = optparse.OptionParser(usage=usage, version=version)
parser.a... | 5b98e682e05514585dcb488f4386b1a1611f6b5a | 3,624,619 |
def load_candidate(path_to_candidate):
"""Load candidate data from a file.
Args:path_to_candidate (str): path to file to load.
Returns:qid_to_ranked_candidate_passages (dict): dictionary mapping from query_id (int) to a list of 1000 passage ids(int) ranked by relevance and importance
"""
with open(... | c25189f709eb9fa00044bd5e0e3ed5e1d5f54371 | 3,624,620 |
def convert_4d_matrix_to_2d_block(K):
"""Convert a 4D matrix of shape ``M, M, V, V`` to a block matrix of shape ``M*V, M*V``"""
M, _, V, __ = K.shape
_K = np.zeros((M*V, M*V))
for i in range(M):
for j in range(M):
_K[i*V:(i+1)*V,j*V:(j+1)*V] = K[i,j,:,:]
return _K | 89e5288d2c63a47c8407c89c1ab63aaadee667a1 | 3,624,621 |
from typing import List
import glob
def get_l10n_files() -> List[str]:
"""取得所有翻譯相關檔案列表,包括.pot .po .mo。
Returns:
List[str]: 翻譯相關檔案列表,包括.pot .po .mo。
"""
po_parser = 'asaloader/locale/*/LC_MESSAGES/asaloader.po'
pot_file = 'asaloader/locale/asaloader.pot'
po_files = glob.glob(po_parser)... | a783679261e7c9bd617728946d01a440b51cfb6a | 3,624,622 |
def get_or_create_service_account(
project_id,
account_id,
account_name,
google_credentials
):
"""
Get a service account or create it if it does not exist.
Args:
project_id:
The ID of the project the service account is contained in.
account_id... | 6d09a854bb11dffd3cde434a63e7bc43d9c529e2 | 3,624,624 |
def delivery_pricing_api_url():
"""
Delivery Pricing API
"""
return get_parameter("/ecommerce/{Environment}/delivery-pricing/api/url") | 5c7ffad311f8bbeff05da6b488a37d5d6b8dcc97 | 3,624,625 |
def filter_value(entry, values=None):
"""
Returns True if it should be filtered.
Only take calls with filter values in the list provided
if None provided, assume that filter_value must be PASS or blank '.'
"""
if values is None:
return len(entry.filter) != 0 and 'PASS' not in entry.filte... | 57ee5ab67fa07cb8c1379d303e9d636718025f45 | 3,624,626 |
def sample_nonlinear_icp_sim(
dag,
n_samples,
nonlinearity="id",
noise_df=2,
combination="additive",
intervention_targets=None,
intervention="soft",
intervention_shift=0,
intervention_scale=1,
intervention_pct=None,
random_state=None,
pre_intervention=False,
lambda_no... | 572aef9f2533a31921f039ec655f4ef8bd39afd5 | 3,624,627 |
def process_data(expected_keys, data):
"""
Check for any expected but missing keyword arguments
and raise a TypeError else return the keywords arguments
repackaged in a dictionary i.e the payload.
:param expected_keys:
:param data:
:return payload:
"""
payload = {}
for key in exp... | a7d9b87af72d5217cdd6c67ab27986780bea293a | 3,624,628 |
def restore_scores(scores, shape, shift):
"""
Restores scores to original size using linear interpolation.
Arguments:
scores -- original 'compressed' scores
shape -- shape of the restored scores
shift -- sliding windows shift
"""
new_scores = np.zeros(shape)
for i in range(1, scor... | 8b2b42fabd22c2e0e2fc15d5df2e6950863ac531 | 3,624,629 |
def get_mtime_for_page():
"""获取分时数据"""
rps = {}
rps["status"] = True
if request.form.get("symbol") or request.form.get("timestamp"):
symbol = request.form["symbol"]
timestamp = request.form["timestamp"]
data = get_stock_mtime(symbol, timestamp, tdx)
if data:
... | 77be6a37bd44527919d651f81d8ef079282ce8af | 3,624,630 |
def make_song_title(artists: list, name: str, delim: str) -> str:
"""
Generates a song title by joining the song title and artist names.
Artist names given in list format are split using the given delimiter.
"""
return f"{delim.join(artists)} - {name}" | 341db19af517c09633a6ebe37726c79c020f4780 | 3,624,632 |
def changeSamplingRateOfSignal(
data,
oldSamplingFrequency,
newSamplingFrequency,
tmpPath = None,
tmpFileName = 'tmp.wav',
sincWidth = 200,
normalize = False
):
"""
change the sampling frequency of a given signal. similar to @ref
changeSamplingRate(), but does not operate on a saved sound file, b... | 5d6fbbbc223590b0d02d2563d03358666bd7400c | 3,624,634 |
def get_mangled_dataframe(metal_currency_key):
"""
Parameter: The key in Redis.
E.g. XAU-USD
"""
currency = metal_currency_key.split('-')[1]
metal = metal_currency_key.split('-')[0]
df = redis_to_dataframe(metal_currency_key)
# convert usd pricing
if currency == 'USD':
... | 90b69dbc326979199103cce9f0fca5847ac0f602 | 3,624,635 |
def value_to_idx(val_range, unique_values, run_idx):
"""Return the index that belongs to the value at run index.
Parameters
----------
range
unique_values
run_idx
Returns
-------
"""
return np.where(unique_values == val_range[run_idx])[0] | 5e455434825e9d4e14a651b935e5908b3d922c74 | 3,624,636 |
def struct_parse(struct, stream, stream_pos=None):
""" Convenience function for using the given struct to parse a stream.
If stream_pos is provided, the stream is seeked to this position before
the parsing is done. Otherwise, the current position of the stream is
used.
Wraps the erro... | ab2629a7155d1d3f199aff1c706663bc93953675 | 3,624,637 |
def DEFAULT_RENAMER(L, Names=None):
"""
Renames overlapping column names of numpy ndarrays with structured dtypes
Rename the columns by using a simple convention:
* If `L` is a list, it will append the number in the list to the key
associated with the array.
* If `L` is a dictionary,... | 62afcc8538d57ca2181419a13acdd5f307895be1 | 3,624,638 |
def authorizeView(user, identifier):
"""
Returns True if a request to view identifier metadata is authorized.
'user' is the requestor and should be an authenticated StoreUser
object. 'identifier' is the identifier in question; it should be a
StoreIdentifier object.
"""
# In EZID, essentially all iden... | c831d74a229043a308226d6ae8078e5630507ded | 3,624,639 |
from pathlib import Path
def create_absolute_installed_file_path(root_dir, file_path):
"""
Return an absolute path to `file_path` given the root directory path at
`root_dir`
"""
file_path = remove_drive_letter(file_path)
# Append the install location to the path string `root_dir`
return st... | 721f610f65b84456e1755e44eea77e0b98744f47 | 3,624,640 |
def test_doc_add_tag_function(flat_mode):
""" Tests that the @add_tag example from doc (functions only) works """
if not flat_mode:
@function_decorator
def add_tag(tag='hi!'):
"""
Example decorator to add a 'tag' attribute to a function.
:param tag: the 'tag'... | 292707b9ba8a4cde589fde26a23c43d7c2445103 | 3,624,641 |
def sort(reader, buf_size, cmp=None, key=None, reverse=False):
"""
Creates a data reader whose data output is sorted.
Output from the iterator that created by original reader will be
buffered into sort buffer, and then sorted. The size of sort buffer
is determined by argument buf_size.
:param ... | f99f21db52c5c85dfad712ad0e5aeb1e7aa9a432 | 3,624,642 |
def __get_editor_of_statement(uid):
"""
:param uid:
:return:
"""
db_statement = DBDiscussionSession.query(TextVersion).filter_by(statement_uid=uid).order_by(
TextVersion.uid.desc()).first()
db_editor = DBDiscussionSession.query(User).get(db_statement.author_uid)
gravatar = get_profi... | 5edcabe74669711828709ba617dfa2d0409be9bd | 3,624,644 |
def clean_keyword(kw):
"""Given a keyword parsed from the header of one of the tutorials, return
a 'cleaned' keyword that can be used by the filtering machinery.
- Replaces spaces with capital letters
- Removes . / and space
"""
return kw.strip().title().replace('.', '').replace('/', '').replac... | eb8ab983bf60f5d1ca2996dc9568ded252d00479 | 3,624,646 |
from typing import Union
from pathlib import Path
import hashlib
def compute_md5(path: Union[str, Path], chunk_size: int):
"""Return the MD5 checksum of a file, calculated chunk by chunk.
Parameters
----------
path : str or Path
Path to the file to be read.
chunk_size : int
Chunk ... | 9e718630323b002307a54e7d3bbf936b6b94637a | 3,624,647 |
def is_canonical_emoji_sequence(seq):
"""Return true if this is a canonical emoji sequence (has 'vs' where Unicode
says it should), and is known."""
_load_emoji_sequence_data()
return seq in _emoji_sequence_data | 6ccf079ee2904cb3ff370d41c1478b947d3c43ca | 3,624,648 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.