content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import collections
def fol_language():
"""Makes a first-order logic language.
This has:
* Predicate symbols p1, ..., p9, q1, ..., r9.
* Constant symbols a1, ..., a9, b1, ..., c9.
* Variable symbols x1, ..., x9, y1, ..., z9.
Returns:
Instance of `Language`.
"""
def make_symbols(start):
... | 0cf4460412ad8cce3d428e60a116cb5d5ecbcb6d | 3,607,346 |
def is_youtube(url: str) -> bool:
"""Test whether the given URL belongs to one of the recognized YouTube domains."""
host = urlparse(url.strip()).netloc
for domain in domains:
if host == domain or host.endswith('.' + domain):
return True
return False | 980b420095d52142fe29919bf80ad73127191a1f | 3,607,347 |
def tv_emulator(ev, x, y):
"""
This emulates a tv-based device, like the OUYA.
"""
if ev.type == pygame.MOUSEBUTTONDOWN:
return None, x, y
elif ev.type == pygame.MOUSEBUTTONUP:
return None, x, y
elif ev.type == pygame.MOUSEMOTION:
return None, x, y
elif ev.type == py... | 724fc758fd16a3c62eab73f783ae5a9b897cdeb6 | 3,607,348 |
def mean_f(center, width, sun_range=1., model="STIS"):
"""Returns the solar F averaged over the bandpass of a "boxcar" filter,
given its center and full width. F is defined such that pi*F is the solar
flux density.
Input:
center the center of the bandpass in microns.
width ... | a898f76e0f6f0f45cc150ea20567a0762a47cbe0 | 3,607,349 |
def strToRange(s):
""" Convert string to range
"""
return [int(i) for i in s.split(',')] | 970a3a76d72187808aecafecbdcf35ca21e5f781 | 3,607,350 |
def read(filepath):
"""Reads in the file at the specified location"""
hdulist = pyfits.open(filepath)
hdulist.verify('silentfix')
fits_comment = hdulist[0].header.get_comment()
# PyFITS 2.x
if len(fits_comment) > 0 and isinstance(fits_comment[0], basestring):
comments = [val fo... | 81e49f2a93cb24e88c3edf50853ddab3d1490d38 | 3,607,351 |
def get_pr_info(lst_lbl, lst_scr):
"""
calculate PR info;
"""
rc_pt = np.linspace(0, 1, 1001)
rc_pt[0] = 1e-16
prs = []
aps = []
for lbl, scr in zip(lst_lbl, lst_scr):
pr, rc, _ = precision_recall_curve(y_true=lbl, probas_pred=scr)
aps.append(average_precision_score(y_tru... | 72c8e3902c222b30f0efa48fb2a21426dce66691 | 3,607,352 |
def nbest_oracle_eval(nbest, n=None):
"""Return the evaluation object of the best sentence in the nbest list."""
return nbest.oracle_hyp(n=n).eval_ | fe7641f6ccbaae7d85f620f4772e3a8b506880f5 | 3,607,353 |
def _prepare_visible_key_name_for_adapting_to_fe(key_name, key_to_parent_map):
"""Prepare single key for adapting to frontend.
Returns:
Dictionary representation of the field that can be handled by
the next adaptation method like adapt_non_recursive(), e.g.:
{
'field': 'gt_n... | 8c66edf19abd9ed43ebd2a34191d3131b105b4ee | 3,607,355 |
def max_pool_forward_reshape(x, pool_param):
"""
A fast implementation of the forward pass for the max pooling layer that uses
some clever reshaping.
This can only be used for square pooling regions that tile the input.
"""
N, C, H, W = x.shape
pool_height, pool_width = pool_param['pool_height'], pool_param['po... | 3e95afaf9793197d7eebfc0beb1661a74d63c648 | 3,607,356 |
import pkg_resources
def get_package_location(package):
"""Return physical location of a package"""
try:
info = pkg_resources.get_distribution(package)
location = info.location
except pkg_resources.DistributionNotFound as err:
logger.error("package provided (%s) not installed." % p... | 1a3dbe1d2425192a67bd3b7b0ed0f22522ee34ad | 3,607,357 |
def rot_euler(v, xyz):
"""
Rotate vector v (or array of vectors) by the euler angles xyz
https://stackoverflow.com/questions/6802577/python-rotation-of-3d-vector
:param v:
:param xyz: euler angels; tuple of length 3
:return:
"""
for theta, axis in zip(xyz, np.eye(3)):
v = np.dot(np.array(v), expm(np.cross(np... | 2bba71264907d7bc8b792b8f380bdb4825807ca9 | 3,607,358 |
def box_to_unit_interval_np(arr, space):
"""
Rescale array values from Box space to the unit interval. This is
essentially just min-max scaling:
.. math::
x\\ \\mapsto\\ \\frac{x-x_\\text{low}}{x_\\text{high}-x_\\text{low}}
Parameters
----------
arr : nd array
A numpy ar... | a0650024abc7e6624470d6e0adceb6e2c5425637 | 3,607,359 |
def NINJA_data_to_hoft(fname, TDlen=-1, scaleT=1., scaleH=1., Fp=1., Fc=0.):
"""
Function to read in data in the NINJA format, i.e.
t_i h+(t_i) hx(t_i)
and convert it to a REAL8TimeSeries holding the observed
h(t) = Fp*h+(t) + Fc*hx(t)
If TDlen == -1 (default), do not zero-pad the returned ... | 81a95e22f735c8f8637cdfbcfcb4727fc881d0c4 | 3,607,361 |
def reaction_class_from_data(class_typ, class_spin,
class_radrad, class_isc):
""" Build a full-class description including the following useful
descriptors of the reaction class:
typ: type of reaction (e.g., abstraction, addition, migration)
spin: whethe... | 7ab3b7713c252e4dc3f2f9410d0021f24141a901 | 3,607,363 |
def get_day_average_price(fsym, tsym, e='all', try_conversion=True,
avg_type='HourVWAP', utc_hour_diff=0):
"""
Get the current days average price of a currency pair.
Args:
fsym: FROM symbol.
tsym: TO symbol.
e: Default returns average price across all excha... | 5d5467b056bb6bba10f861d183b3feb380180a5c | 3,607,364 |
import pytato.utils as utils
from typing import Union
def logical_or(x1: ArrayOrScalar, x2: ArrayOrScalar) -> Union[Array, bool]:
"""
Returns the element-wise logical OR of *x1* and *x2*.
"""
# https://github.com/python/mypy/issues/3186
return utils.broadcast_binary_op(x1, x2,
... | 5bb60a559231f563d9cf63103fbe56bd26f761c7 | 3,607,365 |
def avoir(self):
"""Make a black and white image of the IR 10.8um channel (320m).
Modeled after mpop.instruments.viirs.ir108
"""
self.check_channels("M15")
data = self["M15"].data
range = (-65 + C0, 35 + C0)
img = geo_image.GeoImage((data, data, data),
self... | 83e66a248a8fac381351cdfc6dad6c077284fb3d | 3,607,366 |
def build_auth_url(additional_scopes=[], client_id=''):
"""Create the OAuth URL for the user-approved scopes."""
user_scopes = ['Read & modify playback.'] + additional_scopes
scopes = []
for scope in AUTH_SCOPES_MAPPING:
if scope['name'] in user_scopes:
scopes += scope['scopes']
... | 9231ff04da4f3289ad0e59baac6b7328fa4201c9 | 3,607,368 |
import pickle
def get_one_hot_encodings(filepath='../data/one-hot.pkl'):
"""
Gets the one_hot encodings of the verses of the Quran, along with mappings of characters to ints
:param filepath: the filepath to the one_hot encoding pickled file
:return:
"""
with open(filepath, 'rb') as one_hot_qur... | f255ba44018ae1d38694ba12ad9e733ac4fb433f | 3,607,369 |
import inspect
def has_self_parameter(func):
"""
Checks whether the given func has a self parameter.
:param func: The func to be checked.
:return: True if the func has the self parameter.
"""
func_args = inspect.getargspec(func).args
return len(func_args) > 0 and func_args[0] == 'self' | 24a1157f87190cbcb19d77f13f018141dfc25ebc | 3,607,370 |
def otherline_from_line(line_dict, filing_number, line_sequence, is_amended, filer_id):
"""
http://initd.org/psycopg/docs/extras.html#hstore-data-type
"""
try:
# Some lines have illegal transaction ids -- longer than 20 characters. Truncate those.
line_dict['transaction_id'] = line_dict[... | 2afe0981de5102d80307bdaa99fae0b42ef90c88 | 3,607,372 |
def create_qc(qubits):
"""Creation of the quantum circuit and registers where the circuit will be implemented.
Args:
qubits (int): number of qubits used for the unary basis.
Returns:
q (list): quantum register encoding the asset's price in the unary bases.
ancilla (int): qubit that ... | 9a50a8e8032e34b9828015c7420806bbe22d16d7 | 3,607,373 |
def unique_slug_generator(instance, new_slug=None):
"""
This is for a Django project and it assumes your instance
has a model with a slug field and a title character (char) field.
"""
if new_slug is not None:
slug = new_slug
else:
slug = slugify(instance.name)
if slug in DO... | c01f490d2065b6b5a3897fad9b5394b570fb1dd2 | 3,607,374 |
def classifier(density):
"""Classify rocks with secret algorithm."""
if density <= 0:
raise ValueError('Density cannot be zero or negative.')
elif density >= 2750:
return 'granite'
elif density >= 2400:
return 'sandstone'
else:
return 'not a rock' | 17eaba4ec43effb7bdb90432fddd55c6f2bf163a | 3,607,375 |
import pickle
def errors(model, Xtest, burnin=500, MC=None, plot=False, thinning=1, returnE=False, loadDict=False):
"""
"""
#xbins = np.linspace(np.min(model.x), np.max(model.x), 200)
ybins = np.linspace(np.min(model.y)*1.2, np.max(model.y)*1.2, 500)
#Xgrid, Ygrid = np.meshgrid(xbins, ybins)
... | 6ac39cb4933cfbe1c4512c200632a87fc93a2799 | 3,607,377 |
def draw_masks(ax, img, masks, color=None, with_edge=True, alpha=0.8):
"""Draw masks on the image and their edges on the axes.
Args:
ax (matplotlib.Axes): The input axes.
img (ndarray): The image with the shape of (3, h, w).
masks (ndarray): The masks with the shape of (n, h, w).
... | c343d90ac6d41b5e73cee9d81c5f5b62152d8cfa | 3,607,378 |
from typing import Union
from typing import Optional
from typing import List
def get_operand_or_result(
op: Operation, arg_def_idx: int, previous_var_args: int,
is_operand: bool
) -> Union[SSAValue, Optional[SSAValue], List[SSAValue]]:
"""
Get an operand or a result.
In the case of a varia... | d0681303641c4c17eb110230fa91f7379bac9b23 | 3,607,379 |
def add_noise(prj, ratio=0.05):
"""
Adds Gaussian noise with zero mean and a given standard
deviation as a ratio of the maximum value in data.
Parameters
----------
prj : ndarray
3D stack of projection images. The first dimension
is projection axis, second and third dimensions a... | b3bc95ae15fd9602ac7126737d5a6818e00463f1 | 3,607,380 |
def delete(cm_id, caller_id, user_id):
"""
Deletes User. For technical and legal reasons only inactive User may
be deleted. Other users may only be blocked.
@clmview_admin_clm
@param_post{user_id,int} id of the User to delete
"""
user = User.get(user_id)
if user.last_login_date or user... | cd80eab295a93f11117f3cf21a20f76d2102c58d | 3,607,381 |
def get_label(Z, V):
"""
Transforms Z_arr into the desired form. Also works if data set is
not contiguous.
"""
xlim = Z.shape[0]
dict_labels = dict(zip(range(V), range(V)))
for i in range(xlim):
Z1 = int(Z[i,0])
Z2 = int(Z[i,1])
Z[i,0] = min(dict_labels[Z1], dict_lab... | e51d21a7f3be8a99bc09e309b944ca0478eb8f69 | 3,607,383 |
def _decode_and_random_crop(image_bytes: tf.Tensor,
image_size: int) -> tf.Tensor:
"""Make a random crop of image_size."""
bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
image = _distorted_bounding_box_crop(
image_bytes,
bbox,
min_object_c... | 8d3cd868e413d5c1df70dae1162c00e670c1ce39 | 3,607,384 |
def read_csv(path_or_buf=None, *args, **kwargs):
"""
A convenience wrapper for _read_multi() that uses pd.read_csv as the
read function.
"""
return _read_multi(
read_function=pd.read_csv,
path_or_buf=path_or_buf,
*args,
**kwargs
) | 204fb8cd1327be486be52b0b9e2b654eebba37b1 | 3,607,385 |
def get_sale_invoice_rows(*args, **kwargs):
"""
获取列表
:param args:
:param kwargs:
:return:
"""
return db_instance.get_rows(SASaleInvoice, *args, **kwargs) | 8f8b927e3d45b126d8dcbac3b4feaf8d35ae284f | 3,607,386 |
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scratch.
# sqlite does not have this failure, so we can use the API.
# For not-sqlite, query information-schema dir... | aaad99b2b2718f5c56e2a0671ae4f5dbfffa94e0 | 3,607,387 |
def vap_internalenergy(temp,pres):
"""Calculate water vapour internal energy.
Calculate the specific internal energy of water vapour using the
IAPWS-97 formulation.
:arg float temp: Temperature in K.
:arg float pres: Pressure in Pa.
:returns: Internal energy in J/kg.
"""
g = va... | 732d4d12d54ee7a5c4c135791b54219a8b485809 | 3,607,388 |
def flatten(lst):
"""Flatten a nested list lst"""
return [i for subl in lst for i in subl] | 5835f05ca6b098c096fdb2bbface034a3c3bee26 | 3,607,389 |
import pathlib
def exists_in_experiment_filestore(path: pathlib.Path) -> bool:
"""Returns True if |path| exists in the experiment_filestore."""
return filestore_utils.ls(exp_path.filestore(path),
must_exist=False).retcode == 0 | 0896439b0fdd411600a9bcddf59f4714a1d194ca | 3,607,390 |
import random
def extract_words(text, word_count):
"""
Extract a list of words from a text in sequential order.
:param text: source text, tokenized
:param word_count: number of words to return
:return: list list of words
"""
text_length = len(text)
if word_count > text_length:
... | f84f8b4148380d6c6e29dc0742e42481dda2d11a | 3,607,391 |
def process_observation_data(station):
"""
This function processes the observation data
using baseline correction and rotation (if needed)
"""
# Validate inputs
if len(station) != 3:
print("[ERROR]: Expecting 3 components!")
return False
# Reorder components if needed so tha... | daeb79e88ad3b5f0159ad2660b513b5a8f36c257 | 3,607,392 |
def subproc_captured_object(*cmds, envs=None):
"""
Runs a subprocess, capturing the output. Returns an instance of
CommandPipeline representing the completed command.
"""
return xonsh.procs.specs.run_subproc(cmds, captured="object", envs=envs) | 01c8bfe1c6a62428b0ac2574d337632108719848 | 3,607,393 |
def numeratorC(weight, y_exp, y_pred):
"""
finds the sums Ti*Pi*wi over the channels.
"""
return weight*K.sum(K.flatten(y_exp)*K.flatten(y_pred)) | c0cd2de21a4268418c2b1e6a9585a7365c0519b3 | 3,607,394 |
import xmlrpc
def start_vm(client, session, vm, params):
"""Start a virtual machine. The virtual machine is created if it does not exists."""
if vm['state'] == 'active':
return { 'changed': False, 'vm_id': vm['id'], 'actions': [] }
actions = []
if vm['state'] is None:
vm['id'] = creat... | 9cce62511016cba8ddca59a024f8929e1d4c4ad0 | 3,607,396 |
def deser(val):
"""
Deserialize from a string representation of an long integer
to the python representation of a long integer.
:param val: The string representation of the long integer.
:return: The long integer.
"""
if isinstance(val, str):
_val = val.encode("utf-8")
else:
... | 0a8e486f2cea255c495820f91fa01911b0df4ad3 | 3,607,397 |
import json
def create_registry(registrydata):
"""
POST /registries
:param registry:
:return:
"""
request_inputs = anchore_engine.services.common.do_request_prep(request, default_params={})
user_auth = request_inputs['auth']
method = request_inputs['method']
bodycontent = request_... | ddc95f57d1e4f46485119b33d88114933b56f65f | 3,607,399 |
from sympy import Rational
def RK44_family(w):
"""
Construct a 4-stage fourth order Runge-Kutta method
**Input**: w -- family parameter
**Output**: An ExplicitRungeKuttaMethod
**Examples**::
>>> from nodepy import rk
>>> print(rk.RK44_family(1))
... | 18782206cbc77c5b64d188169fa6fea362177e29 | 3,607,400 |
import scipy
def arbitrary_rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
# Kudos to
# https://stackoverflow.com/questions/6802577/rotation-of-3d-vector
#import math
#
# axis = np.asarray(ax... | e5416f1874820dfbdb5685fdf2daa099edee25df | 3,607,403 |
def Gaussian(shape=(3, 3), sigma=0.5):
"""
2D gaussian mask - should give the same result as MATLAB's
fspecial('gaussian',[shape],[sigma])
"""
m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m + 1, -n:n + 1]
h = np.exp(-(x * x + y * y) / (2. * sigma * sigma))
h[h < np.finfo(h.... | 2f168af07d7b9787f78d9fa413cd6f723cb871cd | 3,607,404 |
def enableDisableEquipment(enable, names):
# type: (bool, Tuple[String, ...]) -> List[unicode]
"""Enables or disables a Tuple of equipment connections from a
script.
Args:
enable: Set to True to enable equipment connections, or set to
False to disable them.
names: A Tuple of... | 6bb1eca2db62cdabf2748bbe6dcec163e0cf806b | 3,607,406 |
import struct
def get_arg() -> bytes:
"""
This function returns the (pre-encoded) `password` argument to be sent to
the `sudo` program.
This data should cause the program to execute our ROP-chain for printing our
message in an endless loop. Make sure to return a `bytes` object and not an
`str` objec... | 829fbde5c8202ec170850b0e9cff891f9e0f27cc | 3,607,408 |
def delay_frame (delay):
"""Construct a spacer frame with no content that serves as a delay."""
return ( graphics_control_block(delay) +
image_descriptor_block(0, 0, 1, 1) +
chr(LZW_palette_bits) +
chr(1) +
chr(trans_index) +
chr(0) ) | 03b227ad66d8125402f040504c16069747faa152 | 3,607,409 |
def get_latest_version(package_name, test_database=False):
"""
Retrieve the latest version of the given package name from PyPi. Return a version of 0.0.0
if no package version information is found.
:param package_name: A string specifying the package name to interrogate.
:param test_database: A boo... | c977f95a42399d40e6d9e3571f9d945bc726ff5d | 3,607,410 |
import logging
def calc_regional_services(
enduse,
uk_techs_service_p,
regions,
spatial_factors,
fuel_disaggregated,
techs_affected_spatial_f,
capping_val=1
):
"""Calculate regional specific end year service shares
of technologies (rs_reg_enduse_tech... | 7fb703fca501b441fa985d7a0a778905cdbf30cb | 3,607,411 |
from datetime import datetime
def get_daily_demographics_age(tiles: np.array(int), day=datetime(year=2020, month=1, day=27)) -> pd.DataFrame:
"""Fetches daily demographics of age categories
Fetches the daily demographics, age distribution, of the tiles and creates a dataframe of the fetched data.
... | 095395e5ac2529bd502d798d9afaaa2643eaf76f | 3,607,413 |
def estimate_magnitude(paz, amplitude, timespan, h_dist):
"""
Estimates local magnitude from poles and zeros or full response of given
instrument, the peak to peak amplitude and the time span from peak to peak.
Readings on two components can be used in magnitude estimation by providing
lists for ``p... | e79fed699599d665dceb06772173f6768e4486ae | 3,607,414 |
def extract_keypoint_index(scoremap):
""" Extract Scoremap.
# Arguments
scoremap: Numpy aray of shape (crop_size, crop-size).
# Returns
max_index_vec: List of Max Indices.
"""
keypoint_index = np.argmax(scoremap)
return keypoint_index | 3c78c64218b3089b85f151e4328ede6c6ca1ffe2 | 3,607,415 |
def transpose(incoming, conv, nonlinearity, *args, **kwargs):
""" Convenience function to transpose a convolutional layer
and use weight tying
"""
return TransposedConv2DLayer(incoming, conv.input_shape[1],
conv.filter_size, stride=conv.stride,
... | 66489060e981f66a36fabc625ff729135b7f577f | 3,607,416 |
def downbin_spec_err(specHR, errHR, lamHR, lamLR, dlam=None):
"""
Re-bin spectum and errors to lower resolution using :py:obj:`scipy.binned_statistic`.
This function calculates the noise weighted mean of the points within a bin such that
:math:`\sqrt{\sum_i \mathrm{SNR}_i}` within each :math:`i` bin is ... | 9a884ea2e3b9c7136f8f20b1ac8f909f9ca8051b | 3,607,417 |
def timebin_dur_from_vec(time_bins, n_decimals_trunc=5):
"""compute duration of a time bin, given the
vector of time bin centers associated with a spectrogram
Parameters
----------
time_bins : numpy.ndarray
vector of times in spectrogram, where each value is a bin center.
n_decimals_tru... | 00b9b31a3edff1ceeacb389a1f2331e8ae3034c4 | 3,607,418 |
def rgb_to_hex(color):
"""Helper function for converting RGB color to hex code
Args:
color (list): List of R,G,B value
Returns:
str: Hex code for the RGB value
"""
r,g,b = color
#print('%02x%02x%02x' % (r,g,b))
return '#%02x%02x%02x' % (r,g,b) | 9308fa029cb2bfd75495c92a2e145f3439e3b60b | 3,607,419 |
def at(seq, msg, cmd=None, *args, **kwargs):
"""Push a new command"""
return translator(seq + 1, msg + clformat("AT*~a=~s,~{~s~^,~}\r",
cmd, seq, map(iso_str, globals()[cmd.lower()](*args, **kwargs)))) | 1080fb5d044556a31e8a5f3d4786334944c6af7d | 3,607,420 |
def L2(v, *args):
"""Returns the L2 norm of a vector v
INPUTS
=======
v: list
Vector of which the L2 norm to be calculated
*arg: list, optional
Weight vector
RETURNS
========
L2_norm: float
float unless len(v) != len(args[0])
in which case a Value... | fe95415fdfdb433dcf75087b943575bf2b7cee5d | 3,607,421 |
def plot_importances(experiment, n_best=15, sort_by='max', calculator=BuiltinImportance(), fontsize=12):
"""
Visualize feature importances (max, mean and std) of an experiment using a given calculator.
:param experiment: Experiment instance, like lb['012ABC']
:param sort_by: one of 'max', 'mean' and 'st... | 1a51bb609a325e92dab1e5f02f81580f7e58f9de | 3,607,422 |
def sort_queryset(queryset, request, allowed_sorts, default=None):
""" Sorts the queryset by one of allowed_sorts based on parameters
'sort' and 'dir' from request """
sort = request.GET.get('sort', None)
if sort in allowed_sorts:
direction = request.GET.get('dir', 'asc')
sort = ('-' if ... | 7d4ef00e0d345d4636caaa9ca69ade0a09e33ea4 | 3,607,423 |
def privacy(request):
"""
The RMG privacy policy.
"""
return render(request, 'privacy.html', {'admins': settings.ADMINS}) | 218f1f24691420e76d562a0251cfce983036ed60 | 3,607,424 |
from typing import Union
import requests
from bs4 import BeautifulSoup
def get_schedule(day: str, format_: Union[pd.DataFrame, set] = set):
"""
Return NBA matchups on queried date.
Arguments:
----------
day: str
Date for which to get schedule.
Format = YYYY-MM-DD
format_: Uni... | 8b29d175d1a1afab302a054793a101941f4027c6 | 3,607,425 |
def match(text):
"""
Parse calendar entry
:param text: The entry to parse
:return: A pair of description, project key
"""
return MATCHER.match(text) | 6e5124cf13656661adb8e2f952ea65542f65197e | 3,607,426 |
def partial_pullback(b, c, d, b_d, c_d):
"""Find partail pullback."""
check_homomorphism(b, d, b_d, total=False)
check_homomorphism(c, d, c_d, total=False)
bd_dom = subgraph(b, b_d.keys())
cd_dom = subgraph(c, c_d.keys())
bd_b = {n: n for n in bd_dom.nodes()}
cd_c = {n: n for n in cd_dom.n... | 2e71a8f7f7664e294380cf446ac425f2766ef595 | 3,607,427 |
def get_colormap_lut(name='flame'):
"""Get lookup table from one of pyqtgraph's gradient editor's presets.
Result is suitable for ImageItem.setLookupTable. Gradient names listed in
Gradients.keys(). Not sure how 'hsv' mode works.
"""
gradient=Gradients[name]
ticks=gradient['ticks']
v=np... | d6bc069c8a54538389995e6dd902ab309b2f7c69 | 3,607,428 |
from typing import Any
import json
async def get_messages(number: str) -> Any:
"""
get messages
"""
response = await run_signal_cli_command(["-u", quote(number), "--output=json", "receive"])
return [json.loads(m) for m in response.split("\n") if m != ""] | 8ec57bff19abce43bd96b48391e3d1f0470e70f0 | 3,607,430 |
import gzip
import pickle
def read_pickle(fname, compress=True):
"""
read analysis from pickle file
"""
if compress:
with gzip.open(fname, "rb") as f0:
return pickle.load(f0)
else:
with open(fname, "rb") as f0:
return pickle.load(f0) | 040976647b637ee08f33094e13d3a19605495463 | 3,607,431 |
import random
def _k_init(X: np.ndarray, n_clusters: int, random_state=None) -> np.ndarray:
"""Initialize kmeans centers by picking a random point as the center"""
return np.array([X[random.randint(0, len(X) - 1)]
for i in range(n_clusters)]) | b1e117c8dbe6d3c3392dd76f7d10872f343a2795 | 3,607,432 |
def post_create(request):
"""
View function for post-create page of site.
Param request post form data.
Return post create view.
"""
user = get_object_or_404(User, pk=request.user.id)
formData = None
form = PostForm()
check_route("post", request.META.get("HTTP_REFERER"), request)
... | 6f5c4caeebbbace23dc5a91c25fbb8c385c3a561 | 3,607,433 |
def extract_path_from_filepath(file_path):
"""
ex: 'folder/to/file.txt' returns 'folder/to/'
:param file_path:
:return:
"""
st_ind=file_path.rfind('/')
foldern = file_path[0:st_ind]+'/'
return foldern | 7014ac6d4fa47edff3315f7e23688cfe2e28a820 | 3,607,434 |
def flip_coordinate_system(q):
"""
as far as i understand it is assumed that we are already in a different coordinate system
so we first flip the coordinate system to the original coordinate system to do the original transformation
then flip coordinate system again to go back to the flipped coordinate s... | a15fe27e507d8129d2ad0d7cc28c0a033dcf9e5e | 3,607,435 |
def fname_to_string(fname):
"""Return given file as sring
Parameters
----------
fname : str
absolute path to file.
"""
with open(fname) as fid:
string = fid.read()
return string | f9a3f94dc4a63c27cadb5c5f9a41eaa942332937 | 3,607,436 |
def index():
"""
Display the home page.
:return: Index template.
"""
user = g.user # get the currently logged in user
return render_template("index.html",
title='Home',
user=user) | a1356d31270bdfd79e6259eb88b563a786902f90 | 3,607,438 |
from typing import Tuple
def create_pca_features(x: pd.DataFrame,
x_train: pd.DataFrame,
x_test: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
""" Compute PCA of given full/training/test data
PCA is fitted on the full dataset x ... | 866453fa63aa8181c6d2d48166d55d641fe3b038 | 3,607,440 |
def global_color_table(color_depth, palette):
"""
Return a valid global color table.
The global color table of a GIF image is a 1-d bytearray of the form
[r1, g1, b1, r2, g2, b2, ...] with length equals to 2**n where n is
the color depth of the image.
----------
Parameters
color_depth:... | 4fc8b0cad668724b0a6d5735f70dcb16b6b9b140 | 3,607,442 |
def feature_extraction_Step(all_s,all_id,all_label,config):
"""
Extract features for all signals included in all_s
Args:
all_s (list of numpy arrays): list of signals from which features are extracted.
all_id (list of strings): corresponding list of IDs for signals in all_s.
all_labe... | 729d942e1a5d9b9774594506949aaa918192e944 | 3,607,443 |
def match_rule_based():
"""
- Create Keyword RuleBased
:return:
"""
item = request.get_json(force=True)
key = CutId(_id=ObjectId()).dict()['id']
item['access_token'] = mango_channel
item['id'] = key
db.insert_one(collection, item)
del item['_id']
return jsonify(item) | 41c615912f505c15b2a12d0992e361e32a47f6c4 | 3,607,444 |
def _create_installation(iid):
"""Send a request to create an installation (ID: iid). Return the object
ID associated with it"""
data = {
"deviceType": "android",
"appVersion": settings.YIKYAK_VERSION,
"parseVersion": settings.PARSE_VERSION,
"appName": "Yik Ya... | 0ca2d19083f7b7d0c1d200bef99b8ad1c1efa6e6 | 3,607,445 |
def _optimize_shape(count, width_height_aspect_ratio=1.0):
"""Computes the optimal X by Y shape of count objects given a desired
width-to-height aspect ratio.
"""
N = count
W = np.arange(1, N).astype(np.uint32)
H = np.ceil(N / W).astype(np.uint32)
closest = np.argmin(np.abs((W / H) - width_h... | 3ddc8b636e8d0d1d51bfa7a2e4e2ae915bf9a8a8 | 3,607,446 |
def parcellate_func_combine_hemis(lh_func, rh_func, lh_parcel_path, rh_parcel_path):
"""
#Function that takes functional data in the form <num_verts, num_timepoints> for
#both the left and right hemisphere, and averages the functional time series across
#all vertices defined in a given parcel, for ... | 5e81489c7b961af38e02ea3490afc03549a7b845 | 3,607,447 |
import numpy
def grpCompose(f1,f2):
"""
compose two elements of group SE(3).
f1.f2 = [R1*R2, (R1*t2)+t1]
where, R1,R2 are rotation matrices and t1,t2 are translation vectors.
But note that the function expects f1 to contain rotation vector instead
of rotation matrix.
Inputs:
f1 -> Elem... | c807eba92c0b8f1504e2f4229be8b2ac7e564020 | 3,607,448 |
def get_rfmid_loaders(
size,
batch_size=64,
num_workers=8,
):
"""get dataloaders for RFMiD dataset, and also return number of labels"""
loaders = []
for split in ["train", "valid", "test"]:
tfms = get_tfms(size=size, augmentation=split == "train")
D = RFMiD(
split=spl... | d632e57aafb4ae16e90b3a36753f5d62a590f4b5 | 3,607,449 |
import torch
def upsample_flow(flow, mask):
""" upsample a flow field """
flow = flow * torch.as_tensor([8.0, 8.0, 1.0]).to(flow.device)
return cvx_upsample(flow, mask) | 5eb436d902b778d99079287439d123c6506b689b | 3,607,451 |
def get_workspace_attribute(ns: str, ws: str, attribute_name: str):
"""
Get value of an existing attribute.
:param ns:
:param ws:
:param attribute_name:
:return:
"""
attributes = _query_workspace(ns, ws)['attributes']
if attribute_name not in attributes:
logger.error(f"Queri... | bef84c2996b4494e6869e4690eee63c0a1b02852 | 3,607,452 |
import httpx
def parse_url(client: httpx.Client, url: str, *, parse_seperate_2p: bool = False) -> Level:
"""
Parses the level data from an url, uses download_level to download with parse_rdzip to parse.
Args:
client (httpx.Client): httpx client to use for the request
url (str): Url for th... | 9621b7967dfb4bb100250f866e91ac249e8f0330 | 3,607,453 |
import math
def arclen(angle, radius, rad=False):
"""Calculates the size of an arc of a circle"""
if rad:
angle = math.degrees(angle)
return (angle / 360) * (2 * math.pi * radius) | c94e3a0f838a4ee635da4997da3ac89867d03366 | 3,607,454 |
def testapp_with_base64(settings, user_format):
"""Fixture for setting up a Swagger 2.0 version of the test testapp."""
settings['pyramid_swagger.swagger_versions'] = ['2.0']
settings['pyramid_swagger.user_formats'] = [user_format]
return App(main({}, **settings)) | 8fdd5b835206f6f943d83243bbf1ea21705278b9 | 3,607,455 |
from typing import Callable
from typing import List
def search_result(_: Callable, result: List[FAMovie]) -> Keyboard:
"""
Keyboard for results of a movie query.
"""
buttons = [
[
Button.inline(
movie['title'],
b'film_' + movie['id'].encode('utf8')
... | 6bc6c903a1dd4817929b4d864ff30a52cb995649 | 3,607,456 |
def import_obj_file(file_path, force=True, **kwargs):
"""
Imports OBJ file into current DCC scene
:param file_path: str
:param force: bool
:param kwargs: keyword arguments
:return:
"""
if not is_plugin_loaded('objexport.mll'):
load_plugin('objexport.mll', quiet=True)
kwargs... | bfd8f56855c6da9695d9498aabaaba1aed9aa306 | 3,607,458 |
def translate(seq):
""" Translate a DNA sequence into protein. """
# Make sure sequence is upper case
seq = seq.upper()
# Find start codon
i = 0
while i < len(seq) + 2 and seq[i:i+3] != 'ATG':
i += 1
# Translate until the stop codon or end of string
prot = []
while i < len... | 2c04af772a3b6bda6b77d3c6ae1c4f507e6292af | 3,607,459 |
def get_number_of_elements(scaledArr, threshold=2e-4):
"""
Computes the number of elements displayed on a image, using a threshold.
Parameters
---------
scaledArr : ScaledArray
Contains the data of interest
Returns
---------
NdArray, Number :
Returns the number of e... | 1e8ca4f871c7cc2347cb495374cdba443439b18b | 3,607,460 |
from typing import Callable
def prepare_image(img_array: npt.ArrayLike, _model_preprocess: Callable) -> npt.ArrayLike:
"""Prepare any image so that it can be fed into a model predict() function.
This includes:
- converting to RGB channels
- resizing to the appropriate image size expected by the model... | 536660fed746e40b76fbaa87a5e86d1f5beb2e35 | 3,607,461 |
import torch
def precision(label_pred, label_gt) -> float:
"""
Computes the precision
"""
with torch.no_grad():
prediction_bin = torch.argmax(label_pred, dim=1)
TP = torch.mul(prediction_bin, label_gt).sum()
FP = torch.mul(prediction_bin, 1 - label_gt).sum()
PC = float(... | 039e4c938d5ef6fd27ecda1d1bf027863b973060 | 3,607,462 |
from typing import Tuple
def _normalize(img: np.ndarray, result_range: Tuple[int, int] = (0, 255)) -> np.ndarray:
""" Normalizes given image by performing simple interpolation to given range. """
return np.interp(img, (img.min(), img.max()), result_range).astype(np.uint8) | 8d28c4ba21f3e32a1be994f6838bc49d5feb90d9 | 3,607,463 |
import hashlib
def get_hashes(binary):
"""Return md5, sha1 and sha256 hashes of input byte string."""
hash_dict = dict()
for hash_type in ['md5', 'sha1', 'sha256']:
if hash_type == 'md5':
hash_alg = hashlib.md5()
elif hash_type == 'sha256':
hash_alg = hashlib.sha256... | 0005a1446b6f58bb6cc6227428a304b0894e6947 | 3,607,464 |
def attach_xunit_results(file: str) -> BuiltInCommand:
"""
Create an Evergreen command to parse results in XUnit test results format.
:param file: A .json file to parse and upload.
"""
params = {"file": file}
return BuiltInCommand("attach.xunit_results", params) | e8b305a083707dadcfd5b23733c1a94252cc1732 | 3,607,465 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.