content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_private_bool(script_dict):
""" Returns is_private boolean value from user dictionary object """
return script_dict['entry_data']['ProfilePage'][0]['graphql']['user']['is_private'] | 1e8b30a38dc527dc5e2ea73e75c253d8f1a59550 | 3,653,122 |
def manage_greylist(request):
"""
View for managing greylist.
"""
message = None
if request.method == 'POST':
form = GreylistForm(request.POST)
if form.is_valid():
# Set details to empty string if blank
new_greylisted_guest = form.save(commit=False)
... | eafbbf10b6150189d25c7d863cb00f6565648925 | 3,653,123 |
def get_regions():
"""Summary
Returns:
TYPE: Description
"""
client = boto3.client('ec2')
region_response = client.describe_regions()
regions = [region['RegionName'] for region in region_response['Regions']]
return regions | 700119f1c852ad9475823170388c062f62291637 | 3,653,124 |
def _is_ignored_read_event(request):
"""Return True if this read event was generated by an automated process, as
indicated by the user configurable LOG_IGNORE* settings.
See settings_site.py for description and rationale for the settings.
"""
if (
django.conf.settings.LOG_IGNORE_TRUSTED_SU... | f6f7417fe923ef6bd56a6d649ef302ed811185e8 | 3,653,125 |
def aten_embedding(mapper, graph, node):
""" 构造embedding的PaddleLayer。
TorchScript示例:
%inputs_embeds.1 : Tensor = aten::embedding(%57, %input_ids.1, %45, %46, %46)
参数含义:
%inputs_embeds.1 (Tensor): 输出,embedding后的结果。
%57 (Tensor): weights。
%input_ids.1 (Tensor): 需要进行embeddi... | d174c7e551bb3db7e7dc5d9014de9edd48ee4032 | 3,653,126 |
def _validate_opts(opts):
"""
Check that all of the types of values passed into the config are
of the right types
"""
def format_multi_opt(valid_type):
try:
num_types = len(valid_type)
except TypeError:
# Bare type name won't have a length, return the name of... | cafd1048a7496728715a192a4f70c7d50ade3622 | 3,653,128 |
async def from_string(input, output_path=None, options=None):
"""
Convert given string or strings to PDF document
:param input: string with a desired text. Could be a raw text or a html file
:param output_path: (optional) path to output PDF file. If not provided,
PDF will be returned as string
... | 2b3b6d9523d516fd3d258a3f722655720f49d91b | 3,653,129 |
def parse_tuple(tuple_string):
"""
strip any whitespace then outter characters.
"""
return tuple_string.strip().strip("\"[]") | d0052dce0582ca04d70455f1833d98545792c8ac | 3,653,130 |
def create_size():
"""Create a new size."""
in_out_schema = SizeSchema()
try:
new_size = in_out_schema.load(request.json)
except ValidationError as err:
abort(400, {'message': err.messages})
try:
db.session.add(new_size)
db.session.commit()
except IntegrityError... | f85b339c5ec5c38b8778de25456caa6fb0680d76 | 3,653,131 |
import click
from typing import Optional
def inject_snakefmt_config(
ctx: click.Context, param: click.Parameter, config_file: Optional[str] = None
) -> Optional[str]:
"""
If no config file argument provided, parses "pyproject.toml" if one exists.
Injects any parsed configuration into the relevant para... | 4d1fc2996db4c63070f67ef6b19387b2b30ac5cd | 3,653,132 |
def sort_by_ctime(paths):
"""Sorts list of file paths by ctime in ascending order.
Arg:
paths: iterable of filepaths.
Returns:
list: filepaths sorted by ctime or empty list if ctime is unavailable.
"""
ctimes = list(map(safe_ctime, paths))
if not all(ctimes) or len(set(ctimes)... | 551b7bc1d2cdc416588cbd783c9b1ac3e5914077 | 3,653,133 |
def get_ospf_metric(device,
destination_address):
"""Get OSPF metric
Args:
device (obj): Device object
destination_address (str): Destination address
"""
out = device.parse('show route')
# Example dictionary
# "route-table": [
# {
# ... | f5cd44794389a28db647e815baac4e954d59757b | 3,653,134 |
def get_episode_url():
"""エピソードの配信URLを追加
Returns:
[type]: [description]
"""
# フォームの値を取得
episode_num = "#"+request.form['episode_num'][0]
print(episode_num)
# 配信先一覧を取得
podcasts = Podcast.query.all()
broadcasts = Broadcast.query.all()
# 配信先 url
broadcast_urls = {... | e27f0324fd8332aa0648d35630cbb88b2b36c721 | 3,653,135 |
def autofs():
"""Fixture data from /proc/mounts."""
data = "flux-support -rw,tcp,hard,intr,noacl,nosuid,vers=3,retrans=5 flux-support.locker.arc-ts.umich.edu:/gpfs/locker0/ces/g/nfs/f/flux-support\numms-remills -rw,tcp,hard,intr,noacl,nosuid,vers=3,retrans=5 umms-remills.... | ea53c34d863de69c15f1e1247b98599c5f365ab7 | 3,653,136 |
def flag_dims(flags):
"""Return flag names, dims, and initials for flags.
Only flag value that correspond to searchable dimensions are
returned. Scalars and non-function string values are not included
in the result.
"""
dims = {}
initials = {}
for name, val in flags.items():
try... | 4cafd991e21facacf36423028288e4c5bb10c8d9 | 3,653,137 |
def to_stack(df, col, by, transform=None, get_cats=False):
""" Convert columns of a dataframe to a list of lists by 'by'
Args:
df:
col:
by:
transform:
Returns:
"""
g = df.groupby(by)
transform = _notransform if transform is None else transform
x_data = []
... | 7bbf0ff609aaf2a6f5b49f80128ad06c04f93b5c | 3,653,139 |
from typing import List
def entries_repr(entries: List[Metadata]) -> str:
"""
Generates a nicely formatted string repr from a list of Dropbox metadata.
:param entries: List of Dropbox metadata.
:returns: String representation of the list.
"""
str_reps = [
f"<{e.__class__.__name__}(pat... | cc768a662ac6440ef7d5ca0eaddff5205a7c0a8c | 3,653,140 |
def frequency_encode(dftrain, dftest, columnlist, output_type="include"):
"""
Frequency encode columns in columnlist.
Parameters:
dftrain: [DataFrame] train set
dftest: [DataFrame] test set
columnlist: [list] columns to encode.
output_type: [str], default="include" will ... | 3380853f0b5f88a6b2392a657424c4fc326876e2 | 3,653,141 |
def get_ranked_results(completed_rounds):
"""
For the rounds given in completed_rounds, calculate the total score for each team.
Then all teams are sorted on total score and are given a ranking to allow for ex aequo scores.
"""
results = []
for team in QTeam.objects.all():
teamtotal = 0
... | cea2afa2bb8de1db82450f323274af94ad3b633f | 3,653,142 |
def get_subgraphs():
"""
Returns a list of lists. Each list is a subgraph (represented as a list of dictionaries).
:return: A list of lists of dictionaries.
"""
subgraph_list = [c.get("color") for c in classes if c.get("color") is not None]
subgraphs = []
# Add to subgraphs all the lists of... | 5e9b766b2c7f58d71eac62d88be64096272d2511 | 3,653,143 |
def score(self, features):
""" return score from ML models"""
assert len(self._models) > 0, 'No valid prediction model'
scores = list()
for feature in features:
# when feature list extraction fails
if not feature:
scores.append(-float('inf'))
continue
item... | 413eb4a0ecdcf0ac4b8f9cf9643b08a839c78b9a | 3,653,144 |
def fromRGB(rgb):
"""Convert tuple or list to red, green and blue values that can be accessed as follows:
a = fromRGB((255, 255, 255))
a["red"]
a["green"]
a["blue"]
"""
return {"red":rgb[0], "green":rgb[1], "blue":rgb[2]} | 205a8f189d177e7af5cdc686e7c52fd2053a3c87 | 3,653,145 |
import math
def computeTelescopeTransmission(pars, offAxis):
"""
Compute tel. transmission (0 < T < 1) for a given set of parameters
as defined by the MC model and for a given off-axis angle.
Parameters
----------
pars: list of float
Parameters of the telescope transmission. Len(pars)... | 50b2e2908726b8a77bc83a2821cf760b7475300b | 3,653,146 |
def mean_iou(
results,
gt_seg_maps,
num_classes,
ignore_index,
nan_to_num=None,
label_map=dict(),
reduce_zero_label=False,
):
"""Calculate Mean Intersection and Union (mIoU)
Args:
results (list[ndarray]): List of prediction segmentation maps.
gt_seg_maps (list[ndarra... | a6d90cb4028c831db82b4dddb6a4c52a8fa4e1f0 | 3,653,147 |
def as_date_or_none(date_str):
"""
Casts a date string as a datetime.date, or None if it is blank.
>>> as_date_or_none('2020-11-04')
datetime.date(2020, 11, 4)
>>> as_date_or_none('')
None
>>> as_date_or_none(None)
None
"""
if not date_str:
return None
return dateut... | bf01bd280526e7962e1b08aa0400d6ebadf8053f | 3,653,148 |
def guarantee_trailing_slash(directory_name: str) -> str:
"""Adds a trailling slash when missing
Params:
:directory_name: str, required
A directory name to add trailling slash if missing
Returns:
A post processed directory name with trailling slash
"""
if not directory_... | 38cfdf971262fceb4888277522b22ba7276fa9b7 | 3,653,149 |
def bc32encode(data: bytes) -> str:
"""
bc32 encoding
see https://github.com/BlockchainCommons/Research/blob/master/papers/bcr-2020-004-bc32.md
"""
dd = convertbits(data, 8, 5)
polymod = bech32_polymod([0] + dd + [0, 0, 0, 0, 0, 0]) ^ 0x3FFFFFFF
chk = [(polymod >> 5 * (5 - i)) & 31 for i in ... | 46feb2b744089f5f4bf84cae6ff9d29623b3bba5 | 3,653,150 |
def read_all_reviews(current_user):
"""Reads all Reviews"""
reviews = Review.query.all()
if reviews:
return jsonify({'Reviews': [
{
'id': review.id,
'title': review.title,
'desc': review.desc,
'reviewer': review.reviewer.use... | 78642f38dab8328c11445e67848b7f6d9583d892 | 3,653,151 |
def matches_filters(row, field_to_index, transformed_filters):
"""
Validate field name in transformed filter_expressions, return TRUE for rows matching all filters
Parameters
------------
row : str
row in `list` registry table (manager.show())
field_to_index : dict
key = column ... | 119b5e7d7f7dfb72e1a66525d5bf84665cbbced0 | 3,653,152 |
def div(f, other):
"""Element-wise division applied to the `Functional` objects.
# Arguments
f: Functional object.
other: A python number or a tensor or a functional object.
# Returns
A Functional.
"""
validate_functional(f)
inputs = f.inputs.copy()
if is_functiona... | abfc7df85946cfcd5196dff58bec22ee237b590b | 3,653,153 |
def _gen_input(storyline, nsims, mode, site, chunks, current_c, nperc, simlen, swg_dir, fix_leap):
"""
:param storyline: loaded storyline
:param SWG_path: path to the directory with contining the files from the SWG
:param nsims: number of sims to run
:param mode: one of ['irrigated', 'dryland']
... | d0594a3b986c1415202db5f894101537464355a8 | 3,653,155 |
def guess_mime_mimedb (filename):
"""Guess MIME type from given filename.
@return: tuple (mime, encoding)
"""
mime, encoding = None, None
if mimedb is not None:
mime, encoding = mimedb.guess_type(filename, strict=False)
if mime not in ArchiveMimetypes and encoding in ArchiveCompressions:... | 8202551c81b25e9bb104ec82114a750a16556b23 | 3,653,156 |
def get_members():
"""
Get a list of all members in FreeIPA
"""
members = []
ldap_conn = ldap.get_con()
res = ldap_conn.search_s(
"cn=users,cn=accounts,dc=csh,dc=rit,dc=edu",
pyldap.SCOPE_SUBTREE,
"(uid=*)",
["uid", "displayName"],
)
for member in res:
... | 2714bddf7554884fa638066f91aa489b497f6c15 | 3,653,158 |
def _unicode_decode_extracted_tb(extracted_tb):
"""Return a traceback with the string elements translated into Unicode."""
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] | bbe020daecf6dc7021ff38dfac6869646120be5d | 3,653,159 |
def load_table(source, version):
"""Load synth table from file
"""
filepath = get_table_filepath(source, version=version)
return pd.read_table(filepath, delim_whitespace=True) | b95d35a6f297e0f73fee3652a0c9c6942b792451 | 3,653,160 |
def single_spaces(string: str) -> str:
"""Replaces all instances of whitespace-like chars with single spaces
Args:
string (str): The string to modify
Returns:
str: The cleaned string
"""
return UGLY_SPACES_RE.sub(" ", string) | eb37ae691f7fb54b6a23a5fd6d2cdd3edf8ebf57 | 3,653,161 |
def create_group(api_key: str, board_id: str, group_name: str, *args, **kwargs):
"""Creates a new group in a specific board.
__________
Parameters
api_key : `str`
The monday.com v2 API user key.
board_id : `str`
The board's unique identifier.
group_name ... | b591fe000718615f44954e488d4e3c46b9cf0123 | 3,653,163 |
import cvxopt
def _solve_qp_ik_vel(vel, jac, joint_pos, joint_lims=None, duration=None, margin=0.2):
"""
Solves the IK for a given pusher velocity using a QP solver, imposing joint limits.
If the solution is optimal, it is guaranteed that the resulting joint velocities will not
cause the joints to rea... | 25bd82403421f936d81d1a5c3090c1fbb1a964c1 | 3,653,164 |
def channel_will_be_next(crontab: str):
"""Checks if the given notification channel will be activated on the
next channel, in an hour."""
return pycron.is_now(crontab, now + timedelta(hours=1)) | b5505d7e27d70377cfb58acab8a38d9bd12d9351 | 3,653,165 |
def hospital_resident(residents, hospitals, optimal="resident"):
"""Solve an instance of HR using an adapted Gale-Shapley algorithm
:cite:`Rot84`. A unique, stable and optimal matching is found for the given
set of residents and hospitals. The optimality of the matching is found with
respect to one part... | e666b502a2e74f5c4628108397a82977b7da5b7f | 3,653,166 |
def log_request(response):
"""Log request.
:param response:
:return:
"""
ip = request.headers.get('X-Forwarded-For', request.remote_addr)
host = request.host.split(':', 1)[0]
app.logger.info(f"method={request.method}, path={request.path}, "
f"status={response.status_cod... | 838df023329b8b49c2349e58d02b44ef51ef7213 | 3,653,167 |
def reduce(path, n_procs, column, function):
""" Calculate an aggregate value from IMB output.
Args:
path: str, path to file
n_procs: int, number of processes
column: str, column name
function: callable to apply to specified `column` of table for `n_procs` in... | e2892b862f02ca11acaa180e24d390804441f0db | 3,653,168 |
from pathlib import Path
def output_file_path(status_id, phase):
"""
"""
BASE_DIR = Path(__file__).resolve().parent.parent
return f"%s/logs/stage/{status_id}-{phase}.txt" %str(BASE_DIR) | 3bcbd80ad95389b9cf37fa66923bacb819ede710 | 3,653,169 |
def clean(some_string, uppercase=False):
"""
helper to clean up an input string
"""
if uppercase:
return some_string.strip().upper()
else:
return some_string.strip().lower() | cdc4587b762625e00c91189950bd45840861c93f | 3,653,170 |
import re
def to_title(value):
"""Converts a string into titlecase."""
t = re.sub("\s+", ".", value)
t = filter(LETTER_SET.__contains__, t)
t = re.sub("([a-z])'\W([A-Z])", lambda m: m.group(0).lower(), t.title())
return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) | a88c9559abeab7426fa874e66c9e81a75138c0cd | 3,653,171 |
import yaml
def parse_config_or_kwargs(config_file, **kwargs):
"""parse_config_or_kwargs
:param config_file: Config file that has parameters, yaml format
:param **kwargs: Other alternative parameters or overwrites for config
"""
with open(config_file) as con_read:
yaml_config = yaml.load(... | f36946ed3a05f32057786ddf8e4194b935b4c129 | 3,653,172 |
def sig_generacion(m):
"""Devuelve la matriz resultante de aplicar las reglas del juego a cada celda"""
FILAS = len(m)
COLUMNAS = len(m[0]) if len(m) else 0
new_m = [] # matriz resultado
for i in range(FILAS):
l = [] # Una lista para ir generando una fila
for j in range(COLUMNAS):
... | 09da2baede2eef22179218f267bc2325d72822ee | 3,653,173 |
import hmac
import hashlib
import base64
def calc_file_signature(data: str, password: str = None) -> str:
"""
Função que calcula o has da assinatura de um arquivo
@param data: string assinada
@param password: senha da assinatura
@return: hash da assinatura
"""
if (password):
digest... | 1422b8058a6eb7995558b3e0a7fa5f33f6cfd134 | 3,653,174 |
def get_angle_from_coordinate(lat1, long1, lat2, long2):
"""https://stackoverflow.com/questions/3932502/calculate-angle-between-two-latitude-longitude-points"""
dLon = (long2 - long1)
y = np.sin(dLon) * np.cos(lat2)
x = np.cos(lat1) * np.sin(lat2) - np.sin(lat1) * np.cos(lat2) * np.cos(dLon)
brng ... | a1ad7ffe1e63197cc5f70b2ce2f343078fd9b5e7 | 3,653,175 |
import json
def get_predictions():
"""Return the list of predications as a json object"""
results = []
conn = None
columns = ("pid", "name", "location", "latitude", "longitude", "type", "modtime")
try:
conn = psycopg2.connect(db_conn)
# create a cursor
cur = conn.cursor()... | 6afb9d703f4dbeff81d4369f9096d577dcafc993 | 3,653,176 |
def parse_packageset(packageset):
"""
Get "input" or "output" packages and their repositories from each PES event.
:return: set of Package tuples
"""
return {parse_package(p) for p in packageset.get('package', packageset.get('packages', []))} | ff8af3423c0fda993cfa88be16142520e29b999e | 3,653,177 |
def pretty_print_large_number(number):
"""Given a large number, it returns a string of the sort: '10.5 Thousand' or '12.3 Billion'. """
s = str(number).ljust(12)
if number > 0 and number < 1e3:
pass
elif number >= 1e3 and number < 1e6:
s = s + " (%3.1f Thousand)" % (number * 1.0 / 1e3)... | 6762f34744da360b36d4a4fc0659fcf7d3fb0465 | 3,653,179 |
def find_aligning_transformation(skeleton, euler_frames_a, euler_frames_b):
"""
performs alignment of the point clouds based on the poses at the end of
euler_frames_a and the start of euler_frames_b
Returns the rotation around y axis in radians, x offset and z offset
"""
point_cloud_a = convert_... | 1d323fcb0af73aacbc57e5cf57f0b9875375b98d | 3,653,180 |
def find_all_visit(tx):
"""
Method that queries the database to find all VISIT relationships
:param tx: session
:return: nodes of Person , Location
"""
query = (
"""
MATCH (p:Person)-[r:VISIT]->(l:Location)
RETURN p , ID(p) , r , r.start_hour , r.end_hour , r.date ,... | 851d790b16f9db285a6d09b5cabc4e12ad364484 | 3,653,181 |
def read_vectors(filename):
"""Reads measurement vectors from a space or comma delimited file.
:param filename: path of the file
:type filename: str
:return: array of vectors
:rtype: numpy.ndarray
:raises: ValueError
"""
vectors = []
data = read_csv(filename)
expected_size = le... | a772c4185d55543e0c641271a5af699f91e81b95 | 3,653,182 |
def get_scoring_algorithm():
""" Base scoring algorithm for index and search """
return scoring.BM25F() | 78fe59d02071ce000262208f4c228566e0747857 | 3,653,183 |
def _make_augmentation_pipeline(augmentation_list):
"""Buids an sklearn pipeline of augmentations from a tuple of strings.
Parameters
----------
augmentation_list: list of strings, A list of strings that determine the
augmentations to apply, and in which order to apply them (the first
s... | e53f4d198e6781c5eaf6ce6c0a453801f4ceb0d7 | 3,653,184 |
def ctg_path(event_name,sc_reform,path_cache,var_map,model,prev_events):
"""
Recursively computes the controllable and contigent events that influence
the schedule of a given event.
"""
if event_name in path_cache:#If solution has been already computed, use it
return path_cache[event_name]
... | 5de8eb6fe3be991da3f4af37b6e81990aa8cb34f | 3,653,185 |
def _setup_mock_socket_file(mock_socket_create_conn, resp):
"""Sets up a mock socket file from the mock connection.
Args:
mock_socket_create_conn: The mock method for creating a socket connection.
resp: iterable, the side effect of the `readline` function of the mock
socket file.
Returns:
The ... | 5b70c73bb948211919065298a01a48d927e64482 | 3,653,186 |
def get_defense_type(action: int, game_config) -> int:
"""
Utility method for getting the defense type of action-id
:param action: action-id
:param game_config: game configuration
:return: action type
"""
defense_type = action % (game_config.num_attack_types+1) # +1 for detection
return... | 68a05cf15bd833fb24aa448b8be2d08c1a949d12 | 3,653,187 |
def color_box(
colors, border="#000000ff", border2=None, height=32, width=32,
border_size=1, check_size=4, max_colors=5, alpha=False, border_map=0xF
):
"""Color box."""
return colorbox.color_box(
colors, border, border2, height, width,
border_size, check_size, max_colors, alpha, border_... | 6f8a98743c11985529afd5ad0c04a64c1301f85a | 3,653,188 |
def get_performance_of_lstm_classifier(X, y, n_epochs, verbose=1, final_score=False):
"""
Reshapes feature matrix X, applies LSTM and returns the performance of the neural network
:param X: List of non-reshaped/original feature matrices (one per logfile)
:param y: labels
:param n_epochs: Number of ... | 13a494f9aca643ff23ce6954471ef007df96f9e8 | 3,653,189 |
def worker(data):
"""Thread function."""
width, column = data
queen = Queen(width)
queen.run(column)
return queen.solutions | ef0f3c6410885ac2e20b28f009085d92b6fca22b | 3,653,190 |
def eitem(self, key, value):
"""Translate included eitems."""
_eitem = self.get("_eitem", {})
urls = []
for v in force_list(value):
urls.append(
{
"description": "E-book by EbookCentral",
"value": clean_val("u", v, str),
}
)
_e... | d9a5d3f9dc29baa15d9df6b4fe32c7f20151316c | 3,653,191 |
def annotate_group(groups, ax=None, label=None, labeloffset=30):
"""Annotates the categories with their parent group and add x-axis label"""
def annotate(ax, name, left, right, y, pad):
"""Draw the group annotation"""
arrow = ax.annotate(name, xy=(left, y), xycoords="data",
... | 33f57ccf96b4b0907ea8c2ea161e19b0e6e536d2 | 3,653,192 |
def background_schwarzfischer(fluor_chan, bin_chan, div_horiz=7, div_vert=5, mem_lim=None, memmap_dir=None):
"""Perform background correction according to Schwarzfischer et al.
Arguments:
fluor_chan -- (frames x height x width) numpy array; the fluorescence channel to be corrected
bin_chan -- b... | 512d1721dc14a4f7a09843603b8700360f97fd37 | 3,653,193 |
def get_output_data_path(extension, suffix=None):
"""Return full path for data file with extension, generated by a test script"""
name = get_default_test_name(suffix)
return osp.join(TST_PATH[0], f"{name}.{extension}") | ce5437c23061df490a31ac11f26f72e5935f0fd7 | 3,653,195 |
def _plot(self, **kwargs) -> tp.BaseFigure: # pragma: no cover
"""Plot `close` and overlay it with the heatmap of `labels`."""
if self.wrapper.ndim > 1:
raise TypeError("Select a column first. Use indexing.")
return self.close.rename('close').vbt.overlay_with_heatmap(self.labels.rename('labels'), ... | eaa6df4f29db8d1ab6dc0ffd1b9ecf8804f6aac9 | 3,653,196 |
def _set_global_vars(metadata):
"""Identify files used multiple times in metadata and replace with global variables
"""
fnames = collections.defaultdict(list)
for sample in metadata.keys():
for k, v in metadata[sample].items():
print k, v
if os.path.isfile(v):
... | 23caefdf0f999a9b60649c85278edb8498b771b3 | 3,653,197 |
def user_get(context, id):
"""Get user by id."""
return IMPL.user_get(context, id) | b3108b4627751d5dfef1b42b8ccad0295b33cc99 | 3,653,198 |
def unpack_singleton(x):
"""
>>> unpack_singleton([[[[1]]]])
1
>>> unpack_singleton(np.array(np.datetime64('2000-01-01')))
array('2000-01-01', dtype='datetime64[D]')
"""
while isinstance(x, (list, tuple)):
try:
x = x[0]
except (IndexError, TypeError, KeyError):
... | f6f55ff17ba29aab5946c682b825c72eb70324dd | 3,653,199 |
def accuracy(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
# print('correct shape:', corre... | a5b2c3d97c839e0ae9954ce48889d5b46966b3cb | 3,653,202 |
def yyyydoy2jd(year,doy,hh=0,mm=0,ss=0.0):
"""
yyyydoy2jd Take a year, day-of-year, etc and convert it into a julian day
Usage: jd = yyyydoy2jd(year,doy,hh,mm,ss)
Input: year - 4 digit integer
doy - 3 digit, or less integer, (1 <= doy <= 366)
hh - 2 digit, or less int, (0 ... | 7e0579197146435d4c3e5031de962b758555846f | 3,653,203 |
def lon2index(lon, coords, corr=True):
"""convert longitude to index for OpenDAP request"""
if corr:
if lon < 0:
lon += 360
lons = coords.lon.values
return np.argmin(np.abs(lons - lon)) | 3fd3571ab221533708c32c9e28293a90ee9f30cd | 3,653,204 |
def get_dynamic_call_address(ea):
"""Find all dynamic calls e.g call eax"""
dism_addr_list = list(FuncItems(ea))
return [addr for addr in dism_addr_list if print_insn_mnem(addr) == 'call' and get_operand_type(addr, 0)==1] | 1f4d0eb3bcfdf0728d12efdfd151246f0497c8dd | 3,653,205 |
def iwbo_nats(model, x, k, kbs=None):
"""Compute the IWBO in nats."""
if kbs: return - iwbo_batched(model, x, k, kbs).mean()
else: return - iwbo(model, x, k).mean() | 5620e60710e6c25804d66f4c668f4670e033fdbe | 3,653,206 |
def ko_json(queryset, field_names=None, name=None, safe=False):
"""
Given a QuerySet, return just the serialized representation
based on the knockout_fields. Useful for middleware/APIs.
Convenience method around ko_data.
"""
return ko_data(queryset, field_names, name, safe, return_json=True) | 25d3b433ffec6eb4e6bb8c0d39a9080692dee4f2 | 3,653,207 |
def delete_demo(guid):
"""
Delete a demo object and all its children.
:param guid: The demo's guid
:return:
"""
web_utils.check_null_input((guid, 'demo to delete'))
demo_service.delete_demo_by_guid(guid)
return '', 204 | eb0a205e4279003a99159b2aeb4b8caefd47c2be | 3,653,209 |
def return_json():
"""
Sample function that has been given a different name
"""
print("Tooler should render out the JSON value returned")
return {"one": 1, "deep": {"structure": ["example"]}} | bf28fab61cabfc3a4f30736e58490d5df6702dc2 | 3,653,210 |
def get(url) -> str:
"""Send an http GET request.
:param str url:
The URL to perform the GET request for.
:rtype: str
:returns:
UTF-8 encoded string of response
"""
return _execute_request(url).read().decode("utf-8") | 2f0b6ed542f75f83478f672ef1f39f192dddbf66 | 3,653,211 |
def train_step(model_optimizer, game_board_log, predicted_action_log,
action_result_log):
"""Run one training step."""
def loss_fn(model_params):
logits = PolicyGradient().apply({'params': model_params}, game_board_log)
loss = compute_loss(logits, predicted_action_log, action_result_log)
... | 628742cb6d2fe19d25b5e283c7bec6f5189fc7b5 | 3,653,214 |
def make_static_rnn_with_control_flow_v2_tests(options):
"""Make a set of tests to do basic Lstm cell."""
test_parameters = [
{
"dtype": [tf.float32],
"num_batches": [4],
"time_step_size": [4],
"input_vec_size": [3],
"num_cells": [4],
"use_sequence_... | aa29c5eddab46624c36be29ee9ce1e6a83efbd7a | 3,653,215 |
def jaccard(structured_phrases, phrases_to_score, partial=False, status_callback=None, status_increment=None, pmd_class=PartialMatchDict):
""" calculate jaccard similarity between phrases_to_score, using
structured_phrases to determine cooccurrences. For phrases `a' and `b', let
A be the set of documents `a... | c7af246028f59b2375974390f337063d740d2f53 | 3,653,216 |
import ast
def print_python(node: AST) -> str:
"""Takes an AST and produces a string containing a human-readable
Python expression that builds the AST node."""
return black.format_str(ast.dump(node), mode=black.FileMode()) | 06281c4622d2b13008c17763bb59f93dfc44527c | 3,653,217 |
def reg2deg(reg):
"""
Converts phase register values into degrees.
:param cycles: Re-formatted number of degrees
:type cycles: int
:return: Number of degrees
:rtype: float
"""
return reg*360/2**32 | c7dbd6119ad3bce9261fb3d78a369251ade2d8af | 3,653,218 |
import pathlib
def load_config_at_path(path: Pathy) -> Dynaconf:
"""Load config at exact path
Args:
path: path to config file
Returns:
dict: config dict
"""
path = pathlib.Path(path)
if path.exists() and path.is_file():
options = DYNACONF_OPTIONS.copy()
option... | da5cc4b830ad3a50ec6713bb509d3db0862963bf | 3,653,221 |
def _build_target(action, original_target, plugin, context):
"""Augment dictionary of target attributes for policy engine.
This routine adds to the dictionary attributes belonging to the
"parent" resource of the targeted one.
"""
target = original_target.copy()
resource, _w = _get_resource_and_... | e3c62944d7083ee96ad510fff0807db50aed9602 | 3,653,222 |
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry):
"""Configure Gammu state machine."""
device = entry.data[CONF_DEVICE]
config = {"Device": device, "Connection": "at"}
gateway = await create_sms_gateway(config, opp)
if not gateway:
return False
opp.data[DOMAIN][SMS_GA... | c0a14f2a92d06e814728ff0ceed05bff17acb66a | 3,653,223 |
def grep_response_body(regex_name, regex, owtf_transaction):
"""Grep response body
:param regex_name: Regex name
:type regex_name: `str`
:param regex: Regex
:type regex:
:param owtf_transaction: OWTF transaction
:type owtf_transaction:
:return: Output
:rtype: `dict`
"""
retu... | b5e9899675a63fe9ede9a9cf612b2004d52bb364 | 3,653,224 |
def link(f, search_range, pos_columns=None, t_column='frame', verbose=True, **kwargs):
"""
link(f, search_range, pos_columns=None, t_column='frame', memory=0,
predictor=None, adaptive_stop=None, adaptive_step=0.95,
neighbor_strategy=None, link_strategy=None, dist_func=None,
to_eucl=None)... | 425f7ffe9bcda4700bc77e74c2e956f27f22d521 | 3,653,225 |
def get_classifier(opt, input_dim):
"""
Return a tuple with the ML classifier to be used and its hyperparameter
options (in dict format)."""
if opt == 'RF':
ml_algo = RandomForestClassifier
hyperparams = {
'n_estimators': [100],
'max_depth': [None, 10, 30, 50, 100... | a522cab05958023dd4239e4ec2b136d2510aec1b | 3,653,226 |
def list_spiders_endpoint():
"""It returns a list of spiders available in the SPIDER_SETTINGS dict
.. version 0.4.0:
endpoint returns the spidername and endpoint to run the spider from
"""
spiders = {}
for item in app.config['SPIDER_SETTINGS']:
spiders[item['endpoint']] = 'URL: ' + ... | 71e7448a621565b540c8ade1dae04d8ef88d5fd2 | 3,653,227 |
def plot3dOnFigure(ax, pixels, colors_rgb,axis_labels=list("RGB"), axis_limits=((0, 255), (0, 255), (0, 255))):
"""Plot pixels in 3D."""
# Set axis limits
ax.set_xlim(*axis_limits[0])
ax.set_ylim(*axis_limits[1])
ax.set_zlim(*axis_limits[2])
# Set axis labels and sizes
ax.tick_params(axis=... | 067219abba7f77f7c4fbb4404ff16a3f5192f7cd | 3,653,228 |
import numpy
def ellipse(a, b, center=(0.0, 0.0), num=50):
"""Return the coordinates of an ellipse.
Parameters
----------
a : float
The semi-major axis of the ellipse.
b : float
The semi-minor axis of the ellipse.
center : 2-tuple of floats, optional
The position of th... | bd4d4663981a0431e40b20d38cc48a7f2476c13b | 3,653,230 |
from typing import List
def get_trade_factors(name: str,
mp: float,
allow_zero: bool,
long_open_values: List,
long_close_values: List,
short_open_values: List = None,
short_close_values:... | 14a7a8c0968e85f996e9c1e8f473be142c66759b | 3,653,233 |
def mbstrlen(src):
"""Return the 'src' string (Multibytes ASCII string) length.
:param src: the source string
"""
try:
return len(src.decode("utf8", errors = "replace"))
except Exception, err:
LOG.error("String convert issue %s", err)
return len(src) | 8b2f64b2791eebf898d3bf8104d93d86dcdd53a3 | 3,653,234 |
def adapted_border_postprocessing(border_prediction, cell_prediction):
"""
:param border_prediction:
:param cell_prediction:
:return:
"""
prediction_border_bin = np.argmax(border_prediction, axis=-1)
cell_prediction = cell_prediction > 0.5
seeds = border_prediction[:, :, 1] * (1 - bord... | 4e74c1a71fb5c5f90d54735fa3af241461b48ebb | 3,653,235 |
def calc_bonding_volume(rc_klab, dij_bar, rd_klab=None, reduction_ratio=0.25):
"""
Calculate the association site bonding volume matrix
Dimensions of (ncomp, ncomp, nbeads, nbeads, nsite, nsite)
Parameters
----------
rc_klab : numpy.ndarray
This matrix of cutoff distances for associat... | cf154af6287286c19d606a2324c548f70f90121b | 3,653,236 |
def scale_enum(anchor, scales):
"""Enumerate a set of anchors for each scale wrt an anchor.
"""
w_w, h_h, x_ctr, y_ctr = genwhctrs(anchor)
w_s = w_w * scales
h_s = h_h * scales
anchors = makeanchors(w_s, h_s, x_ctr, y_ctr)
return anchors | 8de95fc6966133a74f10318f23e97babcb36d5cd | 3,653,237 |
def L1():
"""
Graph for computing 'L1'.
"""
graph = beamline(scatter=True)
for node in ['scattered_beam', 'two_theta', 'L2', 'Ltotal']:
del graph[node]
return graph | 1bd17365107740a41d88ac3825ef2aca412bb616 | 3,653,238 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.