content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import json
def load_info(path = None, eyes = False):
"""Load cascade classifier and DNN from paths in info.json file."""
if path:
assert os.path.exists(path), f"File {path} not found. "
json_file = path
else:
json_file = os.path.join(os.path.dirname(__file__), 'info.json')
# ... | 678db4c09e5110756c5907059c9887266d609f28 | 40,100 |
def group_reads_by_allele(allele_reads):
"""
Returns dictionary mapping each allele's nucleotide sequence to a list of
supporting AlleleRead objects.
"""
return groupby(allele_reads, lambda read: read.allele) | b7a18b40b45d0eeb5234b1f79f6b114bc109b64a | 40,101 |
from typing import Optional
from typing import MutableMapping
from typing import Any
def create_handler(
session: Optional[SessionProxy],
request: ResourceHandlerRequest,
callback_context: MutableMapping[str, Any], # pylint: disable=unused-argument
) -> ProgressEvent:
"""This function is triggered by... | 850f5c600fea75ac56ec4643888235a1ce5db836 | 40,102 |
import sqlite3
def get_buoy_metadata(db):
"""
Extracts the meta data from the buoy database.
Parameters
----------
db : str
Full path to the buoy data SQLite database.
Returns
-------
meta_info : list
List of dicts with keys based on the field names from the Stations
... | 0a985b57093661d768d09f90ff5b2e66d1ad24ca | 40,103 |
def get_dist_args(dist):
"""Probe a scipy.stats distribution (or JMCtools distribution) for its
required arguments"""
has_args = False
try:
fargs = dist.args
has_args = True
except AttributeError:
has_args = False
if not has_args:
try:
func_args = g... | af274ebfc4d1667bead06203c48111907f1f8d0f | 40,104 |
def MobileNetV2(
input_shape,
alpha=0.35,
include_top=True,
pooling=None,
classes=1000,
classifier_activation='softmax',
last_block_filters=None,
**kwargs
):
"""Instantiates the MobileNetV2 architecture.
.. seealso::
* `MobileNetV2: Inverted Residuals and Linear Bottlenecks <https://arxiv.org/... | 4eac36750d536cd4e98247c85271abf3dcf22e6f | 40,105 |
from typing import Collection
def update_menu_item_linked_object(menu_item, linked_object):
"""Assign new linked object to a menu item. Clear other links."""
menu_item.category = None
menu_item.collection = None
menu_item.page = None
if isinstance(linked_object, Category):
menu_item.categ... | 708c8af16a565d5093bf36a0b9ad65a12f6e57ac | 40,106 |
from datetime import datetime
def _get_creation_date():
"""作成時刻を返す"""
return datetime.utcnow().strftime('%Y-%m-%d-T%H:%M:%SZ') | a6725716361b0b37c35c62fe1f9600224d8d04f2 | 40,107 |
def _param_with_axes_sow_reduce_fn(x, y):
"""Reduction function for sow() calls.
Args:
x: Existing value, or () if there was none.
y: New axis names sown.
Returns:
New axis names.
Raises:
TypeError: If the newly sown value is not an AxisMetadata.
ValueError: If the newly sown axis names d... | 7f5ba0199c7ee8743c3bb6d6a4d9a0d2c7654221 | 40,108 |
def combine_similar_titles(extracted_strings):
"""Take a dictionary with titles and nested dicts with scores
and combine scores for titles which we decide are the same."""
# Iterate through each possible pair of title keys, including both
# permutations of each pair
for title_pair in permutation... | 4eaf64cbff8e6000ba41d8e6b8abcde737e06543 | 40,109 |
import operator
def rkLeavesByK(hmat):
"""Sort the Rk leaves by descending compression ratio.
Args:
hmat: an instance of HMatrixStructure
Returns:
[(compression_ratio1, leaf1), ...]
"""
leaves = hmat.listRkLeaves()
ratio_leaves = [(x.k, x) for x in leaves]
ratio_leaves.sort(k... | 228eef2af7c422471744b1c92572d5e66f69166b | 40,110 |
def check_length(min_length: int,
max_length: int,
mode: str = 'and',
*args) -> bool:
"""
check items length is between min_length and max_length
:param min_length: minimum length
:param max_length: maximum length
:param mode: check mode, 'and': all... | f959619a466f62bf6ecfaf10e0fbb316652891e7 | 40,111 |
def _fix_estrs(estrs):
"""Add fitzpatrick colors, and remove emoji variation selectors.
1) The emoji ordering html page omits the skin color variants. Since
we want to display them, we have to add them. However, we don't add
them for sequences with multiple people, since we don't support
multiracial groups ... | 2e7ac8ac84d7a3afad796b607efb075e3ef8d087 | 40,112 |
from typing import Type
from re import T
from typing import Dict
def dict_to_df(desired_type: Type[T], dict_obj: Dict, logger: Logger, orient: str = None, **kwargs) -> pd.DataFrame:
"""
Helper method to convert a dictionary into a dataframe. It supports both simple key-value dicts as well as true
table di... | dad9f8f0630404641bc8316ab06c817d8df51c3a | 40,113 |
import html
def architecture_summary():
"""
Returns the text and image of architecture summary of the project.
"""
return html.Div(children=[
dcc.Markdown('''
# Project Architecture
This project uses MongoDB as the database. All data acquired are stored in raw form to t... | 6e5221c5cf3179760180242c583c4c0c1c3f1a8c | 40,114 |
def chunk_str(msg, sep=(" ", ".", ",", "(")):
"""
chunk_str will take a string and a tuple of separators and recursively
split the string into Chunk objects that record which separator was
used to split it.
:param msg: The string that we want to break apart.
:type msg: str
:param sep... | f1735fc8fda1a86eb3a3722c60764c3e40fc5041 | 40,115 |
def l2_regularization(W, reg_strength):
"""
Computes L2 regularization loss on weights and its gradient
Arguments:
W, np array - weights
reg_strength - float value
Returns:
loss, single value - l2 regularization loss
gradient, np.array same shape as W - gradient of weight by l2... | 382f09091e8dc90f21319d94ef34973b855cab82 | 40,116 |
def build_shared_head(cfg):
"""Build shared head of detector."""
return build(cfg, SHARED_HEADS) | ed82b32b8fab10120ac9a611d18ac0ebae43aa18 | 40,117 |
def check_csrf(func):
"""Checks/removes a csrf_token from request.session's list of valid tokens."""
def _wrapper(request, *args, **kw):
valid_csrf_tokens = request.session.get('csrf_tokens')
request_csrf_token = request.REQUEST.get('csrf_token')
# Special easter-egg to get around the csrf token.
#... | ee3d9b78528318750b08c191bfe0375c6dca95a9 | 40,118 |
from typing import Optional
def get_connection_monitor(connection_monitor_name: Optional[str] = None,
network_watcher_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> ... | 65829ab0b59914cc4dc71b7575641fab9e09959c | 40,119 |
def ssh(host, user, passwd, log=LOG):
"""SSH to any host.
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user, password=passwd)
return ssh | 99b4a474c66e2fd9c9206698f47d8044e675ce5b | 40,120 |
def _filter_deps(filter, deps):
"""Filters dep targets based on tags."""
if not filter:
return deps
kept_deps = []
for dep in deps:
info = None
if TulsiSourcesAspectInfo in dep:
info = dep[TulsiSourcesAspectInfo].filtering_info
# Only attempt to filter targe... | a673c92c93bd43279e355da904ae495075a9027c | 40,121 |
import tokenize
def prepare_text_for_lda(text):
"""
:param text:
:return: list of filetered tokens
"""
tokens = tokenize(text)
tokens = [token for token in tokens if len(token) > 4]
tokens = [token for token in tokens if token not in stop_words_es]
tokens = [get_lemma(token) for token... | 819769632c1d96ade4ddfd6cde6c2b5ea51bb83d | 40,122 |
def make_grammar(description, whitespace=r'\s*'):
"""Convert a description to a grammar. Each line is a rule for a
non-terminal symbol; it looks like this:
Symbol => A1 A2 ... | B1 B2 ... | C1 C2 ...
where the right-hand side is one or more alternatives, separated by
the '|' sign. Each altern... | b390f8a75aa228490a9d4ddc6a0d24b6cf8b5633 | 40,123 |
from pathlib import Path
def repo_root() -> Path:
"""Repository root, 3 levels up from the resources root."""
return builtin_resources_root().parent.parent.parent | 5d156b90d9c60accc5ab55ba13495ac178a168c5 | 40,124 |
from typing import Optional
from typing import Sequence
def get_acl_token(accessor_id: Optional[str] = None,
description: Optional[str] = None,
local: Optional[bool] = None,
namespace: Optional[str] = None,
policies: Optional[Sequence[pulumi.Inpu... | db8255cebea93eb4ce02ef347e38785b41db471f | 40,125 |
def calc_code_churn(
repo: pygit2.Repository,
commit_a: pygit2.Commit,
commit_b: pygit2.Commit,
churn_config: tp.Optional[ChurnConfig] = None
) -> tp.Tuple[int, int, int]:
"""
Calculates churn between two commits.
Args:
repo: git repository
commit_a: base commit for diff cal... | 5297797d567c0b04283e7d68fa0070ba2cf7f8d8 | 40,126 |
def utf8_to_vyxal(code: str) -> str:
"""Turn UTF-8 characters into bytes according to the codepage"""
return "".join(chr(codepage.index(char)) for char in code) | 13590b17a821561e1baabfc01df0a2ba6997b505 | 40,127 |
def apply_chunk_id_maps(continuation_arr, chunk_id_maps):
""" Applies id maps to each set of continuations """
for (c_dict, id_map) in zip(continuation_arr.flat, chunk_id_maps.flat):
apply_id_map(c_dict, id_map)
return continuation_arr | d738e36a264a0b7a707203c01bbf13b952f1b8c8 | 40,128 |
def find_system_symbol(img, instruction_addr, sdk_info=None, cpu_name=None):
"""Finds a system symbol."""
img_cpu_name = get_cpu_name(img['cpu_type'], img['cpu_subtype'])
cpu_name = img_cpu_name or cpu_name
return DSymSymbol.objects.lookup_symbol(
instruction_addr=instruction_addr,
image... | 219e9fe30b5b15e3943ec56bec735395d5fd6a41 | 40,129 |
def check_processed_data(df,col_list,na_action):
""" Checks if provided dataframe consists of required columns and no missing values
"""
check_passed = True
# Check columns
df_cols = df.columns
if set(df_cols) != set(col_list):
check_passed = False
print('Column names mismatched... | fd26d00eabd9eb1dfd1f8bce01a3fb86582a740f | 40,130 |
def bezier_terms(n, t):
""" Bezier curve.
Return n+1 terms in list ()
"""
m_terms = list()
m_C = binomial_term
for i in range(n):
m_terms.append( m_C(n, i) * (1 - t)**(n - i) * t**i )
m_terms.append(t ** n)
return m_terms | b0891cb6fc848f971134367988f2cd85f3a624a5 | 40,131 |
import subprocess
def execute_command(command):
"""Executes a command, capturing the output"""
output = subprocess.run(command, capture_output=True, encoding='utf-8')
if len(output.stderr) > 0:
print(output.stderr)
output.check_returncode()
return output | 7b768251d0ad52091e79b55aadeebc2481e07b26 | 40,132 |
def feed_conversation(samples, limit=5, threshold=.85):
"""helper function to feed result of classifier to Conversation module."""
try:
iter(samples)
assert not any(not isinstance(sub, tuple) for sub in samples)
except (AssertionError, TypeError) as e:
raise TypeError('samples must b... | 4c3d9b7c63e71790bb1a8445662754d48e31524f | 40,133 |
def _mount_config_map_op(config_map_name: str) -> OpFunc:
"""Mounts all key-value pairs found in the named Kubernetes ConfigMap.
All key-value pairs in the ConfigMap are mounted as environment variables.
Args:
config_map_name: The name of the ConfigMap resource.
Returns:
An OpFunc for mounti... | 6c8193465f70ca34619a8a7c9f3debc534208f6e | 40,134 |
def make_tree(file_name):
"""Loads reStructuredText, outputs an lxml tree"""
rst = resource_string(__name__, file_name)
xml = rst2xml(rst)
return etree.fromstring(xml) | be71c99472ecf9fb8994390c090da4d21e26c144 | 40,135 |
import csv
def save_comments(name, token, nfrom = 0, toappend=[]):
"""
Args:
Takes a pagename, an API token, (optionally: an integer specifying
which # post to begin from, and a list to append comments to)
Out:
a list containing:
a list of of the comments it has i... | 210995010d6ee61dec45aaa3db17d1e43aad6c37 | 40,136 |
def point_inside_volume(p, ab1, ab2, eps = 0.01):
"""
Check if point p is inside the aabb volume
"""
ab1 = ab1.copy() - eps
ab2 = ab2.copy() + eps
if ab1[0] <= p[0] <= ab2[0] and \
ab1[1] <= p[1] <= ab2[1] and \
ab1[2] <= p[2] <= ab2[2]:
return True
else:
retu... | 9cdb6323343fdc23dae4b2c899927450c92cb7a2 | 40,137 |
def vgg_input_preprocess(image, max_dim=512, **kvargs):
""" apply appropriate VGG preprocessing to image, shape=(?,h,w,c)
should be same as `tf.keras.applications.vgg19.preprocess_input(rgb_data)/255.0`
NOTE:
- x_train from dataset will be dtype=tf.float32, domain=(0,1.) AFTER tf.image.convert_image_dtype(... | dec82416a3f91842280db82c0c62780ae628dde8 | 40,138 |
def ldns_rr_set_type(*args):
"""LDNS buffer."""
return _ldns.ldns_rr_set_type(*args) | a8223db4323693a46676292fd0d6065341254d05 | 40,139 |
def spline_jacobian(coordinates, force_coordinates, fudge=1e-5):
"""
Make the Jacobian matrix for the 2D biharmonic spline.
Follows [Sandwell1987]_.
Each column of the Jacobian is the Green's function for a single force
evaluated on all observation points.
Parameters
----------
coordi... | a997105a9b7d8ac025bde4d8b77e05199d21b0d7 | 40,140 |
def whip(innings_pitched: float, bb: int, h: int) -> float:
"""Calculate a baseball pitcher's WHIP.
WHIP = (BB + H) / IP
bb = Walks / Base on balls
h = hits
"""
WHIP = (bb + h) / innings(str(innings_pitched))
return round(float(WHIP), 2) | a28809aae63bab2b68f61bde2c84919e34b2998d | 40,141 |
def _determine_levels(index):
"""Determine the correct levels argument to groupby."""
if isinstance(index, (tuple, list)) and len(index) > 1:
return list(range(len(index)))
else:
return 0 | 2eaed820eb45ff17eb4911fe48670d2e3412fb41 | 40,142 |
def integerise(series):
"""
This duplicates functionality that exists in humanleague, rather than intorducing a package dependency solely for this function
"""
sumf = sum(series)
sumi = round(sumf)
# rescale series to nearest-integer sum
series = series * sumi / sumf
# get integer and fr... | a498c3fda42c7c02a3552ece93ea3d6c1996eacc | 40,143 |
def update_cluster_host_deployed_config(
cluster_id, host_id, user=None, session=None, **kwargs
):
"""Update clusterhost deployed config by cluster id and host id."""
clusterhost = _get_cluster_host(
cluster_id, host_id, session=session
)
return _update_clusterhost_deployed_config(
c... | 97ccffbded81262f42bab2349636f28db5416760 | 40,144 |
def make_ppo_runner(env, policy, num_runner_steps, gamma=0.99, lambda_=0.95,
num_epochs=3, num_minibatches=4):
""" Returns env runner for PPO """
transforms = [GAE(policy, gamma=gamma, lambda_=lambda_, normalize=False)]
if not policy.is_recurrent() and getattr(env.unwrapped, "nenvs", Non... | 9443dabb606457f8984900c35941dbf068dd9b2d | 40,145 |
def left_window_coords(win_size, original_left_bound):
"""
Returns a `tuple` `(new_start, new_end)` left of original bound describing a window of length `win_size` (see
note).
Note: Converts any new value less than `1` to `1`.
:param win_size: size of window to the left.
:param original_left_b... | 80d1c96ab2f9de650b50dbde04acfdb455824f78 | 40,146 |
def _get_forms_to_modify(domain, modified_forms, modified_cases, is_deletion):
"""Used on user.retire() and user.unretire()
Returns a list of IDs of forms which only modify the cases passed in and
which aren't already listed in `modified_forms`.
"""
form_ids_to_modify = set()
for case_id in mod... | 4c907c12a79a7eedb29b4b52461dcdc0c2d8602a | 40,147 |
def build_post_required_integer_header_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Test explicitly required integer. Please put a header 'headerParameter' => null and the client
library should throw before the request is sent.
See https://aka.ms/azsdk/python/protocol/quickstar... | ba9fe7629c798311fb9670db3092f5a72d9a9717 | 40,148 |
def mask2rle(img: np.ndarray):
"""
img: numpy array, 1 - mask, 0 - background
Returns run length as string formated
"""
pixels = img.copy().flatten()
pixels = np.concatenate([[0], pixels, [0]])
runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
runs[1::2] -= runs[::2]
return ' '.join(... | be053cd777f30a610121cae80cf97b15014504a3 | 40,149 |
def make_mask(df: pd.DataFrame, image_name: str="img.jpg", shape: tuple=(256, 1600)):
"""
Create mask based on df, image name and shape.
"""
encoded_masks = df.loc[df["im_id"] == image_name, "EncodedPixels"]
masks = np.zeros((shape[0], shape[1], 4), dtype=np.float32)
for idx, label in enumerate... | 7902d5bc5a7a3c5e7d124f698b94548742e37fdf | 40,150 |
from typing import List
from typing import Dict
def parse_filters(tokens: List[str]) -> Dict[str, str]:
"""Parses a filter description, like 'filter-for', 'refcounty', '42'."""
ret: Dict[str, str] = {}
filter_for = False
for index, value in enumerate(tokens):
if value == "filter-for":
... | 6b659342761e11311bfa3aa1962067e3e83a809d | 40,151 |
def format_val(v):
"""Takes in float and formats as str with 1 decimal place
:v: float
:returns: str
"""
return '{:.1f}%'.format(v) | 932ca312a573a7e69aa12e032d7b062ac22f3709 | 40,152 |
def _can_cast(type1, type2):
"""NOT_RPYTHON: operates on BaseType subclasses"""
return casting_table[type1.num][type2.num] | 03e8602528b26c2c5a61fc56af0ef79c82a9ecf2 | 40,153 |
def concat(layers):
"""
Args:
layers (list(layer)): a list of layers
"""
return (
np.concatenate([l[0] for l in layers]),
np.concatenate([l[1] for l in layers])
) | b07eda38b6974a208f2756b04fc7f92ca5853da4 | 40,154 |
import struct
def array_to_bytes(arr: np.ndarray):
"""
Dumps a numpy array into a raw byte string.
:param arr: A numpy array.
:return: A `bytes` string.
"""
shape = arr.shape
ndim = arr.ndim
ret = struct.pack('i', ndim) + struct.pack('i' * ndim, *shape) + arr.tobytes(order='C')
ret... | fa623658aa73d0f5486771f497c9ce159ea89ca6 | 40,155 |
def count_parameters(model):
"""
number of model parameters to update
"""
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 3f739da845f483fdd489afabd9da12340b0f44a9 | 40,156 |
from typing import Union
from typing import Type
from typing import Optional
def unwrap_vec_wrapper(env: Union["GymEnv", VecEnv], vec_wrapper_class: Type[VecEnvWrapper]) -> Optional[VecEnvWrapper]:
"""
Retrieve a ``VecEnvWrapper`` object by recursively searching.
:param env:
:param vec_wrapper_class:... | 9d544e9789499e63303407ebfb472001b218b304 | 40,157 |
import re
def parseLintignoreText(lintignoreText):
"""
*lintignoreText* should be the text of a 'lintignore' file. Return
the corresponding list of regexes to match against file paths.
"""
lintignoreLines = joinLists([parseLintignoreLine(x)
for x in lintignoreText.... | 633268d4816b544a917320a7a21862b480c64ae8 | 40,158 |
import json
from typing import Counter
def statistics(uid):
"""Return url statistics
Arguments:
- `uid`: The hashed id of the url
"""
if not DB.exists(uid):
abort(404)
else:
entry = DB.get(uid)
entry = json.loads(entry)
short_link = uid
full_link = ent... | d223a59e5d72e7f3aed9ef9247c45636adcab599 | 40,159 |
def ProfileMatrix(kmer_list, k, t, mode, pseudo_count=1): # nrow = t, ncol = k
"""Input a list of kmers and output a entropy score or profile probilities.
It can be switched to hamming distance score by setting mode.
"""
matrix = [[0] * k for i in range(4)] # Initiate a zero-filled nested list.
f... | dc474d0a8dd210be1234763b0d5f141e6c3fa7e4 | 40,160 |
import re
def you_to_yall(text: str) -> str:
"""Convert all you's to y'all."""
pattern = r'\b(y)(ou)\b'
return re.sub(pattern, r"\1'all", text, flags=re.IGNORECASE) | 1a3ee7ebf2394f84ad296e18da789dff8ca50a12 | 40,161 |
def svn_client_list4(*args):
"""svn_client_list4(char const * path_or_url, svn_opt_revision_t peg_revision, svn_opt_revision_t revision, apr_array_header_t patterns, svn_depth_t depth, apr_uint32_t dirent_fields, svn_boolean_t fetch_locks, svn_boolean_t include_externals, svn_client_list_func2_t list_func, void * b... | 5a1496f09209da8e42c199518a53e3cf4e655f91 | 40,162 |
from typing import List
def trivial_max_gcd_sum(arr_a: List[int], arr_b: List[int]) -> int:
"""Calculate max gcd sum.
Complexity: O(n^2).
"""
max_gcd = 0
max_sum = 0
for num_a in arr_a:
for num_b in arr_b:
cur_gdc = gcd(num_a, num_b)
if cur_gdc > max_gcd:
... | 857bf53f77e71e0aff8774641054c35927cdb8d4 | 40,163 |
import re
def get_displays():
"""
Return the list of displays.
"""
# get dispays names
conns = ["xrandr", "--query"]
res = Popen(conns, stdout=PIPE).communicate()[0].decode(ENC)
regex = r"\n([^\s]*) (connected|disconnected).*"
names = [res[0] for res in re.findall(regex, res)]
# cr... | a03e10e780e6e6e91917a1d63532fd4ad522089f | 40,164 |
def tjur_r2(y_true, y_score):
"""
Tjur Pseudo R-squared
Parameters
----------
y_true : numpy array
True values (observed response).
y_score : numpy array
Predicted probabilities.
Returns
-------
t_r2 : float
Tjur Pseudo R-squared.
"""
y_mu1 = y_scor... | 0be5ec44a8f6973219c044f7f2378eba3a6aecfb | 40,165 |
def get_full_std_lib(indent=0):
""" Get the code for the full PyScript standard library.
The given indent specifies how many sets of 4 spaces to prepend.
If the full stdlib is made available in JavaScript, multiple
snippets of code can be transpiled without inlined stdlib parts by
using ``py2js... | 9349d3f565cb6a615e7e421e2f460b4ce38aae22 | 40,166 |
def unit(aClass, value):
""" Calls the 'unit' method of 'aClass' with 'value'. """
return aClass.unit(value) | 58c69898fc024a4ed31e4f7fd10f7fd287af565b | 40,167 |
from typing import Optional
def list_location_consortiums(location_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListLocationConsortiumsResult:
"""
Collection of the consortium payload.
:param str location_name: Location Name.
"""
... | bb6e37971495e46911bde0f698239447e50edcec | 40,168 |
from typing import Tuple
def typeshed_py_version(options: Options) -> Tuple[int, int]:
"""Return Python version used for checking whether module supports typeshed."""
# Typeshed no longer covers Python 3.x versions before 3.6, so 3.6 is
# the earliest we can support.
if options.python_version[0] >= 3:... | 73d059966e50b8443c4ab93183556818ac49f619 | 40,169 |
def pcr(adata, covariate, embed=None, n_comps=50, recompute_pca=True, verbose=False):
"""
PCR for Adata object
Checks whether to
+ compute PCA on embedding or expression data (set `embed` to name of embedding matrix e.g. `embed='X_emb'`)
+ use existing PCA (only if PCA entry exists)
... | 9d44321d244f2ad945d8307c2157f73870a20e12 | 40,170 |
from pydantic import BaseModel # noqa: E0611
async def update_one(model: DeclarativeMeta, obj: BaseModel, pk_param: int, pk_attr: str = 'id'):
""" Update one """
query = update(model).where(pk_param == getattr(model, pk_attr)).values(obj.dict())
await database.execute(query)
return {**obj.dict(), pk_... | efdbce5605803a10737af67807af91f144ace9ea | 40,171 |
import sys
def recordDescribe(*args, **kwargs):
"""
.. deprecated:: 0.42.0
Use :func:`record_describe()` instead.
"""
print("dxpy.recordDescribe is deprecated; please use record_describe instead.", file=sys.stderr)
return record_describe(*args, **kwargs) | 4524b9ab780cbe077a280ae26fd85016a1bfdd9d | 40,172 |
def yellow_mask(original):
"""
Create a mask from the yellowish pixels of the frame, combining RGB mask and HSV mask
"""
hsv = yellow_mask_hsv(original)
rgb = yellow_mask_rgb(original)
mask = np.zeros_like(rgb)
mask[(hsv == 1) | (rgb == 1)] = 1
return mask | 1236614531748d8682f3d2676675186bfd914ca3 | 40,173 |
def getClass():
"""
Takes in a JSON of the form {'_id' : String}
Returns all the information for a class including _id stringified
{'result' : None/JSON, 'success' : Boolean}
"""
if request.json is None or '_id' not in request.json:
abort(400)
if not dbworker.validateAccessList([... | 1946ee40a934fcf7e861782b571ce1db435dc341 | 40,174 |
def isstrictlyascending(lam):
"""This determines whether the index string is a strictly ascending sequence
Parameters
----------
lam : an indexable object of things that are comparable. Usually an array of integers
Returns
-------
bool : true if the sequence is strictly ascending, else fal... | fce99e5ae20d987102eeea441b95777f0b775eba | 40,175 |
def collections_endpoint(url):
""" Resource endpoint handler
:param url: the url that led here
.. versionchanged:: 0.0.7
Using 'utils.request_method' helper function now.
.. versionchanged:: 0.0.6
Support for HEAD requests
.. versionchanged:: 0.0.2
Support for DELETE resour... | e3230c8e98bf7f6a0b628c9eceec0170ca70e1f3 | 40,176 |
def create_action(parent, text, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None, data=None, menurole=None,
context=Qt.WindowShortcut):
"""Create a QAction"""
action = QAction(text, parent)
if triggered is not None:
action.triggered.connect(trigger... | 911318619b02a20d3b401e857421a8b066537f31 | 40,177 |
def to_aws_tags(tags):
"""
When you assign tags to an AWS resource, you have to use the form
[{"key": "KEY1", "value": "VALUE1"},
{"key": "KEY2", "value": "VALUE2"},
...]
This function converts a Python-style dict() into these tags.
"""
return [
{"key": key, "valu... | d1e18ea1e4de08fcae59febbe97ab3eb5bc2a2f1 | 40,178 |
def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5):
"""
Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID.
Arguments:
X -- input dataset, of shape (2, number of examples)
parameters -- python dictionary containing... | 5cd9a9fe9b66b26ac79f4bf1657b24797dadca2d | 40,179 |
def compose_postprocessing(postprocessing):
"""
Compose a postprocessing transform to be performed.
Params
------
postprocessing : dict
- dictionary defining all preprocessing steps to be taken with their
values
e.g. {"Name" : "RescaleIntensity"}
... | 2533202fa34f4101fbae0e1403b1df3fce6b2ef0 | 40,180 |
def run_ksp(graph, cfg, k, thresh=10, algorithm=KSP.find_ksp):
"""
Build the shortest path trees and compute k diverse shortest paths
"""
# construct sp trees
_ = graph.sp_trees(**cfg)
# compute k shortest paths
ksp_processor = KSP(graph)
ksp_out = algorithm(ksp_processor, k, thresh=thre... | 9bcc8f3ac6ea34dbbdd55f9abd067c661c448633 | 40,181 |
def handler(event, context):
"""
api entry function
"""
output = process_api_request(event, put_schedule_tags, logger)
logger.info(output)
return output | 32d902f814df51b7dd86bbddefd22f3d47a56af7 | 40,182 |
def check_for_winner(players) -> bool:
"""Checks all players for a single winner. Returns True if there is a winner.
Keyword arguments:
players -- list of player objects
"""
return sum(map(lambda x: not x.is_bankrupt(), players)) == 1 | 17d39e92a38a9474f080ddebfac1d4813f464a1e | 40,183 |
import click
from typing import Iterable
from pathlib import Path
import os
def infer(
context: click.Context,
modify_paths: Iterable[str],
print_only: bool,
full_only: bool,
recursive: bool,
in_place: bool,
json: bool,
annotate_from_existing_stubs: bool,
debug_infer: bool,
ful... | 5d08467907561eb5ddedc4d7dbf7778d402adf55 | 40,184 |
def random(num_points, span):
"""
This function generates a set of random x and y coordinates using the
numpy uniform random number generator 'numpy.random.uniform()'.
Parameters
----------
num_points : int
The number of points to generate
span : World class
The world defin... | d4425619b29782bc926fac925d896345cdf2f410 | 40,185 |
def get_game_player(game_state):
"""Get the game player whose turn it is to play."""
num_players = len(game_state.game_players)
for game_player in game_state.game_players:
if game_state.turn_number % num_players == game_player.turn_order:
return game_player
return None | a75a0b1b7f1ce4da8c944ad40208fba6f9a50f5a | 40,186 |
def details(location_slug: str):
"""View: Location Details"""
slug = slugify(location_slug)
if location_slug and location_slug != slug:
return redirect_url(url_for("locations.details", location_slug=slug))
database_connection = mysql.connector.connect(**current_app.config["database"])
locat... | df830ac6d746f8d82806537c66dc12172a90eeb3 | 40,187 |
def get_widget_config(id_):
"""Get a widget
:param id: The ID of the widget
:type id: str
:rtype: Report
"""
widget_config = WidgetConfig.query.get(id_)
return widget_config.to_dict() | 3b4b92491a2ddae0674ecb8a9b8578a795849cbb | 40,188 |
import ast
def extract_info_attributes(round_datum):
"""Extract information attributes for current round using NLU annotations.
Args:
round_datum: Current round information
Returns:
get_attribute_matches: Information attributes
"""
user_annotation = ast.literal_eval(round_datum["... | 95e60ea10a7888b3f04619fc882279ebffaf189a | 40,189 |
import re
def get_headers_pairs_list(filename, verbose=False):
"""
Read data for clustering from a given file.
Data format: <email_number> <header>.
Clusters are separated with a blank line.
:param filename: file with input data for clustering.
:param verbose: Whether to be verbose. Default ... | d6b457652e1025475075fb601ba81b6a7fe346fc | 40,190 |
def maintainer_menu(request):
"""
View for maintainer menu page.
This page can only access by superuser and maintainer.
:param request: WSGI request from user.
:return: Render the maintainer menu page and pass the value from context to the template (maintainer.html)
"""
hero_image = 'img/m... | fe87e96c1a8cda2618ceaf0f24fa58ece1bac690 | 40,191 |
import os
from contextlib import suppress
import json
def _get_platform_property_from_targets(platform, property, default):
"""
Load properties from targets.json file somewhere in the project structure
:param platform:
:return: property value, None if property not found
"""
for targets_path i... | 44fefb6c2e88b6139bfdf900b48567ec0d31b840 | 40,192 |
def declaration_path(decl, with_defaults=True):
"""
returns a list of parent declarations names
:param decl: declaration for which declaration path should be calculated
:type decl: :class:`declaration_t`
:rtype: [names], where first item contains top parent name and last item
contains... | a17ef5c192b4fd75b51216eecc717dbf1e09740f | 40,193 |
def fit_largest_peak(xs, ys, num):
"""
Algorithm to "fit" the largest peak
:param xs: numpy array of floats, time series data
:param ys: numpy array of floats, power data
:param num: integer, number of peaks to fit
:return:
"""
sort = np.argsort(xs)
xs, ys = xs[sort], ys[sort]
#... | acf7587c081cc427c78dd88dc3b5d33f1dc6f8cf | 40,194 |
import torch
def direction_neuron(layer,
direction,
x=None,
y=None,
batch=None):
"""Visualize a single (x, y) position along the given direction
Similar to the neuron objective, defaults to the center neuron.
InceptionV1... | 7becd4e60fd4810f364c36d7aca165a92060e0bf | 40,195 |
from pathlib import Path
def _run_jlab_string(talktorials_dst_dir):
"""
Print command for starting JupyterLab from workspace folder.
Parameters
----------
talktorials_dst_dir : str or pathlib.Path
Path to directory containing the talktorial folders.
"""
talktorials_dst_dir = Path... | 76c45f77f419b6a302d63d92e51cd0ea1bb92ebb | 40,196 |
def moment2d(grid):
"""
>>> moment2d([[5, 6, 7, 2, 4]])
[[0, 6, 14, 6, 16]]
"""
return list(map(moment, grid)) | d02bf3a21ccf20566c5e2b93ace82579559eef8f | 40,197 |
import typing
import itertools
import sys
def prepare_data_for_net(
vocabulary: dict,
samples: list,
labels_map: dict,
pos_map: dict,
dependencies_map: dict,
entity_length_distribution: typing.Tuple[float, float],
include_entities_nodes: bool=False,
incl... | ac4f39e4f40863e12a585b44e822844346a42560 | 40,198 |
import requests
def get_onprem_cost_efficiency_handler(request):
""" Queries the OneSphere metrics API and returns the private cloud cost efficiency.
"""
# Get KMS secured environment variables
api_base = request.metadata.get('api_base', None)
token = request.metadata.get('token', None)
# G... | a271165c30ea5855be07906b89357c7700796806 | 40,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.