content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def update_alert():
""" Make Rest API call to security graph to update an alert """
if flask.request.method == 'POST':
flask.session.pop('UpdateAlertData', None)
result = flask.request.form
flask.session['VIEW_DATA'].clear()
alert_data = {_: result[_] for _ in resul... | 52248bda1271fbd39ab056c5384f6318e30cc712 | 11,648 |
def simulate_bet(odds, stake):
"""
Simulate the bet taking place assuming the odds accurately represent the probability of the event
:param odds: numeric: the odds given for the event
:param stake: numeric: the amount of money being staked
:return: decimal: the returns from the bet
"""
proba... | 0a56bc4b9a3071cc777786a1a7cf8b1410e3f941 | 11,649 |
from typing import OrderedDict
def lrcn(num_classes, lrcn_time_steps, lstm_hidden_size=200, lstm_num_layers=2):
"""
Args:
num_classes (int):
Returns:
torch.nn.modules.module.Module
"""
class TimeDistributed(nn.Module):
def __init__(self, layer, time_steps):
su... | a17f58906f4d5b514e56f5cba22ac60bdf739b9c | 11,650 |
import tokenize
def index_document(connection, doc_id, content):
"""对document建立反向索引"""
words = tokenize(content)
pipe = connection.pipeline(True)
for word in words:
pipe.sadd('idx:' + word, doc_id)
return len(pipe.execute()) | 89572980c0bfadef9e1557b7e7831fc7aebe6716 | 11,651 |
def get_incar_magmoms(incarpath,poscarpath):
"""
Read in the magnetic moments in the INCAR
Args:
incarpath (string): path to INCAR
poscarpath (string): path to POSCAR
Returns:
mof_mag_list (list of floats): magnetic moments
"""
mof_mag_list = []
init_mof = read(poscarpath)
with open(incarpath,'r') as in... | 6b75f415e7128213bab63d251a3fb6feb7576656 | 11,652 |
import plistlib
def remove_report_from_plist(plist_file_obj, skip_handler):
"""
Parse the original plist content provided by the analyzer
and return a new plist content where reports were removed
if they should be skipped. If the remove failed for some reason None
will be returned.
WARN !!!!
... | fb14ccf1b0a1ad6b5e3b3e536e21386dbbcac84e | 11,654 |
def isTask(item): # pragma: no cover
"""Is the given item an OmniFocus task?"""
return item.isKindOfClass_(taskClass) | b0e2c813b29315e7b84cd9f2a4d211552dab9baf | 11,655 |
from typing import Tuple
import torch
def cox_cc_loss(g_case: Tensor, g_control: Tensor, shrink : float = 0.,
clamp: Tuple[float, float] = (-3e+38, 80.)) -> Tensor:
"""Torch loss function for the Cox case-control models.
For only one control, see `cox_cc_loss_single_ctrl` instead.
Arg... | 1f528ff25984e0bb09bc49edf59d793a44281ddb | 11,657 |
def vector_field(mesh, v):
"""
Returns a np.array with values specified by `v`, where `v` should
be a iterable of length 3, or a function that returns an iterable of
length 3 when getting the coordinates of a cell of `mesh`.
"""
return field(mesh, v, dim=3) | 2d82fa86bc76367e2668b37815c068097d88c6fa | 11,658 |
def is_fav_recipe(request):
"""
Handles the requests from /ajax/is_fav_recipe/
Checks if a :model:`matega.recipe` is a saved recipe for a :model:'matega.user'
**Data**
Boolean if :model:`matega.recipe` is a saved recipe for :model:'matega.user'
"""
user_id = int(request.GET.get('user_id', N... | f5ee3b21409f7a9ffe4ee427e19317f03b8db9c3 | 11,659 |
def people_interp():
"""
<enumeratedValueSet variable="People"> <value value="500"/> </enumeratedValueSet>
Integer between 1 and 500
"""
return f'<enumeratedValueSet variable="People"> <value value="%s"/> </enumeratedValueSet>' | 2aba1330a774e022c280d2e50e3fb63631989a88 | 11,660 |
def through_omas_s3(ods, method=['function', 'class_method'][1]):
"""
Test save and load S3
:param ods: ods
:return: ods
"""
filename = 'test.pkl'
if method == 'function':
save_omas_s3(ods, filename, user='omas_test')
ods1 = load_omas_s3(filename, user='omas_test')
els... | f89bb1c31a9bcbae869d07313ab10a7df658fd1c | 11,662 |
def read_packages(filename):
"""Return a python list of tuples (repository, branch), given a file
containing one package (and branch) per line.
Comments are excluded
"""
lines = load_order_file(filename)
packages = []
for line in lines:
if "," in line: # user specified a branch
... | e73573003bd0388ed850fd2e996643a91199d30a | 11,663 |
import heapq
def find_min(x0, capacities):
"""
(int list, int list) --> (int list, int)
Find the schedule that minimizes the passenger wait time with the given capacity distribution
Uses a mixture of Local beam search and Genetic Algorithm
Returns the min result
"""
scores_and_schedules =... | 016cdd310f4b59e61349edd94b3b7cc387c3c7c1 | 11,664 |
def versioning(version: str) -> str:
"""
version to specification
Author: Huan <[email protected]> (https://github.com/huan)
X.Y.Z -> X.Y.devZ
"""
sem_ver = semver.parse(version)
major = sem_ver['major']
minor = sem_ver['minor']
patch = str(sem_ver['patch'])
if minor % 2:
... | bfef27712b8595f52314f300743012270a42e64f | 11,665 |
def device_create_from_symmetric_key(transportType, deviceId, hostname, symmetricKey): # noqa: E501
"""Create a device client from a symmetric key
# noqa: E501
:param transportType: Transport to use
:type transportType: str
:param deviceId:
:type deviceId: str
:param hostname: name of t... | 15ac85df5a41f88044cf449f0f9d99bfcd72d570 | 11,667 |
def create_with_index(data, columns):
"""
Create a new indexed pd.DataFrame
"""
to_df = {columns[0]: [x for x in range(1, len(data) + 1)], columns[1]: data}
data_frame = pd.DataFrame(to_df)
data_frame.set_index("Index", inplace=True)
return data_frame | f9bb854af5d77f4355d64c8c56a9fdda7bd2cf93 | 11,668 |
def random_aes_key(blocksize=16):
"""Set 2 - Challenge 11"""
return afb(np.random.bytes(blocksize)) | f5bfad117886e51bbb810274c62e44e89ec2c79a | 11,669 |
import json
import torch
def create_and_load(directory: str,
name: str,
new_name: str = None) -> nn.Module:
"""Instantiate an unkown function (uf) required
by the high-order functions with a trained neural network
Args:
directory: directory to the saved we... | 1ebf471fb624918b52953748a4f275b22aeaba1a | 11,670 |
def select_region_climatedata(gcm_name, rcp, main_glac_rgi):
"""
Get the regional temperature and precipitation for a given dataset.
Extracts all nearest neighbor temperature and precipitation data for a given set of glaciers. The mean temperature
and precipitation of the group of glaciers is retu... | 8e2c4bf8a942b4a21d5549e9af87bacb75f92f26 | 11,671 |
def get_patch_boundaries(mask_slice, eps=2):
"""
Computes coordinates of SINGLE patch on the slice. Behaves incorrectly in the case of multiple tumors on the slice.
:mask_slice: 2D ndarray, contains mask with <0, 1, 2> values of pixels
:eps: int, number of additional pixels we extract ar... | 0af985273b3e509bf9ee2580a64c8ddd6392d5a7 | 11,672 |
from typing import Union
from typing import List
def get_sqrt_ggn_extension(
subsampling: Union[None, List[int]], mc_samples: int
) -> Union[SqrtGGNExact, SqrtGGNMC]:
"""Instantiate ``SqrtGGN{Exact, MC} extension.
Args:
subsampling: Indices of active samples.
mc_samples: Number of MC-samp... | 47f074a387d0a6182d93061cbaaf4fc397be26c0 | 11,673 |
def gray_to_rgb(image):
"""convert cv2 image from GRAYSCALE to RGB
:param image: the image to be converted
:type image: cv2 image
:return: converted image
:rtype: cv2 image
"""
return cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) | feede538a2822d6d7f36bb6bbe40c845ca55808d | 11,674 |
def win_to_cygwin(winpath):
"""run `cygpath winpath` to get cygwin path"""
x = detail.command.run(['cygpath', winpath])
assert(len(x) == 1)
return x[0] | 1f941628fae51cfca7621c62c454e80d984f7019 | 11,675 |
def nucleotide_composition_to_letter(composition):
"""
Converts dictionary of {nucleotide letter: proportion} pairs
to IUPAC degenerate DNA letter.
Usage:
c = {'A': 1}
print(nucleotide_composition_to_letter(c)) --> 'A'
c = dict(zip('ACGT', [1, 1, 1, 1]))
print(nucleotide_composition_to... | 2ad080d3a04cfc754f46d490a272362cadecbfd2 | 11,676 |
def forcast(doc):
"""
:param: doc object
:returns: tuple with grade level, age level
"""
word_tokens = doc.word_tokens
monosyllables = 0
for i in word_tokens:
if i.isalpha() == False and len(i) < 2:
word_tokens.remove(i)
for i in word_tokens[10:159]:
if sylla... | e71debbdaf057c61eaa620419b0357e603868989 | 11,677 |
def convert_coordinates_to_country(deg_x: float, deg_y: float) -> str:
""" returns country name """
return geocoder.osm([deg_x, deg_y], method="reverse").country | 5dca9d54bfa154a33a94550f983a3e9457cf2d52 | 11,678 |
def fixture_items(test_list):
"""Returns an instance of ItemCollection for testing"""
return test_list.get_items(query=QUERY) | 6351ffdb9ce8a65d7a08d55c6cfa9db8ef4aa978 | 11,679 |
def get_daily_discussion_post(subreddit_instance: praw.models.Subreddit):
"""Try to get the daily discussions post for a subreddit.
Args:
subreddit_instance
Returns:
The submission object for the discussion post, or None if it couldn't be found.
Works by searching the stickied posts of ... | 841612a8b2d2fa7a8a74f081e360a69884b20925 | 11,681 |
def metric_by_training_size(X, y, classifier_list, training_set, metric, as_percentage=True):
"""
This is a refactoriation of code to repeat metrics for best fitted models by training set percentage size.
i.e.: Find accuracy rating for multiple training-test splits for svm, random forests, and naive bayes a... | 3d918989b28db47479da3479b1804b7a502b9ce0 | 11,682 |
def remove_namespace(tag, ns):
"""Remove namespace from xml tag."""
for n in ns.values():
tag = tag.replace('{' + n + '}', '')
return tag | d4837a3d906baf8e439806ccfea76284e8fd9b87 | 11,684 |
def false_prediction_pairs(y_pred, y_true):
"""
Prints pairs of predicted and true classes that differ.
Returns
-------
false_pairs
The pairs of classes that differ.
counts
Number of occurences of the pairs.
"""
cond = y_pred != y_true
false_preds = np.stack([y_true[... | 460acb967b95d9e4c03e557e6bd1ede2dd7d0902 | 11,685 |
def draw_boxes_and_labels_to_image_multi_classes(image, classes, coords, scores=None, classes_name=None, classes_colors=None, font_color=[0, 0, 255]):
"""
Draw bboxes and class labels on image. Return or save the image with bboxes
Parameters
-----------
image : numpy.array
The RGB image [hei... | 5a11dd98019e5096c83137c43457a312598e2be8 | 11,686 |
def simulate():
"""
Runs a simulation given a context, a simulator, a trace, and a depth
Method PUT
"""
context = request.get_json()['context']
simulator = request.get_json()['simulator']
trace = request.get_json()['trace']
depth = request.get_json()['depth']
if context is None or si... | d905eb9fa34454588d4d1ab95794a6b9c41074ac | 11,688 |
def soft_expected_backup_rl(
next_q: Array,
next_pol: Array,
next_log_pol: Array,
rew: Array,
done: Array,
discount: float,
er_coef: float,
) -> Array:
"""Do soft expected bellman-backup :math:`r + \gamma P \langle \pi, q - \tau * \log{\pi}\rangle`.
Args:
next_q (Array): ? x... | fb1fed9946e05e4ad464f54c559be5e32c1f2e8e | 11,689 |
def generate_bias(series: pd.Series, effect_size: float = 1, power: float = 1) -> pd.Series:
"""
Calculate bias for sensitive attribute
Parameters
----------
series : pd.Series
sensitive attribute for which the bias is calculated.
effect_size : float, optional
Size of the bias f... | a23a201dfeac8ed25cb923080f9c968d1a8a6583 | 11,692 |
def get_thellier_gui_meas_mapping(input_df, output=2):
"""
Get the appropriate mapping for translating measurements in Thellier GUI.
This requires special handling for treat_step_num/measurement/measurement_number.
Parameters
----------
input_df : pandas DataFrame
MagIC records
outp... | ba32104db56cfdb450015a0a43f0717263d5ea44 | 11,694 |
import time
def new_unsigned_vaccination_credential(
passenger_first_name: str,
passenger_last_name: str,
passenger_id_number: str,
passenger_date_of_birth: str,
vaccination_disease: str,
vaccination_vaccine: str,
vaccination_product: str,
vaccination_auth_holder: str,
vaccination_... | e3a072e1d16a3520a5bad92e692e5f4de72e8b1d | 11,695 |
def calc_pk_integrated_intensities(p,x,pktype,num_pks):
"""
Calculates the area under the curve (integrated intensities) for fit peaks
Required Arguments:
p -- (m x u + v) peak parameters for number of peaks, m is the number of
parameters per peak ("gaussian" and "lorentzian" - 3, "pvoigt" - 4, "... | d3ab50d6e6e5d2187917e06a8258a46ac5d4db18 | 11,696 |
def read_fid_ntraces(filename, shape=None, torder='flat', as_2d=False,
read_blockhead=False):
"""
Read a Agilent/Varian binary (fid) file possibility having multiple
traces per block.
Parameters
----------
filename : str
Filename of Agilent/Varian binary file (fid) ... | d82f341326d089dad9def8a95b4233cf4dde607d | 11,697 |
import typing
async def async_get_erc20_decimals(
token: spec.ERC20Reference,
block: typing.Optional[spec.BlockNumberReference] = None,
**rpc_kwargs: typing.Any
) -> int:
"""get decimals of an erc20"""
return await erc20_generic.async_erc20_eth_call(
function_name='decimals', token=token, ... | 665c9e697caffd9470c4f71769c8d215ce7d14a0 | 11,698 |
def get_game_log(game_id: int):
"""
Method used to get list of important events of macau game with given game id.
:param game_id: integer value of existing game
:return: list with string with all important events in game
"""
if game_id >= len(games_container):
return JSONResponse(content... | 837b43b24f747fabb819fe5eeb3e284694fd02a3 | 11,699 |
import time
def time_this_function(func):
"""
Time the function.
use as a decorator.
Examples
---------
::
@time_this_function
def func(x):
return x
a= func(1)
Parameters
----------
func: Callable
function
Returns
-------
... | 6ee2d12dc2301e1c3efe2ca02548297aa83d316f | 11,701 |
def power_plot(data, sfreq, toffset, log_scale, zscale, title):
"""Plot the computed power of the iq data."""
print("power")
t_axis = np.arange(0, len(data)) / sfreq + toffset
if log_scale:
lrxpwr = 10 * np.log10(data + 1e-12)
else:
lrxpwr = data
zscale_low, zscale_high = zsca... | 06d7fab09c027ec2dbf7a11fa78f3b6fcd97e2d7 | 11,702 |
import torchvision
import torch
def load_dataset(dataset):
"""
Loads a dataset and returns train, val and test partitions.
"""
dataset_to_class = {
'mnist': torchvision.datasets.MNIST,
'cifar10': torchvision.datasets.CIFAR10,
'fa-mnist': torchvision.datasets.FashionMNIST
}
assert dataset in dataset_to_cla... | e17dcec84603a742cb6eec0fa18ad40af2454461 | 11,703 |
def compareTo(s1, s2):
"""Compares two strings to check if they are the same length and whether one is longer
than the other"""
move_slice1 = 0
move_slice2 = 1
if s1[move_slice1:move_slice2] == '' and s2[move_slice1:move_slice2] == '':
return 0 # return 0 if same length
elif s1[move_... | 4700360d10561227a6d4995c66953993dce1cea3 | 11,704 |
def is_unique(x):
# A set cannot contain any duplicate, so we just check that the length of the list is the same as the length of the corresponding set
"""Check that the given list x has no duplicate
Returns:
boolean: tells if there are only unique values or not
Args:
x (list): elemen... | 12b4513a71fc1b423366de3f48dd9e21db79e73a | 11,705 |
def str2format(fmt, ignore_types=None):
"""Convert a string to a list of formats."""
ignore_types = ignore_types if ignore_types else ()
token_to_format = {
"s": "",
"S": "",
"d": "g",
"f": "f",
"e": "e",
}
base_fmt = "{{:{}}}"
out = []
for i, token ... | 9cbe719abe6b37a0adcd52af250dfe768f850ffa | 11,706 |
from pathlib import Path
def _read_concordance(filename: Path, Sample_IDs: pd.Index) -> pd.DataFrame:
"""Create a flag of known replicates that show low concordance.
Given a set of samples that are known to be from the same Subject. Flag
samples that show low concordance with one or more replicates.
... | 2c7049ff5b521927ffbf863471fc23e073bce531 | 11,707 |
def load_image(name):
""" Get and cache an enaml Image for the given icon name.
"""
path = icon_path(name)
global _IMAGE_CACHE
if path not in _IMAGE_CACHE:
with open(path, 'rb') as f:
data = f.read()
_IMAGE_CACHE[path] = Image(data=data)
return _IMAGE_CACHE[path] | 6ce56c1a9d4d9e80d25a19aca239f43ebd119840 | 11,708 |
def add_shipment_comment(
tracking_id: str,
body: CreateComment = Body(...),
client: VBR_Api = Depends(vbr_admin_client),
):
"""Add a Comment to a Shipment.
Requires: **VBR_WRITE_PUBLIC**"""
tracking_id = sanitize_identifier_string(tracking_id)
shipment = client.get_shipment_by_tracking_id(... | d115d230bbf47a8f1cf625f0ab66e855f382244c | 11,709 |
def _mp2_energy(output_str):
""" Reads the MP2 energy from the output file string.
Returns the energy in Hartrees.
:param output_str: string of the program's output file
:type output_str: str
:rtype: float
"""
ene = ar.energy.read(
output_str,
app.one_of_the... | febd9f4c5759cb6150ff16bda2e9050199c48c5f | 11,711 |
def fastlcs(a,b,Dmax=None):
"""
return the length of the longest common substring or 0 if the maximum number of difference Dmax cannot be respected
Implementation: see the excellent paper "An O(ND) Difference Algorithm and Its Variations" by EUGENE W. MYERS, 1986
NOTE:
let D be the minim... | d8a88c7ffaae892e48a292b7a045da9f5dc58173 | 11,712 |
from typing import Optional
from typing import Mapping
def FeaturesExtractor( # pylint: disable=invalid-name
eval_config: config_pb2.EvalConfig,
tensor_representations: Optional[Mapping[
Text, schema_pb2.TensorRepresentation]] = None) -> extractor.Extractor:
"""Creates an extractor for extracting f... | 86e58783fca3ebb23de1e6b7ac9cdd4030e99c38 | 11,713 |
def assert__(engine, obj, condition, message=u'Assertion failed'):
""":yaql:assert
Evaluates condition against object. If it evaluates to true returns the
object, otherwise throws an exception with provided message.
:signature: obj.assert(condition, message => "Assertion failed")
:arg obj: object ... | c29e073bf6673ce0c89ed339c27f2287d6952991 | 11,714 |
from typing import Iterable
from typing import List
def build_level_codes(incoming_column_name: str, levels: Iterable) -> List[str]:
"""
Pick level names for a set of levels.
:param incoming_column_name:
:param levels:
:return:
"""
levels = [str(lev) for lev in levels]
levels = [incom... | 994ccc0673bd27dcce30709a97372c29d75a8e67 | 11,716 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get all rsyslog objects
"""
return isamAppliance.invoke_get("Get all rsyslog objects",
"/core/rsp_rsyslog_objs") | 55ff144577a9ef25b555ca3a37db65bfdb0f0af4 | 11,717 |
def genomic_dup1_37_loc():
"""Create test fixture GRCh37 duplication subject"""
return {
"_id": "ga4gh:VSL.CXcLL6RUPkro3dLXN0miGEzlzPYiqw2q",
"sequence_id": "ga4gh:SQ.VNBualIltAyi2AI_uXcKU7M9XUOuA7MS",
"interval": {
"type": "SequenceInterval",
"start": {"value": 4... | 470af80795c649bc0f4dd29393d1093c45c9f0da | 11,718 |
def parse(f, _bytes):
"""
Parse function will take a parser combinator and parse some set of bytes
"""
if type(_bytes) == Parser:
return f(_bytes)
else:
s = Parser(_bytes, 0)
return f(s) | 7f824c46477a384ce97f66806813f4b42412d6d8 | 11,719 |
def spiral_tm(wg_width=0.5, length=2):
""" sample of component cutback """
c = spiral_inner_io_euler(wg_width=wg_width, length=length, dx=10, dy=10, N=5)
cc = add_gratings_and_loop_back(
component=c,
grating_coupler=pp.c.grating_coupler_elliptical_tm,
bend_factory=pp.c.bend_circular,... | e7fcec9e61984d8f89558d7479cc942db389ba3a | 11,720 |
from typing import List
from typing import Tuple
def _chunk(fst: pynini.Fst) -> List[Tuple[str, str]]:
"""Chunks a string transducer into tuples.
This function is given a string transducer of the form:
il1 il2 il3 il4 il5 il6
ol1 eps eps ol2 eps ol3
And returns the list:
[(il1 ... | fa50e13062267e8929df5f538ab9a924822bc265 | 11,722 |
def auth_token_required(func):
"""Your auth here"""
return func | e65b94d40c914c57ff8d894409b664cf97aa790d | 11,723 |
def base_convert_money(amount, currency_from, currency_to):
"""
Convert 'amount' from 'currency_from' to 'currency_to'
"""
source = get_rate_source()
# Get rate for currency_from.
if source.base_currency != currency_from:
rate_from = get_rate(currency_from)
else:
# If curren... | 5417ba7a9d757bafc835df8f55a1d4e6de72cb2f | 11,724 |
async def contestant() -> dict:
"""Create a mock contestant object."""
return {
"id": "290e70d5-0933-4af0-bb53-1d705ba7eb95",
"first_name": "Cont E.",
"last_name": "Stant",
"birth_date": date(1970, 1, 1).isoformat(),
"gender": "M",
"ageclass": "G 12 år",
"... | 261fd560107489b58c645efb1bb9c19a396e0dce | 11,726 |
import requests
import http
def GetApitoolsTransport(timeout='unset',
enable_resource_quota=True,
response_encoding=None,
ca_certs=None,
allow_account_impersonation=True,
use_google_auth=None,
... | 21fc8d521703580a51c753811b7f0d401f68bba5 | 11,727 |
def user_requested_anomaly7():
""" Checks if the user requested an anomaly, and returns True/False accordingly. """
digit = 0
res = False
if is_nonzero_file7(summon_filename):
lines = []
with open(get_full_path(summon_filename)) as f:
lines = f.readlines()
if len(line... | bed54831c00deb6c11ce81c731fe37f35ef070b7 | 11,728 |
def mat_to_r(_line, _mat_object : MatlabObject, _r_object : RObject = RObject()):
"""Move variables from Matlab to R
Parameters
----------
_line : str, Iterable[str]
If str, one of the following:
1. '#! m[at[lab]] -> <vars>'
2. '<vars>'
where <vars> is a comma separated list of Matlab variable names
I... | 22f78c06bcf47a71596563debf6115c954d89e21 | 11,729 |
def RecalculatedEdgeDegreeAttack(G, remove_fraction = 1.0):
""" Recalculated Edge Degree Attack
"""
n = G.number_of_nodes()
m = int(G.number_of_edges() * (remove_fraction+0.0) )
tot_ND = [0] * (m + 1)
tot_T = [0] * (m + 1)
ND, ND_lambda = ECT.get_number_of_driver_nodes(G)
tot_ND[0] = ND... | ff88430f172a1ca319af9d637c292091cab2bf6f | 11,731 |
def get(url, params=None, headers=None):
"""Return the contents from a URL
Params:
- url (str): Target website URL
- params (dict, optional): Param payload to add to the GET request
- headers (dict, optional): Headers to add to the GET request
Example:
```
get('https://httpbin.org/an... | edb0fe25728fe1bd11d9e74509a630f2d3823af1 | 11,732 |
def get_param_num(model):
""" get the number of parameters
Args:
model:
Returns:
"""
return sum(p.numel() for p in model.parameters()) | 19d98a1bcbdcb827be4a657f82cda2ff09f119e4 | 11,733 |
from typing import Union
def format_tensor_to_ndarray(x: Union[ms.Tensor, np.ndarray]) -> np.ndarray:
"""Unify `mindspore.Tensor` and `np.ndarray` to `np.ndarray`. """
if isinstance(x, ms.Tensor):
x = x.asnumpy()
if not isinstance(x, np.ndarray):
raise TypeError('input should be one of [m... | 6e64a40bbafe2b2f89f5afd200077be369adcfe7 | 11,735 |
from typing import Pattern
import re
def hunt_csv(regex: Pattern, body: str) -> list:
"""
finds chunk of csv in a larger string defined as regex, splits it,
and returns as list. really useful only for single lines.
worse than StringIO -> numpy or pandas csv reader in other cases.
"""
csv_strin... | 9c5574f059ef05e6f99e468a9272f42393d79030 | 11,736 |
import re
def time_key(file_name):
""" provides a time-based sorting key """
splits = file_name.split('/')
[date] = re.findall(r'(\d{4}_\d{2}_\d{2})', splits[-2])
date_id = [int(token) for token in date.split('_')]
recording_id = natural_key(splits[-1])
session_id = session_key(splits[-2])
... | 07a5448b7b39b00780f53080b316981198d54c91 | 11,737 |
def sizeRange(contourList, low, high):
"""Only keeps contours that are in range for size"""
newList = []
for i in contourList:
if (low <= cv2.contourArea(i) <= high):
newList.append(i)
return newList | ac83b09acfd8d8e23a03965b52c5c4cc0361710d | 11,739 |
def number_field_choices(field):
"""
Given a field, returns the number of choices.
"""
try:
return len(field.get_flat_choices())
except AttributeError:
return 0 | b8776e813e9eb7471a480df9d6e49bfeb48a0eb6 | 11,740 |
def _is_an_unambiguous_user_argument(argument: str) -> bool:
"""Check if the provided argument is a user mention, user id, or username (name#discrim)."""
has_id_or_mention = bool(commands.IDConverter()._get_id_match(argument) or RE_USER_MENTION.match(argument))
# Check to see if the author passed a usernam... | adecc093a0597d43292171f867ebcf5a64edc7d8 | 11,741 |
def resize_image(image, size):
"""
Resize the image to fit in the specified size.
:param image: Original image.
:param size: Tuple of (width, height).
:return: Resized image.
:rtype: :py:class: `~PIL.Image.Image`
"""
image.thumbnail(size)
return image | 67db04eac8a92d27ebd3ec46c4946b7662f9c03f | 11,742 |
def one_hot_vector(val, lst):
"""Converts a value to a one-hot vector based on options in lst"""
if val not in lst:
val = lst[-1]
return map(lambda x: x == val, lst) | 401ff1d6666c392b3a217659929a4f7832c52522 | 11,743 |
def follow(request, username):
""" Add user with username to current user's following list """
request.user.followers.add(User.objects.get(username=username))
return redirect('accounts:followers') | 72530b32cfcb2282045cd2ef112df62a19e03239 | 11,744 |
def sesteva_stolpce(seznam_seznamov_stolpcev):
"""sešteje vse 'stolpce' v posameznem podseznamu """
matrika_stolpcev = []
for i in range(len(seznam_seznamov_stolpcev)):
sez = seznam_seznamov_stolpcev[i]
stolpec11 = sez[0]
while len(sez) > 1:
i = 0
stolpec22 = ... | fe69368a79b60e549983a07e140ec3b5e532868e | 11,745 |
def create_response(data={}, status=200, message=''):
"""
Wraps response in a consistent format throughout the API
Format inspired by https://medium.com/@shazow/how-i-design-json-api-responses-71900f00f2db
Modifications included:
- make success a boolean since there's only 2 values
- make messag... | 51346e3a92bdf93085b12eaccc99511b66a34bcf | 11,746 |
def do_sizes_match(imgs):
"""Returns if sizes match for all images in list."""
return len([*filter(lambda x: x.size != x.size[0], imgs)]) > 0 | 7da30972ecfd4d3cac3d21ff380255865ec3b5c8 | 11,747 |
def gaussian_sampling(len_x, len_y, num_samples, spread_factor=5, origin_ball=1):
"""
Create a gaussian sampling pattern where each point is sampled from a
bivariate, concatenated normal distribution.
Args:
len_x (int): Size of output mask in x direction (width)
len_y (int): ... | fce7396b02778aa832c5d24028fb1f55f1013b15 | 11,748 |
import json
def from_cx_jsons(graph_json_str: str) -> BELGraph:
"""Read a BEL graph from a CX JSON string."""
return from_cx(json.loads(graph_json_str)) | c61e415199ce0bfc610c1a4277aa8ba1b74a070a | 11,749 |
from typing import Tuple
def _calculate_dimensions(image: Image) -> Tuple[int, int]:
"""
Returns the width and height of the given pixel data.
The height of the image is the number of rows in the list,
while the width of the image is determined by the number of
pixels on the first row. It is assu... | 7e74f181839b70e45cb64ca8b8517ef663c7caf8 | 11,750 |
def cli(ctx, invocation_id):
"""Get a summary of an invocation, stating the number of jobs which succeed, which are paused and which have errored.
Output:
The invocation summary.
For example::
{'states': {'paused': 4, 'error': 2, 'ok': 2},
'model': 'WorkflowInvocation',
... | 94197a9c55c0d37b311585fdfce9d615c6986cb5 | 11,751 |
import numpy as np
def remove_observations_mean(data,data_obs,lats,lons):
"""
Removes observations to calculate model biases
"""
### Import modules
### Remove observational data
databias = data - data_obs[np.newaxis,np.newaxis,:,:,:]
return databias | 8f0cf60137660878f57dc35caa8c23896944d6ab | 11,752 |
import logging
def joint_extraction_model_fn(features, labels, mode, params):
"""Runs the node-level sequence labeling model."""
logging.info("joint_extraction_model_fn")
inputs = features # Arg "features" is the overall inputs.
# Read vocabs and inputs.
dropout = params["dropout"]
if params["circle_fea... | 1e6eb2028c8924733329bc4fc3079ca12af12d94 | 11,753 |
def make_ss_matrices(sigma_x, dt):
"""
To make Q full-rank for inversion (so the mle makes sense), use:
Q = [ dt**2 dt/2
dt/2 1 ]
to approximate Q = (dt 1)(dt 1)'
System:
x = [p_x p_y v_x v_y]
y = [p_x' p_y']
:param sigma_x:
:param dt:
:return:
sigma_0:... | 551a1d46ee67360e159ab966c0b3f30dd77254c8 | 11,755 |
def get_icp_val(tmr):
"""Read input capture value"""
return peek(tmr + ICRx) | (peek(tmr + ICRx + 1) << 8) | 0aef45e0c6edeb3c6540a51ae44013ded03c7be7 | 11,756 |
import torch
def validate(segmenter, val_loader, epoch, num_classes=-1):
"""Validate segmenter
Args:
segmenter (nn.Module) : segmentation network
val_loader (DataLoader) : training data iterator
epoch (int) : current epoch
num_classes (int) : number of classes to consider
Returns... | 716f1eda3a283c2707fa8ffd6e8073c351bda560 | 11,757 |
def detect_forward(CoreStateMachine, PostConditionStateMachine):
"""A 'forward ambiguity' denotes a case where the post condition
implementation fails. This happens if an iteration in the core pattern is a
valid path in the post- condition pattern. In this case no decision can be
made about where to res... | 4d6c1952a201f3505b0770f12f42609847728a54 | 11,758 |
def price_sensitivity(results):
"""
Calculate the price sensitivity of a strategy
results
results dataframe or any dataframe with the columns
open, high, low, close, profit
returns
the percentage of returns sensitive to open price
Note
-----
Price sensitivity is calc... | 02ab811bf689e760e011db6d091dcb7c3079f0d1 | 11,759 |
def wrap_zone(tz, key=KEY_SENTINEL, _cache={}):
"""Wrap an existing time zone object in a shim class.
This is likely to be useful if you would like to work internally with
non-``pytz`` zones, but you expose an interface to callers relying on
``pytz``'s interface. It may also be useful for passing non-`... | 7776153859b30ee758b16498b1122d0af294d371 | 11,760 |
async def async_browse_media(
hass, media_content_type, media_content_id, *, can_play_artist=True
):
"""Browse Spotify media."""
info = list(hass.data[DOMAIN].values())[0]
return await async_browse_media_internal(
hass,
info[DATA_SPOTIFY_CLIENT],
info[DATA_SPOTIFY_ME],
me... | d3f912ecbd8949a637d461a453a4b9a9ea73a20c | 11,761 |
from typing import Tuple
import json
def bounds(url: str) -> Tuple[str, str, str]:
"""Handle bounds requests."""
info = main.bounds(url)
return ("OK", "application/json", json.dumps(info)) | 2da1ec2db8b2c0c3a3d28854dc2f68b71aa96bf1 | 11,762 |
import email
def make_message_id():
"""
Generates rfc message id. The returned message id includes the angle
brackets.
"""
return email.utils.make_msgid('sndlatr') | 7030efe1d61f4e54d833bb5c808f582689c626c6 | 11,763 |
def _understand_err_col(colnames):
"""Get which column names are error columns
Examples
--------
>>> colnames = ['a', 'a_err', 'b', 'b_perr', 'b_nerr']
>>> serr, terr = _understand_err_col(colnames)
>>> np.allclose(serr, [1])
True
>>> np.allclose(terr, [2])
True
>>> serr, terr =... | 2fab9346a3ea8fa6e84e406856eef8ad14ad9f66 | 11,764 |
def unpivot(frame):
"""
Example:
>>> df
date variable value
0 2000-01-03 A 0.895557
1 2000-01-04 A 0.779718
2 2000-01-05 A 0.738892
3 2000-01-03 B -1.513487
4 2000-01-04 B -0.543134
5 2000-01-05 B 0.902733
6 20... | 6cda1c29e7e7c9b4176e83b6a0e1d907458721b2 | 11,765 |
import type
def find_viable_generators_aux (target_type, prop_set):
""" Returns generators which can be used to construct target of specified type
with specified properties. Uses the following algorithm:
- iterates over requested target_type and all it's bases (in the order returned bt
t... | 40764a16b17b54c28495e08623d616d0927451d1 | 11,766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.