content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fslimage_to_qpdata(img, name=None, vol=None, region=None, roi=False):
""" Convert fsl.data.Image to QpData """
if not name: name = img.name
if vol is not None:
data = img.data[..., vol]
else:
data = img.data
if region is not None:
data = (data == region).astype(np.int)
... | 1f383f17196a11f64ab6d95f5cf001dc41346372 | 15,696 |
import gc
def xgb_cv(
data_, test_, y_, max_depth,gamma, reg_lambda , reg_alpha,\
subsample, scale_pos_weight, min_child_weight, colsample_bytree,
test_phase=False, stratify=False,
):
"""XGBoost cross validation.
This function will instantiate a XGBoost classifier with paramete... | 2ad542c0a6f10835b352ea941a40dfb20b0f02f2 | 15,697 |
def _infer_elem_type(list_var):
"""
Returns types.tensor. None if failed to infer element type.
Example:
Given:
main(%update: (2,fp32)) {
block0() {
%list: List[unknown] = tf_make_list(...) # unknown elem type
%while_loop_0:0: (i32), %while_loop_0:1: List[(2,fp32)] = while_lo... | 207d9ca4bd4f666d867d17756a7cd84110c47e76 | 15,698 |
def plot_hairy_mean_binstat_base(
list_of_pred_true_weight_label_color, key, spec,
is_rel = False, err = 'rms'
):
"""Plot binstats of means of relative energy resolution vs true energy."""
spec = spec.copy()
if spec.title is None:
spec.title = 'MEAN + E[ %s ]' % (err.upper())
else:
... | aebe7d7b4131618c4ca1ef4b78a79258b5f405b7 | 15,699 |
def parse_csv_file(file_contents):
"""
The helper function which converts the csv file into a dictionary where each
item's key is the provided value 'id' and each item's value is another
dictionary.
"""
list_of_contents = file_contents.split('\n')
key, lines = (list_of_contents[0].split(',')... | 32bec37d01a58ff374b28225e4619f3b9cb98480 | 15,700 |
def get_config():
"""
Returns the current bot config.
"""
return BOT_CONFIG | bb9f3a8c5176d31bb32ea7ecd8e334dae2de1ebc | 15,701 |
def SensorLocation_Meta():
"""SensorLocation_Meta() -> MetaObject"""
return _DataModel.SensorLocation_Meta() | f062916300ae9669fa8e22fd6449ec829371a7f4 | 15,702 |
from pathlib import Path
def plot_sample_eval(images: list,
sub_titles=None,
main_title=None,
vmin=None, vmax=None,
label_str=None, pred_str=None,
additional_info=None,
show_plot=False, save_a... | a71d2b84a0c5b236bcf17e82a44dcbaaecd98169 | 15,703 |
def predict():
"""
Get data and do the same processing as when we prototyped,
because we need to normalize based on training data summary stats
:return:
"""
data = pd.read_csv('data.csv')
df = data.drop("Unnamed: 32", axis=1)
df = data.drop("id", axis=1)
df.drop(columns=["Unnamed: ... | 7c0d21b38ce79cb9d2700b79ccb1c47bf27952de | 15,704 |
def format_number(number, num_decimals=2):
"""
Format a number as a string including thousands separators.
:param number: The number to format (a number like an :class:`int`,
:class:`long` or :class:`float`).
:param num_decimals: The number of decimals to render (2 by default). If no... | d898afd3254ee012c94653641ce177eb6e70a842 | 15,705 |
def query_rockets():
"""
request all rockets
"""
query = '''
{
rockets {
id
}
}
'''
return query | 8bf6c912a21bc0250c9a74f7fc26347b50ba1fa8 | 15,706 |
def get_block_len(built_prims, prim_type):
""" Calculates the maximum block length for a given primitive type """
retval = 0
for _, p in built_prims:
if p.prim_type == prim_type:
retval = max(retval, p.block_len)
return retval | 091d96a864abce6d782f3baf832ae508a018d083 | 15,708 |
import torch
def _interpolate_gather(array, x):
"""
Like ``torch.gather(-1, array, x)`` but continuously indexes into the
rightmost dim of an array, linearly interpolating between array values.
"""
with torch.no_grad():
x0 = x.floor().clamp(min=0, max=array.size(-1) - 2)
x1 = x0 + ... | 47025fbe25f2d1f5df9ee1423d63d5022b8d280d | 15,709 |
def modify_column_cell_content(content, value_to_colors):
"""
Function to include colors in the cells containing values.
Also removes the index that was used for bookkeeping.
"""
idx, value = content
if type(value) == int or type(value) == float:
color = value_to_colors[content]
... | efbac52eb49efa2054b7b346def96b8e7608bae7 | 15,710 |
def ReversePolishSolver(expression):
"""
Solves a given problem in reverse polish notation
:param expression - tuple of strings
"""
# Create empty stack
rp_calculator = Stack()
for c in expression:
# Check if next part of expression is an operator or a number
operator = {'+... | 13f916be6a64f15f2d96642e178ef1842df77d24 | 15,711 |
import curses
def _make_selection(stdscr, classes, message='(select one)'):
"""
This function was originally branched from https://stackoverflow.com/a/45577262/5009004
:return: option, classes index
:rtype: (str, int)
"""
attributes = {}
curses.init_pair(1, curses.COLOR_WHITE, curses.COLO... | 7b2d22e70c84138d4bcfae1d1bc5d6a11d4ce806 | 15,712 |
def _check_keys(keys, spec):
"""Check a list of ``keys`` equals ``spec``.
Sorts both keys and spec before checking equality.
Arguments:
keys (``list``): The list of keys to compare to ``spec``
spec (``list``): The list of keys to compare to ``keys``
Returns:
``bool``
Rais... | 83d7662b2e28bb4a5ad959ea04d0ede5ac15458b | 15,713 |
def hangToJamo(hangul: str):
"""한글을 자소 단위(초, 중, 종성)로 분리하는 모듈입니다.
@status `Accepted` \\
@params `"안녕하세요"` \\
@returns `"ㅇㅏㄴㄴㅕㅇㅎㅏ_ㅅㅔ_ㅇㅛ_"` """
result = []
for char in hangul:
char_code = ord(char)
if not 0xAC00 <= char_code <= 0xD7A3:
result.append(char)
... | 680ff6f873eff03df36a619e221f62c38b69daec | 15,715 |
import json
def get_config(config_path):
""" Open a Tiler config and return it as a dictonary """
with open(config_path) as config_json:
config_dict = json.load(config_json)
return config_dict | 72a2133b44ffc553ad72d6c9515f1f218de6a08c | 15,716 |
from typing import Iterable
from re import T
from typing import Tuple
import itertools
def groupby_index(iter: Iterable[T],n:int) -> Iterable[Iterable[T]]:
"""group list by index
Args:
iter (Iterable[T]): iterator to group by index
n (int): The size of groups
Returns:
Iterable[It... | 20172b8d52247228253790150225177a2d65caa3 | 15,717 |
def _build_message_classes(message_name):
"""
Create a new subclass instance of DIMSEMessage for the given DIMSE
`message_name`.
Parameters
----------
message_name : str
The name/type of message class to construct, one of the following:
* C-ECHO-RQ
* C-ECHO-RSP
... | bee717a712acb3463811a64ca2e960823bb60cc5 | 15,718 |
def valid_string(s, min_len=None, max_len=None,
allow_blank=False, auto_trim=True, pattern=None):
"""
@param s str/unicode 要校验的字符串
@param min_len None/int
@param max_len None/int
@param allow_blank boolean
@param auto_trim boolean
@:param pattern re.p... | 07bb43fd9fc3581330377e16b7e876d5ee051543 | 15,719 |
def update_visitor(visitor_key, session_key=None):
""" update the visitor using the visitor key """
visitor = get_visitor(visitor_key)
if visitor:
visitor.mark_visit()
if session_key:
visitor.last_session_key = session_key
visitor.save()
return visitor | cc73997ff0fdb3b591f4f55f8a00b6d0ab02a8ea | 15,720 |
def PNewUVTable (inUV, access, tabType, tabVer, err):
""" Obsolete use PGetTable
"""
if ('myClass' in inUV.__dict__) and (inUV.myClass=='AIPSUVData'):
raise TypeError("Function unavailable for "+inUV.myClass)
return PGetTable (inUV, access, tabType, tabVer, err) | a7f9c156a9787839a55de10bf524f12a8086e1b0 | 15,721 |
import binascii
def fmt_hex(bytes):
"""Format the bytes as a hex string, return upper-case version.
"""
# This is a separate function so as to not make the mistake of
# using the '%X' format string with an ints, which will not
# guarantee an even-length string.
#
# binascii works on all ve... | d25379ec333a653549c329932e304e61c57f173d | 15,722 |
import requests
def getTracksAudioFeatures(access_token, id_string):
"""
getTracksAudioFeatures() retrieves the track list audio features, this includes danceability, energy, loudness, etc..
"""
# URL to pass a list of tracks to get their audio features
audio_features_url = f"/audio-features"... | c0f627bf804065826e2e3e47edaba3077dbfad8f | 15,724 |
def tan(x):
"""Element-wise `tangent`."""
return sin(x) / cos(x) | 4854c102c02c0cc32af51eb5f5b47ab39f66f17e | 15,726 |
def scalingImage(img, minVal, maxVal):
"""
Scale image given a range.
Parameters: img, image to be scaled;
minVal, lower value for range;
maxVal, upper value for range.
Returns: imgScaled, image scaled.
"""
imax = np.max(img)
imin = np.min(img)
std = (... | 7e4edb22f464afdf5dbc12f2dd9ab99533a68d54 | 15,727 |
def forcestr(name):
""" returns `name` as string, even if it wasn't before """
return name if isinstance(name, bytes) else name.encode(RAW_ENCODING, ENCODING_ERROR_HANDLING) | 8b2dff5762ebab584b1e578f640d56d0c3af3e1a | 15,728 |
def IsGitSVNDirty(directory):
"""
Checks whether our git-svn tree contains clean trunk or some branch.
Errors are swallowed.
"""
# For git branches the last commit message is either
# some local commit or a merge.
return LookupGitSVNRevision(directory, 1) is None | 903e3827fc3569a9ac67038a9112afe6e2db9842 | 15,729 |
def create_pyfunc_dataset(batch_size=32, repeat_size=1, num_parallel_workers=1, num_samples=None):
"""
Create Cifar10 dataset pipline with Map ops containing only Python functions and Python Multiprocessing enabled
"""
# Define dataset
cifar10_ds = ds.Cifar10Dataset(DATA_DIR, num_samples=num_sample... | c03b730e58abe09560d073b2abe5ee43e782b5f5 | 15,731 |
from typing import Sequence
from typing import Union
from typing import Tuple
from typing import List
from typing import Type
def _infer_structured_outs(
op_config: LinalgStructuredOpConfig,
in_arg_defs: Sequence[OperandDefConfig], ins: Sequence[Value],
out_arg_defs: Sequence[OperandDefConfig],
outs: ... | 00efb063451c1a6b6d9f451043f162bb0ca91efc | 15,732 |
import functools
def event_source(method: t.Callable, name: t.Optional[str] = None):
"""A decorator which makes the function act as a source of before and after call events.
You can later subscribe to these event with :py:func:`before` and :py:func`after` decorators.
:param method: Target class method
... | 136e25826d508259c95d2b6967b8c5f43a17e2e8 | 15,733 |
def lst_blocks(uvp, blocks=2, lst_range=(0., 2.*np.pi)):
"""
Split a UVPSpec object into multiple objects, each containing spectra
within different contiguous LST ranges. There is no guarantee that each
block will contain the same number of spectra or samples.
N.B. This function uses the `lst... | 4c2882f7d513dbb920c33aa6e829852ee22e74fb | 15,734 |
def is_completed(book):
"""Determine if the book is completed.
Args:
book: Row instance representing a book.
"""
return True if book.status == BOOK_STATUS_ACTIVE \
and not book.complete_in_progress \
and book.release_date \
else False | 002d3d5829218dc02a6e6bdc39d67bc9bdd6ca15 | 15,735 |
def compute_encryption_key_AESV3(password : 'str', encryption_dict : 'dict'):
"""
Derives the key to be used with encryption/decryption algorithms from a user-defined password.
Parameters
----------
password : bytes
Bytes representation of the password string.
encryption_dict : dict... | c6d3ec657e43187f582b414824082f5483145f94 | 15,736 |
def list_group(group_name, recursive=True):
"""Returns all members, all globs and all nested groups in a group.
The returned lists are unordered.
Returns:
GroupListing object.
"""
return get_request_cache().auth_db.list_group(group_name, recursive) | ebd0ddfc7494d2af18057b2adde51cdb0e0b3a76 | 15,737 |
def pi():
"""Compute Pi to the current precision.
>>> print(pi())
3.141592653589793238462643383
"""
getcontext().prec += 2 # extra digits for intermediate steps
three = Decimal(3) # substitute "three=3.0" for regular floats
lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
whi... | e9907ef4e437ddbeae34d869d48328ee32bd8d5c | 15,738 |
def load_cifar_data(limit=None) -> np.ndarray:
"""
:param limit:
:return:
"""
# cifar10 data (integrated in TensorFlow, downloaded on first use)
cifar10_data = tf.keras.datasets.cifar10
# split into training and test data
train_data, test_data = cifar10_data.load_data()
# split dta i... | 48bbdc60d614b00fdddd7492f37c5ebb62d21caf | 15,739 |
def set_goal_orientation(delta,
current_orientation,
orientation_limit=None,
set_ori=None):
"""
Calculates and returns the desired goal orientation, clipping the result accordingly to @orientation_limits.
@delta and @current_orientat... | 48475c0428f8fa4c179ece5c3d13f5db701256e8 | 15,740 |
def get_fixed_income_index():
"""获取固定收益及中债总财富指数对比走势"""
return get_stg_index('fixed_income', '037.CS') | b04c8a84e0f65c7a88e5e48f2460cd70e57fd394 | 15,741 |
def get_jobid(db):
"""
Ask MongoDB for the a valid jobid.
All processing jobs should have a call to this function at the beginning
of the job script. It simply queries MongoDB for the largest current
value of the key "jobid" in the history collection. If the history
collection is em... | c21976961c8465b387cdc0d8298a7887563d8233 | 15,742 |
def isA(token, tt=None, tv=None):
"""
function to check if a token meets certain criteria
"""
# Row and column info may be useful? for error messages
try:
tokTT, tokTV, _row, _col = token
except:
return False
if tt is None and tv is None:
return True
elif tv is No... | d16eb9c963addcdc5eb416dc627c18ee98ddd28c | 15,744 |
from typing import Tuple
from typing import Dict
def authenticate(
*,
token: str,
key: str,
) -> Tuple[bool, Dict]:
"""Authenticate user by token"""
try:
token_header = jwt.get_unverified_header(token)
decoded_token = jwt.decode(token, key, algorithms=token_header.get("alg"))
e... | 1bb326b4d958ab6e4b8dc11a67f658dae0e8c753 | 15,745 |
def backup(source, destination, *, return_wrappers=False):
"""
Backup the selected source(s) into the destination(s) provided.
Source and destination will be converted into ``Source`` and
``Destination`` respectively. If this conversion fails,
an exception will be raised.
:param return_wrapper... | 9ee19caa86a398abbfce2bbe28d0995ebe1e842f | 15,746 |
def _prepare_data(cfg, imgs):
"""Inference image(s) with the detector.
Args:
model (nn.Module): The loaded detector.
imgs (str/ndarray or list[str/ndarray] or tuple[str/ndarray]):
Either image files or loaded images.
Returns:
result (dict): Predicted results.
"""
... | 993074d9f789469a38a0050c0ed970b3c86227b8 | 15,747 |
import json
import six
def _HandleJsonList(response, service, method, errors):
"""Extracts data from one *List response page as JSON and stores in dicts.
Args:
response: str, The *List response in JSON
service: The service which responded to *List request
method: str, Method used to list resources. O... | db87c9ed87df1268e1187f74c193b5f96f9e10f7 | 15,748 |
def gray_arrays_to_rgb_sequence_array(arrays, start_rgb, end_rgb, normalise_input=False, normalise_output=True):
"""Returns an RGB array that is mean of grayscale arrays mapped to linearly spaced RGB colors in a range.
:param list arrays: list of numpy.ndarrays of shape (N, M)
:param tuple start_rgb: (R, G... | 2b20c524529e195f49348cc56bf2aa2c46a7ab4e | 15,749 |
def normalize_inputs(df, metrics):
"""Normalize all inputs around mean and standard deviation.
"""
for m in metrics:
mean = np.mean(df[m])
stdev = np.std(df[m])
def std_normalize(x):
return (x - mean) / stdev
#df[m] = df[m].map(std_normalize)
xmin = min(df... | 6e861050d4cec7d5d75c3597412df91b175a821f | 15,750 |
def calc_z_rot_from_right(right):
"""
Calculates z rotation of an object based on its right vector, relative to the positive x axis,
which represents a z rotation euler angle of 0. This is used for objects that need to rotate
with the HMD (eg. VrBody), but which need to be robust to changes in orientati... | 32ee873fe96d5460ac9bfe6d0a3361b9f7e88cc7 | 15,751 |
def poisson_interval(data, alpha=0.32):
"""Calculates the confidence interval
for the mean of a Poisson distribution.
Parameters
----------
data: array_like
Data giving the mean of the Poisson distributions.
alpha: float
Significance level of interval. Defaults to
one si... | bf5d9071df9cea065af63205c6557d1a9334c236 | 15,752 |
def sales_administrative_expense(ticker, frequency):
"""
:param ticker: e.g., 'AAPL' or MULTIPLE SECURITIES
:param frequency: 'A' or 'Q' for annual or quarterly, respectively
:return: obvious..
"""
df = financials_download(ticker, 'is', frequency)
return (df.loc["Sales, General and administr... | 30f5c4a1a1b28ec2c581671964b35c4009c5dffe | 15,753 |
def clip(x, min_, max_):
"""Clip value `x` by [min_, max_]."""
return min_ if x < min_ else (max_ if x > max_ else x) | 3ad7625fa3dc5a0c06bb86dc16698f6129ee9034 | 15,754 |
import random
def generate_code():
"""Generate a URL-compatible short code."""
return ''.join(random.choice(ALPHABET) for _ in range(10)) | 35c8674f39dd1ad6e8f4a238c01fbf5e020513e8 | 15,755 |
def prox_pos(v, t = 1, *args, **kwargs):
"""Proximal operator of :math:`tf(ax-b) + c^Tx + d\\|x\\|_2^2`, where :math:`f(x) = \\max(x,0)` applied
elementwise for scalar t > 0, and the optional arguments are a = scale, b = offset, c = lin_term, and
d = quad_term. We must have t > 0, a = non-zero, and d >= 0. ... | 18136db3b35ef20a03dfe2502930dad648bbc96e | 15,756 |
def delete_mapping(module, sdk, cloud, mapping):
"""
Attempt to delete a Mapping
returns: the "Changed" state
"""
if mapping is None:
return False
if module.check_mode:
return True
try:
cloud.identity.delete_mapping(mapping)
except sdk.exceptions.OpenStackCloud... | 2b9a0606775949ed1361010b2ca8ef1257d9db25 | 15,757 |
def insert_target(x, segment_size):
"""
Creates segments of surrounding words for each word in x.
Inserts a zero token halfway the segment to mark the end of the intended
token.
Parameters
----------
x: list(int)
A list of integers representing the whole data as one long encoded
... | 7874e26deb13e7872992741dc232ffbdcdaf7d00 | 15,758 |
import functools
def find_nearest_network(ipa, nets):
"""
:param ipa: An ip address string
:param nets:
A of str gives and ip address with prefix, e.g. 10.0.1.0/24
>>> net1 = "192.168.122.0/24"
>>> net2 = "192.168.0.0/16"
>>> net3 = "192.168.1.0/24"
>>> net4 = "192.168.254.0/24"
... | 43001fb2236a3654ff769e0e7a7eaad37bc74100 | 15,759 |
def set_action_translation(
language_id: int,
action_id: int,
name: str,
description: str = '',
short_description: str = '',
) -> ActionTranslation:
"""
Create or update an action translation.
:param language_id: the ID of an existing language
:param action_id: t... | b0fe43b8e0fdee7a6604a4de4a8546763f152498 | 15,761 |
def partialSVD(batch, S, VT, ratio = 1, solver = 'full', tol = None, max_iter = 'auto'):
"""
Fits a partial SVD after given old singular values S
and old components VT.
Note that VT will be used as the number of old components,
so when calling truncated or randomized, will output a
specific number of eigenvector... | 9b50e7f60ea187e7e6553ee1406322dd920e26a3 | 15,762 |
def can_move_in_direction(node: Node, direction: Direction, factory: Factory):
"""If an agent has a neighbour in the specified direction, add a 1,
else 0 to the observation space. If that neighbour is free, add 1,
else 0 (a non-existing neighbour counts as occupied).
"""
has_direction = node.has_nei... | 7e747b8ba2c5b385b484b16c0c108aafd3c11351 | 15,763 |
def Usable(entity_type,entity_ids_arr):
"""Only for Linux modules"""
filNam = entity_ids_arr[0]
return filNam.endswith(".ko.xz") | d64aebf033fad9d81350b9221368c2208d9a003f | 15,765 |
import torch
def detection_collate(batch):
"""Custom collate fn for dealing with batches of images that have a different
number of associated object annotations (bounding boxes).
Arguments:
batch: (tuple) A tuple of tensor images and lists of annotations
Return:
A tuple containing:
... | ec2217eb0fcd1c348d3d6f65f07ea20ac33b55ea | 15,766 |
import scipy
def _apply_fft_high_pass_filter(data, fmin, fs=None, workers=None,
detrend=True, time_name=None):
"""Apply high-pass filter to FFT of given data.
Parameters
----------
data : xarray.DataArray
Data to filter.
fmin : float
Lowest frequen... | a1e345b19c6f39b7c667a03b2a95f824f3c15aa8 | 15,768 |
def truncate(array:np.ndarray, intensity_profile:np.ndarray, seedpos:int, iso_split_level:float)->np.ndarray:
"""Function to truncate an intensity profile around its seedposition.
Args:
array (np.ndarray): Input array.
intensity_profile (np.ndarray): Intensities for the input array.
se... | 81d3cd02d9e784bfbdaf5c77041ba1192c72b2dc | 15,769 |
import warnings
def fitting_process_parent(scouseobject, SAA, key, spec, parent_model):
"""
Pyspeckit fitting of an individual spectrum using the parent SAA model
Parameters
----------
scouseobject : Instance of the scousepy class
SAA : Instance of the saa class
scousepy spectral aver... | 763ac6bca7db2813c0b2d9dc67baa541b9596546 | 15,770 |
def _load_grammar(grammar_path):
"""Lee una gramática libre de contexto almacenada en un archivo .cfg y
la retorna luego de realizar algunas validaciones.
Args:
grammar_path (str): Ruta a un archivo .cfg conteniendo una gramática
libre de contexto en el formato utilizado por NLTK.
... | a7432ca9ef4a19b2ec07dcf2434e1dfd140333b9 | 15,771 |
from datetime import datetime
def time_span(ts):
"""计算时间差"""
delta = datetime.now() - ts.replace(tzinfo=None)
if delta.days >= 365:
return '%d年前' % (delta.days / 365)
elif delta.days >= 30:
return '%d个月前' % (delta.days / 30)
elif delta.days > 0:
return '%d天前' % delta.days
... | b93100a0ac3d7b7f45ea7f26b03a0f0149cce1a3 | 15,772 |
def check_point(point_a, point_b, alpha, mask):
"""
Test the point "alpha" of the way from P1 to P2
See if it is on a face of the cube
Consider only faces in "mask"
"""
plane_point_x = lerp(alpha, point_a[0], point_b[0])
plane_point_y = lerp(alpha, point_a[1], point_b[1])
plane_point_z =... | a3848840edd7ab2408197463a7c688954e456a66 | 15,773 |
def gIndex(df, query_txt, coluna_citacoes:str):
"""Calcula índice g"""
df = df.query(query_txt).sort_values(by=[coluna_citacoes],ascending=False)
df = df.reset_index(drop=True)
df.index+= 1
df['g^2'] = df.index**2
df['citações acumuladas'] = df[coluna_citacoes].cumsum()
df['corte'] = abs(df['g^2'] - df['... | 2ef7343026ddf214a5fea7771c1a67887a87f320 | 15,774 |
from typing import List
def dockerize_cli_args(arg_str: str, container_volume_root="/home/local") -> str:
"""Return a string with all host paths converted to their container equivalents.
Parameters
----------
arg_str : str
The cli arg string to convert
container_volume_root : str, optiona... | de4ce13700459089489a8e0d3d10795931d5ba51 | 15,775 |
def _invert_monoms(p1):
"""
Compute ``x**n * p1(1/x)`` for a univariate polynomial ``p1`` in ``x``.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import _invert_monoms
>>> R, x = ring('x', ZZ)
>>> p ... | 790e308f4ec5b689f1bb89d33f5ecf6aaa858334 | 15,776 |
from typing import Dict
def cleaned_picker_data(date: dt.date) -> Dict:
"""Retrieve and process data about Podcast Picker visits
from Webtrekk API for a specific date.
Args:
date (dt.date): Date to request data for.
Returns:
Dict: Reply from API.
"""
config = AnalysisConfig(... | 7b12183ea54a05e20c72a2826bb4adb6e2b6a6ac | 15,777 |
import math
def create_model(args, vocab_size, num_labels, mode='train'):
"""create lac model"""
# model's input data
words = fluid.data(name='words', shape=[-1, 1], dtype='int64', lod_level=1)
targets = fluid.data(
name='targets', shape=[-1, 1], dtype='int64', lod_level=1)
if mode == "tr... | 0996c0a9f8d97463816946b50af112f3738676df | 15,778 |
def escape_string(value):
"""escape_string escapes *value* but not surround it with quotes.
"""
value = value.replace('\\', '\\\\')
value = value.replace('\0', '\\0')
value = value.replace('\n', '\\n')
value = value.replace('\r', '\\r')
value = value.replace('\032... | 1373ea81d22d246c0c0429d6588995e719bd61fb | 15,779 |
def _supports_masking(remask_kernel: bool):
"""Returns a decorator that turns layers into layers supporting masking.
Specifically:
1) `init_fn` is left unchanged.
2) `apply_fn` is turned from
a function that accepts a `mask=None` keyword argument (which indicates
`inputs[mask]` must be masked), into
... | 0fd189ee791edb394fe5fb0efd1f7dd6d944c689 | 15,781 |
def warnings(request: HttpRequest):
"""Adiciona alguns avisos no content"""
warning = list()
if hasattr(request, 'user'):
user: User = request.user
if not user.is_anonymous:
# Testa email
if user.email is None or user.email == "":
warning.append({
... | 990c45c03235eca90b1074d8cc1b6a27b8c5c014 | 15,782 |
def _get_raw_key(args, key_field_name):
"""Searches for key values in flags, falling back to a file if necessary.
Args:
args: An object containing flag values from the command surface.
key_field_name (str): Corresponds to a flag name or field name in the key
file.
Returns:
The flag value ass... | 4af0b0c680b4b0642f40f3a08718239da6de552d | 15,783 |
def get_images(headers, name, handler_registry=None,
handler_override=None):
"""
This function is deprecated. Use Header.data instead.
Load images from a detector for given Header(s).
Parameters
----------
fs: RegistryRO
headers : Header or list of Headers
name : string
... | fcbf887d1a5c71ab4f6c5dcc91df0743497ccefb | 15,784 |
from typing import Union
from typing import Sequence
from typing import Any
from typing import Tuple
def shape_is_ok(sequence: Union[Sequence[Any], Any], expected_shape: Tuple[int, ...]) -> bool:
"""
Check the number of items the array has and compare it with the shape product
"""
try:
sequenc... | f23c0cec12e9038b693e345ccc6909cc2d25c8b1 | 15,785 |
def ChannelSE(reduction=16, **kwargs):
"""
Squeeze and Excitation block, reimplementation inspired by
https://github.com/Cadene/pretrained-models.pytorch/blob/master/pretrainedmodels/models/senet.py
Args:
reduction: channels squeeze factor
"""
channels_axis = 3 if backend.image_dat... | 791089f5729c39d4397afae3a18bd76205ab3185 | 15,786 |
def add_trainingset_flag(cam_parquet,
trainingset_pkl_path,
cam=None):
"""
Add to a single-cam parquet the information flags (adding columns)
indicating if a given cam view was used in a training set for
melting, hydro classif or riming degree
Input... | be6cfd10ab6e9fb7a71b55c13f343caabafa62da | 15,787 |
def pw_wavy(n_samples=200, n_bkps=3, noise_std=None, seed=None):
"""Return a 1D piecewise wavy signal and the associated changepoints.
Args:
n_samples (int, optional): signal length
n_bkps (int, optional): number of changepoints
noise_std (float, optional): noise std. If None, no noise ... | 94a9a681b763a4db36d2186a93e3c5bd0cbd2389 | 15,788 |
def date():
"""
____this is data type for date column____
"""
return Column(Date) | 3953cd155ed03a8cafcc09ee45efcab00c557611 | 15,789 |
import logging
def get_people_urls(gedcom_data, apid_full_map):
"""
Read in all the person URLs for later reference
"""
people = {}
found = False
logging.info("Extracting person specific URL information")
for line in gedcom_data.split("\n"):
if len(line) > 5:
tag = line... | 2495a39c988d726cf8b4f63a34a963d6a442dc32 | 15,792 |
import torch
def permute_masks(old_masks):
"""
Function to randomly permute the mask in a global manner.
Arguments
---------
old_masks: List containing all the layer wise mask of the neural network, mandatory. No default.
seed: Integer containing the random seed to use for reproducibility. Default is 0
Return... | 55a45f0e6c651bb4df0a5b8d58f1f50f992cdfb8 | 15,793 |
import asyncio
async def file_clang_formatted_correctly(filename, semaphore, verbose=False):
"""
Checks if a file is formatted correctly and returns True if so.
"""
ok = True
# -style=file picks up the closest .clang-format
cmd = "{} -style=file {}".format(CLANG_FORMAT_PATH, filename)
asy... | 0372fe5da05c3ede36db0bc35d228adde6c0aaa9 | 15,794 |
import json
def service_builder(client: Client, is_for_update: bool, endpoint_tag: str,
name: str, service_type: str, protocol: str = None, source_port: int = None,
destination_port: int = None, protocol_name: str = None,
icmp_type: str = None, icmp_code: st... | ef51eeff73d7f32f92185ebe6607af525816d13c | 15,795 |
def fkl( angles ):
"""
Convert joint angles and bone lenghts into the 3d points of a person.
Based on expmap2xyz.m, available at
https://github.com/asheshjain399/RNNexp/blob/7fc5a53292dc0f232867beb66c3a9ef845d705cb/structural_rnn/CRFProblems/H3.6m/mhmublv/Motion/exp2xyz.m
Args
angles: 99-long ve... | 667f1356bf2d56ec5adad7bd723167d4c741faae | 15,796 |
import builtins
def no_matplotlib(monkeypatch):
""" Mock an import error for matplotlib"""
import_orig = builtins.__import__
def mocked_import(name, globals, locals, fromlist, level):
""" """
if name == 'matplotlib.pyplot':
raise ImportError("This is a mocked import error")
... | 90182d9dbbde52779109d4d6cf43ae4fbac140d6 | 15,797 |
from typing import Callable
from typing import Any
from typing import Optional
def profile(func: Callable[..., Any]) -> Callable[..., Any]:
"""
Create a decorator for wrapping a provided function in a LineProfiler context.
Parameters
----------
func : callable
The function that is to be w... | 13db0f994f472b95535a27ab8bb58c01491eb092 | 15,798 |
import torch
def phase_comp(psi_comp, uwrap=False, dens=None):
"""Compute the phase (angle) of a single complex wavefunction component.
Parameters
----------
psi_comp : NumPy :obj:`array` or PyTorch :obj:`Tensor`
A single wavefunction component.
Returns
-------
angle : NumPy :obj... | 3a27564b2e4ad323bb9d6c5c4d344027219ccd3d | 15,799 |
def EG(d1,d2,P):
"""
Méthode permettant de calculer l'esperance de gain du joueur 1 s'il lance d1 dés et
que le joueur 2 lance d2 dés
----------------------------------------------------
Args:
- d1 : nombre de dés lancés par le joueur 1
- d2 : nombre de dés lancés par le joueur 2
... | 7032bbff4bcf721727c2cb86d6e6f480aa520ee2 | 15,800 |
def roi_max_counts(images_sets, label_array):
"""
Return the brightest pixel in any ROI in any image in the image set.
Parameters
----------
images_sets : array
iterable of 4D arrays
shapes is: (len(images_sets), )
label_array : array
labeled array; 0 is background.
... | 2a8993ddb417ac9852ac8a85a4b021cd3db46b66 | 15,802 |
import unicodedata
def normalize_full_width(text):
"""
a function to normalize full width characters
"""
return unicodedata.normalize('NFKC', text) | f8b443089e7083e11f6539f4103ce05f616170c4 | 15,803 |
import random
def make_definitions(acronym, words_by_letter, limit=1):
"""Find definitions an acronym given groupings of words by letters"""
definitions = []
for _ in range(limit):
definition = []
for letter in acronym.lower():
opts = words_by_letter.get(letter.lower(), [])
... | bc0af7b4e81a443c0afe62c2d77ace15bd1ab306 | 15,804 |
def plot_effective_area_from_file(file, all_cuts=False, ax=None, **kwargs):
""" """
ax = plt.gca() if ax is None else ax
if all_cuts:
names = ["", "_NO_CUTS", "_ONLY_GH", "_ONLY_THETA"]
else:
names = tuple([""])
label_basename = kwargs["label"] if "label" in kwargs else ""
kw... | b2627c767dfe8abf64eba1b8b1c1f14a4bf52d87 | 15,805 |
def get_spreading_coefficient(dist):
"""Calculate the spreading coefficient.
Args:
dist: A Distribution from a direct (GC) spreading simulation.
Returns:
The dimensionless spreading coefficient (beta*s*A).
"""
potential = -dist.log_probs
valley = np.amin(potential)
split = ... | 549a0052400466f64f707588e313a9e88829a4d7 | 15,806 |
from pathlib import Path
def get_config_path() -> Path:
"""Returns path to the root of the project"""
return Path(__file__).parent / "config" | b66ece2bc77717b59e88ac65746a2e3b3e8576a2 | 15,807 |
def round(x):
"""
Return ``x`` rounded to an ``Integer``.
"""
return create_RealNumber(x).round() | 403f5f0b4316ef2f06f45885d21fe352f003e193 | 15,808 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.