content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fetch_items(parent_key, valid_flag=None):
"""
Fetch the items by parent_key
:param parent_key|str:
:rtype list of Registry:
"""
query = Registry.all()
if parent_key is not None:
query.filter("parent_key =", parent_key)
if valid_flag is not None:
qu... | 89715533cb5edc28c6c15daaf9047772a4634456 | 3,600,918 |
from typing import Sequence
def shard_args(devices: Sequence[xb.xla_client.Device],
indices: Sequence[Sequence[Index]],
args) -> Sequence[Sequence[xb.xla_client.Buffer]]:
"""Shard each argument data array along its leading axis.
Args:
devices: sequence of Devices mapping replica... | a805a542d4b3e79997900b25dfcd40216ab57401 | 3,600,920 |
def blog_get_mkd_attachment(post):
"""
Attempts to find a vimpress tag containing a URL for a markdown attachment and parses it.
@params post - the content of a post
@returns a dictionary with the attachment's content and URL
"""
attach = dict()
try:
lead = post.rindex("<!-- ")
... | f005ec7b44a3beb0016ab37df457800f036326fe | 3,600,921 |
def algo2(x,y):
"""
Trouve le nombre de carres dans deux listes pour chaque absisse
Args:
x (list): liste des cordonnees en x
y (lsit): liste des coordonnees en y
Returns:
int: Nombre de carres
"""
liste_x = []
liste_y = []
resul = 0
'''Crée une liste qui co... | d2e1c47f98c912fff3f02f759176b81b479ca659 | 3,600,922 |
def setop2d_functor(op):
"""Return a binary function that will perform the passed 1-dimensional set operation on 2-dimensional array arguments.
"""
if op not in (np.intersect1d, np.union1d, np.setdiff1d):
raise ValueError
def setop2d(a, b):
# inspired by https://stackoverflow.com/questi... | 2f4da344f875df22b15b1a441b05ce60f946f339 | 3,600,923 |
import joblib
from pathlib import Path
def _test_clean():
"""
Ordinal Encoding for Test Categorical Columns.
Yields
------
test_clean: 'datasets/test_clean.csv'
Returns
-------
test_clean.
"""
test_set = pd.read_csv('datasets/test_set.csv')
cat_data = test_set[CA... | 76174aa63f9eb576008b97d74ba0e0cb19888fd0 | 3,600,924 |
def compose_tbl_filename_from_config(table_cfg, default=None):
"""compose a file name based on a table config.
This function calls ``compose_tbl_filename()``.
Parameters
----------
table_cfg : dict
A table config
default : dict, optional
A default config
Returns
-----... | 08865e36201b843c134a2bdb9cb1d01433cbb839 | 3,600,925 |
def abbreviate_agency(agency_name):
""" Abbreviate the name of the agency for storage. """
return NAME_TO_ABBR[agency_name] | cdc1fd7be6417bf2a488e95b00477c0180bbec3a | 3,600,926 |
def exp_decay_k(x, width=1., height=None, mode="causal"):
"""
Exponential decay kernel function
Normalized by area if ``height=None`` (if possible), otherwise `height` is the value at 0.
Mode determines value for ``x<0``:
- ``'causal'`` - it's 0 for ``x<0``;
- ``'step'`` - it's... | b624cf6951e1ceb3458cb4c857d284a084ff2aaa | 3,600,927 |
def check_board(board):
"""
This function is to check if the board is in correct format
The length of the board must be 9 (Rows)
Each row must have 9 elements (Columns)
Each element must be between 1 - 9
"""
check_if_the_board_is_correct = True
if len(board) == 9:
... | f5940470c6158bfd500aca40a9f89c715d8592ac | 3,600,928 |
import re
def remove_url(txt):
"""Replace URLs found in a text string with nothing
(i.e. it will remove the URL from the string).
Parameters
----------
txt : string
A text string that you want to parse and remove urls.
Returns
-------
The same txt string with url's removed.
... | 8d1b8b89cb65ca7761c093dc388d1f19729137e7 | 3,600,929 |
import time
def findLoadOnBus(mirror, Busnum, Id=None):
"""Find first load on bus unless Id specified
Note that Ids are typically a strings i.e. '2'
"""
tic = time.time()
if not mirror.searchDict:
for x in range(len(mirror.Load)):
if mirror.Load[x].Busnum == Busnum:
... | 1b81f7495b5ea5fe060d7eead92db10510b76c97 | 3,600,930 |
def get_timestamp_drop_sql(variant):
"""
Generate a list of statements to drop the timestamp update triggers
"""
sql = []
if "postgres" in variant:
sql.append("DROP FUNCTION IF EXISTS update_history_update_time() CASCADE;")
else:
for operation in ["INSERT", "UPDATE", "DELETE"]:... | 0d64fc2ae8b2678f87cc02d1448f11e824b79bd9 | 3,600,932 |
def _check_proper_permutation(a):
"""
Check to see if the matrix has been properly permuted.
This should be redundent to what is already built into 'fix_top'.
Parameters
----------
a : numpy.ndarray
A matrix.
Returns
-------
bool
"""
t = len(a)
for ind in range... | c715e41eb8ef68add832b7a9e7a082ceba25ad88 | 3,600,933 |
def get_package_format_names_with_distros():
"""Get names for package formats that support distributions."""
return get_package_format_names(lambda k, v: "distribution" in v) | b9e3f03fa4ee9742b8c7bd81686727b5e687352e | 3,600,934 |
def distance_PBC(a: np.ndarray, b: np.ndarray, lattice: np.ndarray) -> float:
"""Compute the distance between a and b on the lattice with periodic BCs.
Parameters
----------
a, b : np.array
points in cartesian coordinates
lattice : np.array
lattice to use to compute PBC
Returns... | 4bedf4690c0f975c71b85e86ae601b340baf3277 | 3,600,935 |
def release_gamepad_input() -> None:
"""release_gamepad_input() -> None
(internal)
Resumes normal gamepad event processing.
"""
return None | fe4ea812ba64d50dec7d67c85f93199af8a27b30 | 3,600,936 |
def pretty_print_fmt_containers(containers, args):
"""
Pretty print container data in regular long form, displaying all data.
:param containers: The containers found from docker ps.
:type containers: list
:param args: Parsed arguments from cli.
:type args: <Namespace> obj
"""
selected_i... | 1c75181ac4fb6e833b790ba0bf6dc1cdaec42e58 | 3,600,937 |
def StyleGAN(const_shape, resolution, n_dense=2, n_styles=5, middle_input_synth=None, microstyle_layer=6):
"""
:param const_shape:
:param middle_input_synth: None - full network; 8, 16, ... - input resolution
:return:
"""
def G_mapping(input_, truncation_psi, mapping_layers, dlatent_broadcast, ... | 54ebe63adff29c791655866619b4d0d4cea37734 | 3,600,938 |
def _FetchMapTile(url):
"""Fetches and returns a tile, given an url.
Args:
url: the exact url of the tile to fetch.
Returns:
The tile bitmap.
"""
try:
fp = urllib.urlopen(url)
f = StringIO.StringIO(fp.read())
im_tile = Image.open(f)
im_tile.load()
except IOError, e:
im_tile... | a2053be7c91b1581315cef744348e9e499388fdb | 3,600,939 |
def _bin_str_to_int(bin_str):
"""
This function returns integere value extracted from binary string of
length 16.
:param bin_str:
:return:
"""
if len(bin_str) <= 16:
return int(bin_str, 2)
else:
None | 42ea2d6858d9e41f0dcffb9711ea287c8d051f07 | 3,600,940 |
def get_FN026_cache(lake=None):
"""Return a dictionary of dictionaries that reference the spaces
available for each creel.
useage:
fn026 = FN026_cache[prj_cd][space_code]
"""
FN026_cache = {}
if lake:
spaces = FN026.objects.filter(creel__lake__abbrev=lake).select_related("creel")... | 8bbb6ad1a9fdc244658ee21b7ddb35b7cdefa4b0 | 3,600,941 |
from datagears.core.stores import FeatureStore
def feature_store() -> FeatureStoreAPI:
"""Default feature store fixture."""
return FeatureStore() | 2611e0fdac74c722d7b0690416dd8c2f63fe5281 | 3,600,942 |
def str_to_bytes(s):
"""convert string to byte unit. Case insensitive.
>>> str_to_bytes('2GB')
2147483648
>>> str_to_bytes('1kb')
1024
"""
s = s.replace(' ', '')
if s[-1].isalpha() and s[-2].isalpha():
_unit = s[-2:].upper()
_num = s[:-2]
elif s[-1].isalpha():
_unit = s[-1].upper()
... | 71bef1d7a81fad44a00deb268fba83dac1ed633e | 3,600,943 |
import sympy
def guard(clusters):
"""
Return a ClusterGroup containing a new PartialCluster for each conditional
expression encountered in ``clusters``.
"""
processed = ClusterGroup()
for c in clusters:
free = []
for e in c.exprs:
if e.conditionals:
... | 1dc3f1f922b65b493a426f9424dd441044a921c5 | 3,600,944 |
def select_first_node(g):
"""
:param g: the graph
:return: the first node of the node sequence based on which the graph will be partitioned. We select the first node
as the node which has the lowest degree
"""
all_degrees = []
node_list = list(range(0, len(g)))
for node in node_list:
... | 769a36437e38b19984f88f510b544c22df984106 | 3,600,945 |
def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra):
"""
Same as `django.core.urlresolvers.reverse`, but optionally takes a request
and returns a fully qualified URL, using the request to get the base URL.
"""
if format is not None:
kwargs = kwargs or {}
... | d1048fe8f08a6a23b8ed00fed47b4d10012a670b | 3,600,947 |
def get_subsequences(sequence):
"""
Get length k-1 subsequences of length k sequence
>>> get_subsequences((('A', 'B'), ('C',)))
[(('A', 'B'),), (('A',), ('C',)), (('B',), ('C',))]
>>> get_subsequences((('A', 'B'), ('C',), ('D', 'E')))
[(('A', 'B'), ('C',), ('D',)), (('A', 'B'), ('C',), ('E',)),... | 7f25a3339d7b73eda1d56b7c4cb7941adc17adad | 3,600,948 |
import scipy
import numpy
def deleterowcol(A: scipy.sparse.csc_matrix, delrow: numpy.ndarray,
delcol: numpy.ndarray) -> scipy.sparse.csc_matrix:
"""
Delete the specified rows and columns from csc sparse matrix A.
Assumes that matrix is in symmetric csc form!
Parameters
---------... | 0d62c07226eb7cf10a0ff0635d3c80be4850d23c | 3,600,949 |
import math
def determine_camera_orientation(obj_pos, gantry_pos):
"""
Calculates the orientation of the camera for a given object position and
gantry position.
obj_pos: object position in world frame. numpy array of size (3,), in cm
gantry_pos: gantry position in world frame. numpy array of size ... | 97fc80c1a1fdeea22e62709557eaee460dbac0a7 | 3,600,950 |
from typing import List
def get_all_duplicates(df: pd.DataFrame) -> List:
"""Find the subject ids of all subjects where the `iauname` metadata field is the same as one or more other subjects
Note: classifications.csv only lists subjects with at least one classification, so run this often.
Args:
... | 700d0088ff11fc631b65a07e711411b375245b2b | 3,600,952 |
def expand_line(line, var_dict):
"""
Expand one line of text by substituting environment
and user variables, as well as variables in 'var_dict'.
"""
line = expandvars(expanduser(line))
if "$" not in line:
return line
for key, val in var_dict.items():
line = line.replace(var_r... | e48f73c9641789f690c385d3e61e166d6c64a33e | 3,600,953 |
def publicKeyEncrypt(recipientKeyfile, message):
"""
Applies public key (hybrid) encryption to a given message when supplied
with a path to a public key (RSA in PEM format).
"""
# Load the recipients pubkey from a PEM file
with open(recipientKeyfile, 'rb') as f:
recipientKey = RSA.impor... | 6cdc0a4b39a7a1ce418dc5973fff748fbac6bf33 | 3,600,954 |
def chroma_to_tonnetz( C ):
"""Transforms chromagram to Tonnetz (Harte, Sandler, 2006)."""
N = C.shape[0]
T = np.zeros((N,6))
r1 = 1 # Fifths
r2 = 1 # Minor
r3 = 0.5 # Major
# Generate Transformation matrix
phi = np.zeros((6,12))
for i in range(6):
for j in ran... | 92b461b1d5cecd77296afcb5580ad31a77ef509d | 3,600,956 |
def generate_aliases(aliases, cfg):
"""Generate aliases according to command line and level generation."""
def process(aliased, what, method):
checking = {k: method(f) for k, f in what.items()}
if all_unique_values(aliased, checking):
return checking
return what
def remo... | 3e954c78bc12ec42e7e013a1c917bc14a578c007 | 3,600,957 |
def init_grid_hdf(init_region, h5file, overlap_thresh, crd_sys, intr_prms=None, base_grp="rapidpe_grids"):
"""
Set up a new HDF5 file (h5file), truncating any existing file with this name. A new 'folder' called 'base_grp' is set up and the initial region with attribute 'overlap_thresh' is set up under it.
"... | a700ad338d5469cd5c44704f14ed14dbe5d76908 | 3,600,958 |
def integrated_time(sampler,w, low=10, high=None, step=1, c=2, full_output=False,
axis=0, fast=False):
"""Estimate the integrated autocorrelation time of a time series.
This estimate uses the iterative procedure described on page 16 of
`Sokal's notes <http://www.stat.unc.edu/faculty... | 10ae57c452ce0ce94be9cc17456e30a52fa508b3 | 3,600,959 |
def grasp_dataset_rotation_to_xyz_theta(rotation, verbose=0):
"""Convert a rotation to an angle axis theta specifically for brainrobotdata
From above, a rotation to the right should be a positive theta,
and a rotation to the left negative theta. The initial pose is with the
z axis pointing down, the y ... | a8ebc763d700f24ba958c3f8878f03363d4ee147 | 3,600,960 |
def _get_three_wdr_with_flag_group_and_shift(asm_str):
"""decode the full BN standard format with wd, ws1 and optional flag group and
possibly shifted rs2 (e.g.: "w21, w5, w7 >> 128")"""
substr = asm_str.split(',')
if not (len(substr) == 3 or len(substr) == 4):
raise SyntaxError('Syntax error in... | 19f206d83ce25e3b4ee1208e45aec7c9da3c8f54 | 3,600,961 |
def _logsumexp_and_conditionalprobs(array):
"""return logsumexp and conditional probabilities from array a
that has the same shape as the discrete data in dummy-representation"""
exp_shifted, a_max = _exp_shiftedmax(array, axis=1)
summed = np.sum(exp_shifted, axis=1, keepdims=True) # entries always > ... | 5c6a56bf927089d423244a91966db82d53939e25 | 3,600,962 |
def _flatten(coll):
""" Flatten list and convert elements to int
"""
if isinstance(coll, list):
return [int(a) for i in coll for a in _flatten(i)]
else:
return [coll] | a6f1dee42a5c881e4cf4496283f248a230f38465 | 3,600,963 |
def random_rotation(patch, low_bound=5, high_bound=89, verbose=0):
"""
Rotates randomly the input, angle between low_bound and high_bound.
:param patch: List of 2 or 3 inputs (ndarrays) [image, mask, (weights)]
:param low_bound: Int, lower bound of the randomly selected rotation angle.
:param high_b... | b4bc8fa109e2832e67ae0ab4f56069a81ad473b1 | 3,600,964 |
def augment_parser(parser):
"""Augment parser from sequential wrapper with parallel wrapper"""
group = parser.add_argument_group("Parallel Options", "Configuration of parallel execution")
group.add_argument(
"--threads",
type=int,
default=1,
help="Number of threads to use fo... | 481e0edc9e8d90ccbc5f0d71ef201ccd9ac23a01 | 3,600,965 |
from typing import Iterable
from typing import Dict
def vlad_histograms(images: Iterable[str], data: DataSetBase) -> Dict[str, np.ndarray]:
"""Construct VLAD histograms from the image features.
Returns a dictionary of VLAD vectors for the images.
"""
batch_size = 4
vlads = context.parallel_map(
... | 88f1c851915126cbe49cdf411d994afab287de18 | 3,600,966 |
def get_local_absolute_jitter(frequencies, p_floor, p_ceil, max_p_factor):
"""Given a sequence of frequencies, and some period conditions,
compute the local absolute jitter, as per
https://royalsocietypublishing.org/action/downloadSupplement?doi=10.1098%2Frsif.2010.0456&file=rsif20100456supp1.pdf
Args... | 3558c35fd9a1358c3220e32ddeaa78a8c56713d3 | 3,600,967 |
def impute_times(final, times_open, times_closed, columns, imputation_method="mean"):
"""
Impute open work items times with different methods
:param final: Complete preprocessed dataframe
:param times_open: Dataframe of work items that are not closed
:param times_closed: Dataframe of work items that... | b176045cbc8bda516b2248f61db439cfad3f9a04 | 3,600,968 |
def complete_line(tile, row, tiles):
""" Complete the line of tiles """
line = [tile]
# Search before the start until we can't find any more
try:
if row:
for x in xrange(tile[2] - 1, MIN_X - 1, -1):
line.append(find_tile(x, tile[3], tiles))
else:
... | 8a7cb1a2fd5991243f0c80ea829579aa3f59d782 | 3,600,969 |
def to_float_hours(hours, minutes, seconds):
""" (int, int, int) -> float
Return the total number of hours in the specified number
of hours, minutes, and seconds.
Precondition: 0 <= minutes < 60 and 0 <= seconds < 60
>>> to_float_hours(0, 15, 0)
0.25
>>> to_float_hours(2, 45, 9)
2.7... | f94f37585929fc45f4b417ab63ca9b7b501a2e57 | 3,600,972 |
def soft_round_conditional_mean(inputs, alpha):
"""Conditional mean of inputs given noisy soft rounded values.
Computes g(z) = E[Y | s(Y) + U = z] where s is the soft-rounding function,
U is uniform between -0.5 and 0.5 and `Y` is considered uniform when truncated
to the interval [z-0.5, z+0.5].
This is des... | e473d5fce4e13e5618016fa82c2d6fa7eb9da1d2 | 3,600,973 |
import string
def get_abbr_ratio(text, known_abbreviatures=None):
"""Returns the percentage of dissambiguated abbreviations of the text.
INPUT: Textual data, [Abbreviatures already identified]
OUTPUT: Percentage of identified abbreviatures"""
spacy.prefer_gpu()
nlp = spacy.load('en_core_sci_md')
... | 7a5315e2e840b0e00c5147410f24780b024e356c | 3,600,974 |
def print_policy_analysis(policies, game, verbose=False):
"""Function printing policy diversity within game's known policies.
Warning : only works with deterministic policies.
Args:
policies: List of list of policies (One list per game player)
game: OpenSpiel game object.
verbose: Whether to print po... | d899fe3be974e15a9bb3bfe9a22f36e025d756e5 | 3,600,975 |
import re
def decode_html(html_str):
"""Un-escape or decode HTML strings to more usable Python strings.
From here: http://wiki.python.org/moin/EscapingHtml
"""
return re.sub('&(%s);' % '|'.join(name2codepoint),
lambda m: unichr(name2codepoint[m.group(1)]), html_str) | 3995e9f158d7e91e2a67bca4081d55cd696a4bb7 | 3,600,976 |
import torch
def get_pose_estimation_prediction(config, pose_model, image, centers, scales, transform, device):
"""Predict the 2D human pose using the hrnet model
Args:
config ([type]): [description]
pose_model ([type]): [description]
image ([type]): [description]
centers ... | e26b7b59dd38d0b823d7ebb31b935321367ca8b9 | 3,600,977 |
def fit_simulaid(phi):
"""
DEPRECATED AND WORKING FOR SMALL NUMBER OF SAMPLES
--
Fit theta such as:
phi_i = theta * i + phi_0 (E)
Solving the system:
| SUM(E)
| SUM(E*i for i)
that can be written:
| a11 * theta + a12 * phi_0 = b1
| a21 * theta + a22 * ph... | 98a9bf064e56a48312170a8c32e032654317d40f | 3,600,978 |
def default_figure(climate_data: pd.DataFrame, column: str) -> go.Figure:
"""
Default figure generation
Args:
climate_data: DataFrame with
column: Which column of the data should be displayed
Returns:
plotly Figure object
"""
fig = go.Figure(
data=[
go... | 3b8efdf3751c3d4c1448f505ec739eab1e2bfafe | 3,600,979 |
def _fpgrowth_filter(concept, winlen, max_c, min_neu):
"""
Filter for selecting closed frequent items set with a minimum number of
neurons and a maximum number of occurrences and first spike in the first
bin position
"""
intent = np.array(concept[0])
keep_concept = (min(intent % winlen) == 0... | 89e1c8e265b9b2213dd260878463b3618c0d0d41 | 3,600,981 |
from typing import List
import numba
def multiplicative_variance_trees(
X: List[np.ndarray],
y2: np.ndarray,
*,
q: List[float]=np.r_[:1:11j][1:-1],
num_trees: int,
max_depth: int,
min_gain: float,
learning_rate: float=0.3,
min_child_size: int=1000,
threads: bool=True
):
"""... | 66c1825db1a86926e7526d632d37c97add7c5504 | 3,600,982 |
def _callable_tabular_policy(tabular_policy):
"""Turns a tabular policy into a callable.
Args:
tabular_policy: A dictionary mapping information state key to a dictionary
of action probabilities (action -> prob).
Returns:
A function `state` -> list of (action, prob)
"""
def wrap(st... | 302081ec400101b63351e699f0dace34b1cf3e8f | 3,600,983 |
def _create_raid_adapter(node):
"""Create RAID adapter info on a RAID controller.
:param node: an ironic node object.
:raises: IRMCOperationError on an error from python-scciclient.
"""
irmc_info = node.driver_info
target_raid_config = node.target_raid_config
try:
return client.el... | 164c335d4057e237329bc7f3e9940a800077b10d | 3,600,985 |
def orthogonal_directional(vector, count=1):
"""
"""
dimensionality = len(vector)
subspace_basis = []
if vector[-1] != 0:
identity = np.eye(dimensionality - 1, dimensionality)
else:
idx = np.nonzero(vector)[0]
identity = np.eye(dimensionality, dimensionality)
ide... | 379c198f881ea6d1d7b68aaf29f70ff5037813bb | 3,600,986 |
def open_nb(name: str, src: str) -> nbformat:
"""
Open notebook file
:param name: name of notebook to open
:param src: source directory
:return: notebook object
"""
print("Reading...", end=" ")
nb = nbformat.read(
"{src}/{name}/{name}.ipynb".format(name=name, src=src), as_versio... | 963a48e72c9cbf8a12c0be672f084c20d0ea7683 | 3,600,989 |
def create_idle():
""" creates a subtree which causes the robot to idle on each tick, with status of RUNNING """
idle = py_trees.behaviours.Running(name="Idle")
return idle | 76fde31723f4ad51a135595cc4d461021f28cf36 | 3,600,990 |
import difflib
def _get_suggestion(provided_string, allowed_strings):
"""
Given a string and a list of allowed_strings, it returns a string to print
on screen, with sensible text depending on whether no suggestion is found,
or one or more than one suggestions are found.
:param provided_string: th... | ebd1b963116bddebbc340312f2d7a16be36b11c6 | 3,600,991 |
def NHWC_to_HWNC(x, name='NHWC_to_HWNC'):
"""Convert data format from NHWC to HWNC, may be used for re-indexing.
"""
x = tf.transpose(x, [1, 2, 0, 3])
return x | 6838048568c35627445224668bf6abc9c5457d6c | 3,600,992 |
import array
def kmeans_train(pm_options, spark):
"""
Kmeans Training function
:param pm_options:
:param spark:
:return:
"""
# Import Data
##################################
input_data = (spark.read.format("csv")
.option("header", pm_options.with_headers)
... | 933878e5c89013638eaa18e963dfe73aebf14248 | 3,600,993 |
def iso_8601(datetime):
"""Convert a datetime into an iso 8601 string."""
if datetime is None:
return datetime
value = datetime.isoformat()
if value.endswith('+00:00'):
value = value[:-6] + 'Z'
return value | 968b9d9edfe13340e4c2f74fb78c11cb38d6c013 | 3,600,994 |
def tuple_subtract(tuple1, tuple2):
"""Perform element-wise subtraction of two tuples or numbers."""
return tuple_add(tuple1, tuple_mul(tuple2, -1)) | 7700c544d96257c906215c75f665266630d6aea0 | 3,600,995 |
from typing import Tuple
from typing import Sequence
def _binlbins(glon: float, vterm: float, dl: float = 1.0) -> Tuple[Sequence, Sequence]:
"""Bin l bins."""
minglon, maxglon = (
np.floor(np.amin(glon)),
np.floor(np.amax(glon)),
)
minglon, maxglon = int(minglon), int(maxglon)
nout... | 51f47be874dbfcb3337b21c7c483a3b80de4c8b3 | 3,600,996 |
import math
def colorize(im, total_fr, fr_no):
"""
motion representation of the input pose maps from consequent frames based on the color codeing of
the time proceeding
====== input ======
im: pose map with gray scale intensity ( all the channels have are identical)
total_fr : total number of ... | 39830525df94bf30f518dea1503e8be5518ff42b | 3,600,997 |
def previous_request_handler(username):
"""Request handler for previewing all previous requests of a given user
Args:
username (str): user who initiated the request
Returns:
tuple: data in json form and status code
"""
user_exists = validate_previous_request(username)
if not us... | 1233f7b82f7ac9aaa2c50f92b490b7fc1e6b5531 | 3,600,998 |
def tox_configure(config):
"""
:param tox.config.Config config: Configuration object to observe.
:rtype: tox.config.Config
"""
return _ensure_envs_recreated_on_requirements_update(config) | 2876fc37badbb59ddb8149882fb5bec0ae22b542 | 3,600,999 |
def rms_model(nu, nu_rms, rms):
"""
"""
return (1/3)*rms[crrls.best_match_indx(nu, nu_rms)] | b48d38625eb985ce69f37cdd4cf8903be5749815 | 3,601,000 |
def remove(predicate, coll):
""" Return those items of collection for which predicate(item) is true.
>>> from functoolz import remove
>>> def even(x):
... return x % 2 == 0
>>> list(remove(even, [1, 2, 3, 4]))
[1, 3]
"""
return filter(lambda x: not predicate(x), coll) | 388960b59dd996a9dcac2470ac3c63a8d904853c | 3,601,002 |
def channel_shuffle2(x,
groups):
"""
Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
https://arxiv.org/abs/1707.01083.
The alternative version.
Parameters:
----------
x : Tensor
Input tensor.
... | 7fd5d4e9438ec0e294e839231ebe103cdd74eac1 | 3,601,003 |
def blackmanharris7(N, sym):
""" 7 Term Cosine, 180.468 dB, NBW 2.63025 bins, 11.33355 dB gain"""
a = [2.712203605850388e-001,
-4.334446123274422e-001,
2.180041228929303e-001,
-6.578534329560609e-002,
1.076186730534183e-002,
-7.700127105808265e-004,
1.36... | 4f81e08f72d1cf2f361812a53fb43810111dcc21 | 3,601,004 |
import types
def register(fnname, nargs):
"""
Register a function with excel
"""
if type(fnname) == types.FunctionType:
fnname=fnname.func_name
r=RegisterFnXLL(str(getXLLDLL()),
"ExPyDispatch",
"P"+"P"*nargs+"#",
fnname)
fnreg... | e2409eb95d414d564cdc066ab15516e1a210e43d | 3,601,006 |
def compute_accuracy(y_pred, y_test):
"""Compute accuracy of prediction.
Parameters
----------
y_pred : array, shape (N_test)
Predicted labels.
y_test : array, shape (N_test)
True labels.
"""
true_counter = 0
for i in range(len(y_pred)):
if y_pred[i] == y_test[i]... | a06b4d91f1878288ab4746d1f729040c95b91a91 | 3,601,007 |
def verify_device_tracking_policy_configuration(device, policy_name, security_level='guard',
trusted_port=None, device_role=None,
data_glean=None, prefix_glean=None,
neighbor_d... | f6aa0753acda069f6c51e8410a6fb0b265dfaaf1 | 3,601,008 |
import itertools
def findEpitopes(responses, sharedRule, **kwargs):
"""Given a list of responses find the minimum
set of epitopes that "explain" all responses."""
"""Start with all possible sets of responses (i.e. combinations)"""
sharedSets = []
for N in range(1, len(responses) + 1):
for... | 4dab98a31b3581ef1310d7a09a4525ad23576cfa | 3,601,009 |
def closest_approach(points, direction):
"""
Compute the point of closest approach between lines.
Parameters
----------
points : ndarray
An n x 3 array of points on each line
direction : ndarray
An n x 3 array of vectors that defines the direction of each line
... | 99bbf31659dc7140cc816767a12c46f7d8fa3634 | 3,601,010 |
def read_random_int(nbits: int) -> int:
"""Reads a random integer of approximately nbits bits."""
randomdata = read_random_bits(nbits)
value = transform.bytes2int(randomdata)
value |= 1 << (nbits - 1)
return value | 691042f40206b5a4f12b0023797eec22483690ee | 3,601,011 |
def init_centroids(k, edges):
"""Returns k centroids by randomly sampling data points out of a given set of
edges, as a matrix of shape (k, n).
:param k: an integer value denoting the number of means/clusters.
:param edges: a matrix of edges to sample the initial means from
:returns: a matrix of k ... | 7193d44b312ffd1910cf22c01ccbe501ee524e87 | 3,601,012 |
def get_request_url(url, *args, **kwargs):
"""Returns url parameter that request will use"""
return url | fde43b531d53e0f3cf80655b0da9895b7a001e13 | 3,601,013 |
from typing import Set
def get_genes_in_graph(graph: pybel.BELGraph) -> Set[str]:
"""Get BEL graph gene set for a pathway.
:param graph: BEL Graph
:return: BEL graph gene set
"""
return {
node
for node in graph
if isinstance(node, CentralDogma) and node.namespace.lower() =... | 83446ff7f38f935ed5d26423b57ea1eecdb59ba3 | 3,601,016 |
import typing
import scipy
def get_pcs(mat: np.ndarray, num_pcs: int) -> typing.Tuple[np.ndarray, np.ndarray]:
"""Gets the top num_pcs principal component vectors and associated
values from the specified matrix.
Args:
mat (np.ndarray[samples, features]): The matrix to reduce
num_pcs (int)... | b5de6199f88d513d438efb2e770d3a98cca3412d | 3,601,017 |
def square_table_while(n):
"""
Returns: list of squares less than (or equal to) N
This function creates a list of integer squares 1*1, 2*2, ...
It only adds those squares that are less than or equal to N.
Parameter n: the bound on the squares
Precondition: n >= 0 is a number
"""
... | 8eb94d9690f4138fb6759cf73d5a602659571b34 | 3,601,018 |
import json
async def home_card(request : VueRequest):
"""
获取首页卡片上数据的接口
:param:
:return str response: 需要返回的数据
"""
try:
response = {'code': '', 'message': '', 'data': ''}
request = rsa_crypto.decrypt(request.data)
request = json.loads(request)
token = req... | 2ec13c58f038cb3de3109739edfd655c72b76474 | 3,601,020 |
from functools import reduce
def subtract(ctx, *operands):
"""Negate one number or subtract many."""
if len(operands) == 1:
return -operands[0]
else:
return reduce(float, lambda x, y: x - y, *operands) | c131a6975297deccc31e06634935df328e4306f6 | 3,601,022 |
def get_gsom_node_array_with_new_feature_vectors(gsom_nodemap, gsom_list, labels, input_database, centroids, global_centroid):
"""
Advanced Version of the get_gsom_node_array(gsom_list, labels)
:param gsom_list:
gsom neuron weights returned by the kmeans clustering
:param labels:
This is regar... | 033f3454d152bb1ad5fd965aba3ff5b68932b3b9 | 3,601,023 |
def gtk_get_light_theme():
"""Return the GTK Light theme specified in the yin-yang config"""
return config["gtkLightTheme"] | e3c0e2155f8ad147535e43fb2db42e9aa2436bfa | 3,601,024 |
def populate_words(words, oxford_api, words_api=None, allow_messages=True):
"""
Iterates the words dictionary, populating the data of each object using the OxfordAPI and with the optional
WordsAPI to be used in the case the word is not found in the Oxford dictionary.
:param words: The dictionary contain... | 6f435b2e8d9947a9e7c6ba558aa43e13fe0dcfd6 | 3,601,025 |
def fold(paper, axis, pos):
"""
Make a fold.
"""
if axis == 'y':
top, bottom = np.array_split(paper, [pos,], axis=0)
bottom = bottom[1:]
if top.size > bottom.size:
bottom = np.pad(bottom, ((0, len(top)-len(bottom)), (0, 0)), 'constant')
else:
top =... | 8620d612a0bde3a58f80432722bd1fa9824c5e62 | 3,601,026 |
def LoadSignedJson(txt, key):
"""Verify that a given message was signed with the given key, and load it.
@param txt: json-encoded hmac-signed message
@param key: the shared hmac key or a callable taking one argument (the key
selector), which returns the hmac key belonging to the key selector.
Typical usa... | 73a4f21f0c587b4f357c48ddc1f6068c14ed0344 | 3,601,027 |
import json
import logging
def create_iam_role_for_lambda(iam_role_name):
"""Create an IAM role to enable a Lambda function to call AWS services
:param iam_role_name: Name of IAM role
:return: ARN of IAM role. If error, returns None.
"""
# Lambda trusted relationship policy document
lambda_a... | f876543b2c9ccb3cb53aae8fa03cfb8d0ee97bef | 3,601,028 |
def multilabel_dilation(img, radius=1, kernel=sitk.BinaryDilateImageFilter.Ball):
"""
This function...
:param img:
:param radius:
:param kernel:
:return:
"""
distImg = sitk.SignedMaurerDistanceMap(
img != 0, insideIsPositive=False, squaredDistance=False, useImageSpacing=False
... | 6dc3b795d87eb40e5d7589a049c1d9ab5f7e503a | 3,601,029 |
def _neighbors_sparse_fixed_radius(csrmat, radius):
"""
Returns the list of neighbor column indices within the fixed radius
Parameter
---------
csrmat : scipy.sparse.csr_matrix
radius : int
Return
------
list of lists of ints
Example
-------
>>> M = np.array([[-1,0,1,4],[1,-1,0,2],[0,10,-1,3],[0,0,2... | 1948ced30f98a20692e7ed9b97e212ff332001e0 | 3,601,030 |
def set_subMenus(id, menus):
"""
:param id: 父id
:param subMenu:子菜单列表
:return: 没有子菜单返回None 有子菜单返回子菜单列表
"""
try:
_subMenus = []
for menu in menus:
if menu.pid == id:
_subMenus.append(model_to_dict(menu))
for sub in _subMenus:
menu2 =... | 8ff3e506f837ed3bc9f110bbf99d40505ebf4f6b | 3,601,032 |
def media_artist(self):
"""Artist of current playing media, music track only."""
return self._media_artist | 12e0538850bfb04ae52fe6840b7445423e393687 | 3,601,034 |
def baseline_predict_scenev2(LR, QM, interpolation=cv2.INTER_CUBIC):
"""
baseline version 2 :
average image with the maximum number of clearance pixel of one imageset
"""
# load clearance map
n = len(QM)
clearance = np.zeros( (n,) )
#for cl in QM:
for i in prange(n)... | ca8701adf17e1e76177441d09cb5ce63923fbb57 | 3,601,035 |
import ast
def NullIncDec(p, w, bp):
""" ++x or ++x[1] """
right = p.ParseUntil(bp)
child = tdop.ToLValue(right)
if child is None:
p_die("This value can't be assigned to", word=w)
return ast.UnaryAssign(word.ArithId(w), child) | 823944c0d75ed2aadc3a208e4a7ec15fa9b97f8f | 3,601,036 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.