content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def my_model_builder(my_model: MyModel) -> KerasModel:
"""Build the siamese network model """
input_1 = layers.Input(my_model.input_shape)
input_2 = layers.Input(my_model.input_shape)
# As mentioned above, Siamese Network share weights between
# tower networks (sister networks). To allow this, we w... | 53b32468469e7fc8cbc8f2776a1711181363bf60 | 6,600 |
from datetime import datetime
def create_embed(
title,
description,
fields = None,
colour = None,
timestamp = datetime.utcnow(),
author = None,
author_icon = None,
thumbnail = None,
image = None,
footer = None
):
"""Create an Embed
Args:
title (str): Set title
... | 741238fc50e2eda98a5cbfeab0c5c4d5cb3adbf2 | 6,601 |
def autoCalibration(I):
"""Returns horizontal and vertical factors by which every distance in
pixels should be multiplied in order to obtain the equivalent distance in
millimeters. This program assumes that the scale presents clear axis ticks and
that the distance between two biggest ticks is equal to 1... | 30016c41a8b21531cfd277a669a6b16b01322387 | 6,602 |
def reverse_handler(handler_input):
"""Check if a verb is provided in slot values. If provided, then
looks for the paradigm in the irregular_verbs file.
If not, then it asks user to provide the verb again.
"""
# iterate over the dictionaries in irregular_verbs.py and looks for
# the verb in the... | f1b49b88314f3218af03c6910d72729f888f2a11 | 6,603 |
def load_wrf_data(filename):
"""Load required data form the WRF output file : filename"""
base_data=load_vars(filename,wrfvars)
skin_t=load_tskin(filename,tsvar,landmask)
base_data.append(skin_t)
atts=mygis.read_atts(filename,global_atts=True)
return Bunch(data=base_data,global_atts=at... | da6439d3d4adfc8b84d5bf5911aa5e4b9d628baa | 6,604 |
def DensityRatio_QP(X_den, X_num, kernel, g, v_matrix, ridge=1e-3):
"""
The function computes a model of the density ratio.
The function is in the form $A^T K$
The function returns the coefficients $\alpha_i$ and the bias term b
"""
l_den, d = X_den.shape
l_num, d_num = X_num.shape
# TO... | 945f0fe26a1cea10a85e20944a5fe0d0f9c6427b | 6,605 |
def sanitize_date(date_dict: dict):
"""
Function to take the date values entered by the user and check their validity. If valid it returns True,
otherwise it sets the values to None and returns False
:param date_dict:
:return:
"""
month = date_dict["month"]
day = date_dict["day"]
ye... | c8cc01c8c1259ab8c4b263e36ae9f85a95356017 | 6,606 |
def create_scale(tonic, pattern, octave=1):
"""
Create an octave-repeating scale from a tonic note
and a pattern of intervals
Args:
tonic: root note (midi note number)
pattern: pattern of intervals (list of numbers representing
intervals in semito... | f9337289fda2e1b08cd371d3e91cc5a23c9c9822 | 6,607 |
def _qfloat_append(qf, values, axis=None):
"""Implement np.append for qfloats."""
# First, convert to the same unit.
qf1, qf2 = same_unit(qf, values, func=np.append)
nominal = np.append(qf1.nominal, qf2.nominal, axis)
std = np.append(qf1.uncertainty, qf2.uncertainty, axis)
return QFloat(nominal,... | 46049a2ba43997578ae502acd395cfa767e623ca | 6,608 |
from typing import List
def filter_by_mean_color(img:np.ndarray, circles:List[Circle], threshold=170) -> List[Circle]:
"""Filter circles to keep only those who covers an area which high pixel mean than threshold"""
filtered = []
for circle in circles:
box = Box(circle=circle)
area = box.ge... | d23f92d363cd4df70ba0d0d01450865546d7f289 | 6,609 |
def ParseSortByArg(sort_by=None):
"""Parses and creates the sort by object from parsed arguments.
Args:
sort_by: list of strings, passed in from the --sort-by flag.
Returns:
A parsed sort by string ending in asc or desc.
"""
if not sort_by:
return None
fields = []
for field in sort_by:
... | cc2c40d8d810396420e5c3ede0d65159ed21d6bc | 6,610 |
def dense_to_text(decoded, originals):
"""
Convert a dense, integer encoded `tf.Tensor` into a readable string.
Create a summary comparing the decoded plaintext with a given original string.
Args:
decoded (np.ndarray):
Integer array, containing the decoded sequences.
... | d7d4ec6ef2653a4e9665711201cef807a6c9830b | 6,611 |
def admin_view_all_working_curriculums(request):
""" views all the working curriculums offered by the institute """
user_details = ExtraInfo.objects.get(user = request.user)
des = HoldsDesignation.objects.all().filter(user = request.user).first()
if str(des.designation) == "student" or str(des.designat... | 8ba99fe5712c8a93b62e2ab0c9e22594a442d9bd | 6,612 |
def getEmuAtVa(vw, va, maxhit=None):
"""
Build and run an emulator to the given virtual address
from the function entry point.
(most useful for state analysis. kinda heavy though...)
"""
fva = vw.getFunction(va)
if fva == None:
return None
cbva,cbsize,cbfva = vw.getCodeBlock(v... | bea812a1d74b39e9ba83fde56bf90e4055425b89 | 6,613 |
def _create_test_validity_conditional(metric):
"""Creates BigQuery SQL clauses to specify validity rules for an NDT test.
Args:
metric: (string) The metric for which to add the conditional.
Returns:
(string) A set of SQL clauses that specify conditions an NDT test must
meet to be c... | 8c65150bdbed3ba75546fc64d8b322d9950339c1 | 6,614 |
from typing import Union
from typing import Sequence
def tfds_train_test_split(
tfds: tf.data.Dataset,
test_frac: float,
dataset_size: Union[int, str],
buffer_size: int = 256,
seed: int = 123,
) -> Sequence[Union[tf.data.Dataset, tf.data.Dataset, int, int]]:
"""
!!! does not properly work,... | 8bbb554eca8a09716279a5d818e1cc3e7bd5ad16 | 6,615 |
from datetime import datetime
def seconds_to_hms(seconds):
"""
Convert seconds to H:M:S format.
Works for periods over 24H also.
"""
return datetime.timedelta(seconds=seconds) | e862be76c6ef6b76f8e4f6351e033193ddefd5b8 | 6,616 |
import argparse
import multiprocessing
def parse_args(args):
"""
Takes in the command-line arguments list (args), and returns a nice argparse
result with fields for all the options.
Borrows heavily from the argparse documentation examples:
<http://docs.python.org/library/argparse.html>
"""
... | 9ab9bad96af383a8d7441d7ccb0da10ae68dafb5 | 6,617 |
def _add_spot_2d(image, ground_truth, voxel_size_yx, precomputed_gaussian):
"""Add a 2-d gaussian spot in an image.
Parameters
----------
image : np.ndarray, np.uint
A 2-d image with shape (y, x).
ground_truth : np.ndarray
Ground truth array with shape (nb_spots, 4).
- coord... | 45c32a181df1d0239b0ad872d7c0ad83862338ed | 6,618 |
import requests
def bing(text, bot):
"""<query> - returns the first bing search result for <query>"""
api_key = bot.config.get("api_keys", {}).get("bing_azure")
# handle NSFW
show_nsfw = text.endswith(" nsfw")
# remove "nsfw" from the input string after checking for it
if show_nsfw:
t... | 5aa5fe7acdc64c815d4a8727b06c13f1e3e3b2ce | 6,619 |
from typing import List
def single_length_RB(
RB_number: int, RB_length: int, target: int = 0
) -> List[List[str]]:
"""Given a length and number of repetitions it compiles Randomized Benchmarking
sequences.
Parameters
----------
RB_number : int
The number of sequences to construct.
... | dda3f5a191c666460fc4c791c33530940986b623 | 6,620 |
def decode(text_file_abs_path, threshold=10):
"""
Decodes a text into a ciphertext.
Parameters
---------
text_file_abs_path: str
Returns
-------
ciphertext: str
"""
try:
with open(text_file_abs_path, "rb") as f:
text = f.read()
except Exc... | c0c8c96438baedda43940e2373edc4714511b507 | 6,621 |
def templatetag(parser, token):
"""
Outputs one of the bits used to compose template tags.
Since the template system has no concept of "escaping", to display one of
the bits used in template tags, you must use the ``{% templatetag %}`` tag.
The argument tells which template bit to output:
... | 3b441ec3035f8efde9fd2507ab83c83ec5940a7a | 6,622 |
def reflected_phase_curve(phases, omega, g, a_rp):
"""
Reflected light phase curve for a homogeneous sphere by
Heng, Morris & Kitzmann (2021).
Parameters
----------
phases : `~np.ndarray`
Orbital phases of each observation defined on (0, 1)
omega : tensor-like
Single-scatter... | e6f9fadaec4614b5ea0058d13956cb5ef13d57b5 | 6,623 |
from operator import pos
def costspec(
currencies: list[str] = ["USD"],
) -> s.SearchStrategy[pos.CostSpec]:
"""Generates a random CostSpec.
Args:
currencies: An optional list of currencies to select from.
Returns:
A new search strategy.
"""
return s.builds(pos.CostSpec, curr... | 4147a7046e5d4b16a6f919d77683a849ceb2ce54 | 6,624 |
import gzip
import os
import json
def get_gene_names_conversion():
"""Get the compressed file containing two-way mappings of gene_id to gene_symbol"""
with gzip.open(
os.path.join(
current_app.config["FIVEX_DATA_DIR"], "gene.id.symbol.map.json.gz",
),
"rt",
) as f:
... | d04aef6993c3f5c2309c518798978e4fc225c8e9 | 6,625 |
import json
import base64
def _process_input(data, context):
""" Pre-process request input before it is sent to TensorFlow Serving REST API
Args:
data (obj): the request data stream
context (Context): an object containing request and configuration details
Returns:
(dict): a JSON-... | 542e9d04a8e93cb835f049ebd3c9105e24e3b5ac | 6,626 |
def similarity_matrix_2d(X, Y, metric='cos'):
"""
Calculate similarity matrix
Parameters:
X: ndarray
input matrix 1
Y: ndarray
input matrix 2
distFunc: function
distance function
Returns:
result: ndarray
similarity matrix
"""
n_X ... | 02d78531347c3acb90049505297c009c845e27d2 | 6,627 |
def issue_list_with_tag(request, tag=None, sortorder=None):
"""
For a tag. display list of issues
"""
if tag:
stag = "\"%s\"" % tag
issues = Issue.tagged.with_any(stag)
tag_cloud = []
if issues:
tag_cloud = get_tagcloud_issues(issues)
issues = iss... | 1f51db85a0b5008819fda73d3d86fa184b56b327 | 6,628 |
def update_deal(id, deal_dict):
"""
Runs local validation on the given dict and gives passing ones to the API to update
"""
if utils.validate_deal_dict(utils.UPDATE, deal_dict, skip_id=True):
resp = utils.request(utils.UPDATE, 'deals', {'id': id}, data=deal_dict)
return utils.parse(resp)... | 82355c1a0204128f30b66a91fc22e3650b99f74d | 6,629 |
def plot_tilt_hist(series, ntile: str, group_name: str, extra_space: bool = True):
"""
Plots the histogram group tilts for a single ntile
:param series: frame containing the avg tilts, columns: group, index: pd.Period
:param ntile: the Ntile we are plotting for
:param group_name: the name of the gro... | 8f3077831cd11092e2a14bc60152ba693c0da6a6 | 6,630 |
def get_constraints_for_x(cell, board):
"""
Get the constraints for a given cell cell
@param cell Class instance of Variable; a cell of the Sudoku board
@param board
@return Number of constraints
"""
nconstraints = 0
# Row
for cellj in board[cell.row][:cell.col]:
if cellj.... | a46cda54569a12e80b9d52896f07335480799cb1 | 6,631 |
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print average([20, 30, 70])
40.0
"""
try:
return stats.mean(values)
except ZeroDivisionError:
return None | 85d02529404301891e0ecd1f2a9b76695a357504 | 6,632 |
def get_subgraph_pos(G, pos):
""" Returns the filtered positions for subgraph G. If subgraph = original graph then pos will be returned.
Parameters
----------
G : nx.Graph
A graph object.
Pos : dict
A dictionary with nodes as keys and positions as values.
Example
-------... | ca7fc389cc51aaace7a751f2107fe5cfbfd22e6c | 6,633 |
def _calculateWindowPosition(screenGeometry, iconGeometry, windowWidth, windowHeight):
"""
Calculate window position near-by the system tray using geometry of a system tray
and window geometry
@param screenGeometry: geometry of the screen where system tray is located
@type screenGeometry: QRect
... | 112011828dcfd0a6a54b6fe2c3d8acd92baf6c64 | 6,634 |
def build_from_config(config: dict, name: str) -> HomingMotor:
"""Build the named HomingMotor from data found in config"""
def check_for_key(key, cfg):
if key not in cfg:
raise RuntimeError('Key "{}" for HomingMotor "{}" not found.'.format(key, name))
else:
return cfg[ke... | ce39fc8db48da8145b9221120c3ec02f3bdda40f | 6,635 |
def arg_return_greetings(name):
"""
This is greeting function with arguments and return greeting message
:param name:
:return:
"""
message = F"hello {name}"
return message | 23bab521832358692c3aa653c6138ffee13c4e7a | 6,636 |
from typing import Any
def basic_usage(card_id: str, parent: Any = None):
"""Basic usage of the application, minus the card recognition bits"""
data = pull_card_data(card_id)
qt_window = Card(parent, data)
qt_window.setWindowTitle("YGO Scanner")
qt_window.show()
return qt_window | 6960697ef12959a7aaaf47607c3026d0925b0a88 | 6,637 |
from typing import Dict
from typing import Optional
from pathlib import Path
import json
def get_abi(
contract_sources: Dict[str, str],
allow_paths: Optional[str] = None,
remappings: Optional[list] = None,
silent: bool = True,
) -> Dict:
"""
Generate ABIs from contract interfaces.
Argumen... | bd9eb4959796d549950f8dd0372ee42c95cd0dd6 | 6,638 |
def predict(w , b , X ):
"""
使用学习逻辑回归参数logistic (w,b)预测标签是0还是1,
参数:
w - 权重,大小不等的数组(num_px * num_px * 3,1)
b - 偏差,一个标量
X - 维度为(num_px * num_px * 3,训练数据的数量)的数据
返回:
Y_prediction - 包含X中所有图片的所有预测【0 | 1】的一个numpy数组(向量)
"""
m = X.shape[1] #图片的数量
Y_prediction ... | 4e258d7de1788d6da5c8a832ff11a5e8718b5d84 | 6,639 |
def delta_C(parcels_old, parcels_new, normed=False):
"""
Compute the number of vertices that change connected component from
old parcellation to new parcellation.
Parameters:
- - - - -
parcels_old : dictionary
old connected component sample assignments
parcels_new : dictionary
... | 07f48d30fbaa4b0278871b199d7768c6f2d49508 | 6,640 |
def increment(number):
"""Increases a given number by 1"""
return number + 1 | ad10a887ee571182247e76fe41fddd6d53b2dc6a | 6,641 |
def get_recent_added_companies(parser, token):
"""
Gets any number of the recent added comapnies.
Syntax::
{% get_recent_added_companies [limit] as [var_name] %}
"""
return base_tag(parser, token, RecentCreatedCompanies) | 73c7c0f12951ba9d6b6a3220c2f88055ea027624 | 6,642 |
import glob
def search_data(templates, pols, matched_pols=False, reverse_nesting=False, flatten=False):
"""
Glob-parse data templates to search for data files.
Parameters
----------
templates : str or list
A glob-parsable search string, or list of such strings, with a {pol}
spot f... | 9f8018de15db0659928e28779ebf4acda0ddba74 | 6,643 |
import re
def normalize_word(word):
"""
:type word: str
:rtype: str
"""
acronym_pattern = r'^(?:[A-Z]\.)+$'
if re.match(pattern=acronym_pattern, string=word):
word = word.replace('.', '')
if word.lower() in _REPLACE_WORDS:
replacement = _REPLACE_WORDS[word.lower()]
if word.islower():
return replaceme... | e2c96d456cc8b555b68f2c7498a6d2898ce5990e | 6,644 |
def _ggm_qsize_prob_gt_0_whitt_5_2(arr_rate, svc_rate, c, ca2, cs2):
"""
Return the approximate P(Q>0) in G/G/m queue using Whitt's simple
approximation involving rho and P(W>0).
This approximation is exact for M/M/m and has strong theoretical
support for GI/M/m. It's described by Whitt as "crude" ... | 3eded5597dc199e61c4d79187369e1a84531ac3d | 6,645 |
def pds3_label_gen_date(file):
"""Returns the creation date of a given PDS3 label.
:param path: File path
:type path: str
:return: Creation date
:rtype: str
"""
generation_date = "N/A"
with open(file, "r") as f:
for line in f:
if "PRODUCT_CREATION_TIME" in line:
... | c2877fa9246dd0c12c6ea47635ab248dc038b179 | 6,646 |
def harmony(*args):
"""
Takes an arbitrary number of floats and prints their harmonic
medium value. Calculation is done with formula:
number_of_args \ (1 \ item1 + 1 \ item2 + ...)
Args:
*args (tuple): number of arguments with a type: float, integer
Returns:
float: harmonic... | bc66276b3ef27ef0bfd059afa8ca7afd5d9cbb82 | 6,647 |
def node_gdf_from_graph(G, crs = 'epsg:4326', attr_list = None, geometry_tag = 'geometry', xCol='x', yCol='y'):
"""
Function for generating GeoDataFrame from Graph
:param G: a graph object G
:param crs: projection of format {'init' :'epsg:4326'}. Defaults to WGS84. note: here we are defining the crs of... | cf5849c672877010aae7b1fb841a6993a53d232f | 6,648 |
def views():
""" Used for the creation of Orientation objects with
`Orientations.from_view_up`
"""
return [[1, 0, 0], [2, 0, 0], [-1, 0, 0]] | 21ffce8e8a56cf31e2d03a6384d584bcb4bfb2c8 | 6,649 |
from sys import path
def savePlot(widget, default_file_type, old_file_path=None):
"""Saves a plot in the specified file format.
:param widget: graphics widget.
:param default_file_type: default save file type.
:param old_file_path: file path from a previous save operation.
:return: returns file p... | 5f1a9ab9f8bf9854716737fe59bf8f95710ab2be | 6,650 |
def check_closed(f):
"""Decorator that checks if connection/cursor is closed."""
def g(self, *args, **kwargs):
if self.closed:
raise exceptions.Error(f'{self.__class__.__name__} already closed')
return f(self, *args, **kwargs)
return g | 4772de94c28022266ee01f0c900e8937859cc58c | 6,651 |
import os
import subprocess
import example
import pickle
def generate_glove_vecs(revs):
"""
This function generates GloVe vectors based on the training data. This function
can be more optimized in future.
:return: A dictionary containing words as keys and their GloVe vectors as the corresponding ... | 4f252bd2208d55b71b59c249b2c83e7bda12b325 | 6,652 |
def get_diff_comparison_score(git_commit, review_url, git_checkout_path,
cc): # pragma: no cover
"""Reads the diff for a specified commit
Args:
git_commit(str): a commit hash
review_url(str): a rietveld review url
git_checkout_path(str): path to a local git checkout
c... | b68904a62d1e42b8e147705984c9455ff0f5d6fc | 6,653 |
def pack(pieces=()):
"""
Join a sequence of strings together.
:param list pieces: list of strings
:rtype: bytes
"""
return b''.join(pieces) | ffd0852a16c6292f921e5cf205301171e3a96fd3 | 6,654 |
def options():
"""
pylbm command line options
"""
parser = ArgumentParser()
logging = parser.add_argument_group('log')
logging.add_argument("--log", dest="loglevel", default="WARNING",
choices=['WARNING', 'INFO', 'DEBUG', 'ERROR'],
help="Set the ... | e3df9ee1128dccf09eae9b6cde53aab24e639e8b | 6,655 |
def compte_var(f, var):
"""compte le nombre d'apparition de la variable var dans f"""
n = f.nb_operandes()
if n == 0:
v = f.get_val()
if v == var:
return 1
else:
return 0
elif n == 1:
f2 = (f.decompose())[0]
return compte_var(f2, var)
e... | 002051e3bf723cfcc1a2cb3d094b58980591adc5 | 6,656 |
from watchlist.models import User
def inject_vars(): # 函数名可以随意修改
"""模板上下文处理函数"""
user = User.query.first() # 用户对象
if not user:
user = User()
user.name = 'BL00D'
return locals() | edf9126fb919cb825acac3f951f481575fe2ef57 | 6,657 |
def try_parse_section(text: str, section_name: str) -> str:
"""
Parse a section. Return an empty string if section not found.
Args:
text (str): text
section_name (str): section's name
Returns:
(str): section
"""
try:
return parse_section(text, section_name)
... | 26c8d6d3f8475954fcf742e662981ad5f1223e53 | 6,658 |
from bs4 import BeautifulSoup
def get_location_based_lifers(web_page):
"""
a method that takes in a web page and returns back location frequency for lifers and lifer details.
"""
bs4_object = BeautifulSoup(web_page, html_parser)
table_list = bs4_object.find_all('li', class_=myebird_species_li_clas... | 1c6b85962f6c142ab816255a1fe5c98f272dfebb | 6,659 |
def parse_show_qos_queue_profile(raw_result):
"""
Parse the show command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the 'show qos queue-profile' command in a \
dictionary:
for 'show qos queue-profile':
::
{
... | 2a883a50663607356e0edadeb2d4cf17d34ab028 | 6,660 |
import random
import io
def plot_png(num_x_points=50):
""" renders the plot on the fly.
"""
fig = Figure()
axis = fig.add_subplot(1, 1, 1)
x_points = range(num_x_points)
axis.plot(x_points, [random.randint(1, 30) for x in x_points])
output = io.BytesIO()
FigureCanvasAgg(fig).print_png... | bac5e9146bf0b60d943e5d58376a84eddebd21ec | 6,661 |
def render_message(session, window, msg, x, y):
"""Render a message glyph.
Clears the area beneath the message first
and assumes the display will be paused
afterwards.
"""
# create message box
msg = GlyphCoordinate(session, msg, x, y)
# clear existing glyphs which intersect
for gl... | 2f0362dfa1f884571339456b0a610e0f6cdd75a6 | 6,662 |
from pathlib import Path
def part_one(filename='input.txt', target=2020):
"""Satisfies part one of day one by first sorting the input rows so we can
avoid the worst case O(n**2). We incur O(n log n) to do the sort followed by
a brute force search with short circuiting if the sum exceeds our target.
Th... | d9c6790f9c5b5de7fbd9555a8483f2cb0e156b3b | 6,663 |
def get_urls(name, version=None, platform=None):
"""
Return a mapping of standard URLs
"""
dnlu = rubygems_download_url(name, version, platform)
return dict(
repository_homepage_url=rubygems_homepage_url(name, version),
repository_download_url=dnlu,
api_data_url=rubygems_api_... | d11666a72771187166a6b9f620237639fd8422f3 | 6,664 |
def getEHfields(m1d, sigma, freq, zd, scaleUD=True, scaleValue=1):
"""Analytic solution for MT 1D layered earth. Returns E and H fields.
:param discretize.base.BaseMesh, object m1d: Mesh object with the 1D spatial information.
:param numpy.ndarray, vector sigma: Physical property of conductivity correspond... | e850762955ff513adef7099b61eb285d059c1ffe | 6,665 |
def repeated(f, n):
"""Returns a function that takes in an integer and computes
the nth application of f on that integer.
Implement using recursion!
>>> add_three = repeated(lambda x: x + 1, 3)
>>> add_three(5)
8
>>> square = lambda x: x ** 2
>>> repeated(square, 2)(5) # square(square(... | dd2024ffa7c5abbcfb43b1a6a8d6ea00c3fb42c4 | 6,666 |
def method_functions():
"""
Returns a dictionary containing the valid method keys and their
corresponding dispersion measure functions.
"""
return _available | 6d9ea23e4c0449b4b2d0a27b5117be30400a7d43 | 6,667 |
import os
def get_file_names(maindir, sessid, expid, segid, date, mouseid,
runtype="prod", mouse_dir=True, check=True):
"""
get_file_names(maindir, sessionid, expid, date, mouseid)
Returns the full path names of all of the expected data files in the
main directory for the specifi... | 7dee7e6b801f4b9270f87b9eaaf256a64cffaf58 | 6,668 |
def generate_auth_token():
"""Generate a token using jwt.
Returns:
token.
"""
key = PRIVATE_KEY
data = {'appId': APPLICATION_ID}
token = jwt.encode(data, key, algorithm='RS256')
return token | a2e9307f392a8a6c0d83e9f1064475c11fc4eeec | 6,669 |
from typing import Dict
from typing import Any
from typing import List
def dict_expand(d: Dict[Any, Any]) -> List[Dict[Any, Any]]:
"""Converts a dictionary of lists to a list of dictionaries.
The resulting list will be of the same length as the longest dictionary
value. If any values are not lists then t... | 6ca2c25318a3b6bc0b2a45bf3aeec7187ad78e5c | 6,670 |
def get_asexual_lineage_num_discrete_state_changes(lineage, attribute_list):
"""Get the number of discrete state changes from an asexual lineage.
State is described by the aggregation of all attributes give by attribute list.
Args:
lineage (networkx.DiGraph): an asexual lineage
attribute_l... | 9c0d4badc7b4fea70c56ce69727e48eb991a96e1 | 6,671 |
def check_downloaded(dataset: str,
directory: str = None) -> bool:
"""
Check whether dataset is downloaded
Args:
dataset (str): String of dataset's name, e.g. ml-100k, bx
directory (str, optional): String of directory of downloaded data.
Defaults to None... | bf3342e7da11b34918bc2cb9939c95145d2f4feb | 6,672 |
from pathlib import Path
def enterprise_1_9_installer() -> Path:
"""
Return the path to an installer for DC/OS Enterprise 1.9.
"""
return Path('/tmp/dcos_generate_config_1_9.ee.sh') | 857b5d339e05cbb225189d7ee47d0415fc539c54 | 6,673 |
def Laplacian(n):
"""
Create Laplacian on 2-dimensional grid with n*n nodes
"""
B = forward_diff_matrix(n)
D = -B.T @ B
Dx = sparse.kron(sparse.eye(n), D).tocsr()
Dy = sparse.kron(D, sparse.eye(n)).tocsr()
return Dx + Dy | 47d70e635dc8e7d722e069435d17214a6ea3c6de | 6,674 |
import re
def LookupGitSVNRevision(directory, depth):
"""
Fetch the Git-SVN identifier for the local tree.
Parses first |depth| commit messages.
Errors are swallowed.
"""
if not IsGitSVN(directory):
return None
git_re = re.compile(r'^\s*git-svn-id:\s+(\S+)@(\d+)')
proc = RunGitCommand(directory, ... | 664da44ee6057a62eb8ece161ade5cabac15bc7b | 6,675 |
def collect_jars(
dep_targets,
dependency_analyzer_is_off = True,
unused_dependency_checker_is_off = True,
plus_one_deps_is_off = True):
"""Compute the runtime and compile-time dependencies from the given targets""" # noqa
if dependency_analyzer_is_off:
return _collect_... | 10203c31bb2d1b5df9336d606355b497f7dd755a | 6,676 |
def _cred1_adapter(user=None, password=None):
"""Just a sample adapter from one user/pw type to another"""
return dict(user=user + "_1", password=password + "_2") | 9e7c218d2dc01793cba232ba1f6d69a54bf21fee | 6,677 |
def acc_metric(y_true, y_pred):
"""
Accuracy
"""
diff = K.abs(y_pred - y_true) * 5000
return K.mean(diff, axis=-1) | 0722791db5546f16648f74b8927590de8696e3d5 | 6,678 |
async def confirm(message: discord.Message, fallback: str = None) -> bool:
"""
Helper function to send a checkmark reaction on a message. This would be
used for responding to a user that an action completed successfully,
without sending a whole other message. If a checkmark reaction cannot
be added,... | 2567957d4239605072bd4f707c12e2b265b8cfbe | 6,679 |
def get_layer_version(
lambda_client: BaseClient,
layer_name: str,
version: int,
) -> "definitions.LambdaLayer":
"""Retrieve the configuration for the specified lambda layer."""
return definitions.LambdaLayer(
lambda_client.get_layer_version(
LayerName=layer_name,
Ver... | cfa2121ac757ae24b67bb25f7fd3046f017df85d | 6,680 |
import requests
def get_detail_msg(detail_url):
"""
2.获取某个职位的详细数据
:param detail_url: 职位详细页面的url
:return: 职位数据
"""
# print('请求的详细地址是:' + detail_url)
response = requests.get(detail_url, headers=HEADERS)
html_element = etree.HTML(response.text)
position = {}
# 【数据】获取职位标题
title = html_element.xpath('//tr[@cl... | 2fc5b316abed9eb9aeff99ae87cdd8e5e59a5e70 | 6,681 |
def wizard_process_received_form(form):
""" Processing of form received during the time measure
Expected result example: {1: '00:43.42', 2: '00:41.35', 3: '00:39.14', 4: '00:27.54'}
"""
lines = {key.split('_')[1]: value.split('_')[1] for key, value in form.items() if key.startswith("line")}
# print(... | 54b10589cab7ce689b64f5373d2f0a998044db82 | 6,682 |
import inspect
def getsource(obj,is_binary=False):
"""Wrapper around inspect.getsource.
This can be modified by other projects to provide customized source
extraction.
Inputs:
- obj: an object whose source code we will attempt to extract.
Optional inputs:
- is_binary: whether the obje... | 9e97a030c695b9ea50d27abc5253e47be7d4c06a | 6,683 |
import re
def extract_sector_id(room):
"""Given a room identifier of the form:
'aaa-bbb-cc-d-e-123[abcde]'
Return the sector id:
'123'
"""
m = re.search(r'(?P<sector_id>\d+)', room)
return m.group('sector_id') if m else None | f5bfb64d32769cd4b6c2b7309d41450fa807d7a2 | 6,684 |
def splitext_all(_filename):
"""split all extensions (after the first .) from the filename
should work similar to os.path.splitext (but that splits only the last extension)
"""
_name, _extensions = _filename.split('.')[0], '.'.join(_filename.split('.')[1:])
return(_name, "."+ _extensions) | bf9e4ee06eb30dfeb7898ce6e34607bef20b290b | 6,685 |
def catch(func, *args, **kw):
"""Catch most exceptions in 'func' and prints them.
Use to decorate top-level functions and commands only.
"""
# d:
print("calling %s with args %s, %s" % (func.__name__, args, kw))
try:
return func(*args, **kw)
except Exception as e:
print(e)
... | bca64becacb6121afff6d5ecaa14b1a2ef2ef3dc | 6,686 |
def tag_in_tags(entity, attribute, value):
"""
Return true if the provided entity has
a tag of value in its tag list.
"""
return value in entity.tags | ad88be5f8848b387f2a261ce5506dffde285a1d8 | 6,687 |
def generate_finding_title(title):
"""
Generate a consistent title for a finding in AWS Security Hub
* Setup as a function for consistency
"""
return "Trend Micro: {}".format(title) | 0cf390c2579e06c2166b086332035b864d3db1e3 | 6,688 |
def makeHexagon(x,y,w,h):
"""Return hexagonal QPolygon. (x,y) is top left coner"""
points=[]
cos=[1.,0.5,-0.5,-1,-0.5,0.5]
sin=[0,0.866025,0.866025,0,-0.866025,-0.866025]
for i in range(len (cos)):
points.append(QPoint(x+w*cos[i],y+h*sin[i]))
return QPolygonF(points) | 7310e0313130f54b125c81f332a541b2b2b9b9a9 | 6,689 |
def save_conv_output(activations, name):
"""
Saves layer output in activations dict with name key
"""
def get_activation(m, i, o):
activations[name] = F.relu(o).data.cpu().numpy()
return get_activation | 13034128234ea6a9633ae144ac02788f2d49986a | 6,690 |
async def get_profile_xp(user_id: int):
"""
Get a user's profile xp.
:param user_id: Discord User ID
"""
return (await self.conn.fetchrow("SELECT profilexp FROM currency.levels WHERE userid = $1", user_id))[0] | d029bb335442aa3ba5ef02b143351e8ccc6b6434 | 6,691 |
import os
import shutil
import click
def tryrmcache(dir_name, verbose=False):
"""
removes all __pycache__ starting from directory dir_name
all the way to leaf directory
Args:
dir_name(string) : path from where to start removing pycache
"""
# directory_list = list()
is_removed = Fa... | d4453352b30a8d3683b928f864536bcd1d6fda9f | 6,692 |
from typing import Optional
def validate_raw_data(data: Optional[UserPackage]) -> bool:
"""Returns False if invalid data"""
# NOTE: add more validation as more fields are required
if data is None or data.contribs is None:
return False
if (
data.contribs.total_stats.commits_count > 0
... | 22185bc2691b6a5fce98749c119ea14649c0d676 | 6,693 |
def extractTheSunIsColdTranslations(item):
"""
Parser for 'The Sun Is Cold Translations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if '108 maidens' in item['tags']:
return buildReleaseMessageWithType(ite... | 94ef69f42dd183a2155a02c8035c12da30eb34e2 | 6,694 |
import torch
def to_device(x, device):
"""Cast a hierarchical object to pytorch device"""
if isinstance(x, torch.Tensor):
return x.to(device)
elif isinstance(x, dict):
for k in list(x.keys()):
x[k] = to_device(x[k], device)
return x
elif isinstance(x, list) or isins... | a315905fb0cf6d6720103c0d22440418ebd41bf1 | 6,695 |
def git_show_oneline(obj):
"""Returns: One-line description of a git object `obj`, which is typically a commit.
https://git-scm.com/docs/git-show
"""
return exec_headline(['git', 'show', '--oneline', '--quiet', obj]) | 77427786a8d1b9e3b01d5194387f047c1c9ce505 | 6,696 |
from operator import and_
import logging
def like_post():
""" Like a post """
try:
# This will prevent old code from adding invalid post_ids
post_id = int(request.args.get('post_id', '-1'))
if post_id < 0:
return "No Post Found to like!"
vote = (db_session.query(Vot... | 8cdde2ec6f71104178c49661a9e3fdf5c62bb67d | 6,697 |
def login_post():
"""Obdelaj izpolnjeno formo za prijavo"""
# Uporabniško ime, ki ga je uporabnik vpisal v formo
username = bottle.request.forms.user
# Izračunamo MD5 hash geslo, ki ga bomo spravili
password = password_md5(bottle.request.forms.psw)
# Preverimo, ali se je uporabnik pravilno prij... | 9b2243f7e618833d59a7d07454ed8fe86d4b18fc | 6,698 |
def parse_symbol_file(filepath, fapi=None):
"""Read in stock symbol list from a text file.
Args:
filepath: Path to file containing stock symbols, one per line.
fapi: If this is supplied, the symbols read will be conformed
to a financial API; currently 'google' or 'yahoo'.
Retur... | af0f085fd5424045c71dee6a290a07645f242ff8 | 6,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.