content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def calc_overlap(row):
"""
Calculates the overlap between prediction and
ground truth and overlap percentages used for determining
true positives.
"""
set_pred = set(row.predictionstring_pred.split(' '))
set_gt = set(row.predictionstring_gt.split(' '))
# Length of each and intersection
len_gt = len(set_gt)
len_pred = len(set_pred)
inter = len(set_gt.intersection(set_pred))
overlap_1 = inter / len_gt
overlap_2 = inter/ len_pred
return [overlap_1, overlap_2] | 98e65250f82ab13b23de049fd80a59dea30ccce2 | 705,225 |
def _bucket_from_workspace_name(wname):
"""Try to assert the bucket name from the workspace name.
E.g. it will answer www.bazel.build if the workspace name is build_bazel_www.
Args:
wname: workspace name
Returns:
the guessed name of the bucket for this workspace.
"""
revlist = []
for part in wname.split("_"):
revlist.insert(0, part)
return ".".join(revlist) | 4cf3f4505a894f63258846abbe41b3b787485d40 | 705,227 |
def get_attrib_uri(json_dict, attrib):
""" Get the URI for an attribute.
"""
url = None
if type(json_dict[attrib]) == str:
url = json_dict[attrib]
elif type(json_dict[attrib]) == dict:
if json_dict[attrib].get('id', False):
url = json_dict[attrib]['id']
elif json_dict[attrib].get('@id', False):
url = json_dict[attrib]['@id']
return url | 838b698e3475ebdc877b29de6f3fd446d2be1cdf | 705,230 |
import inspect
def super_class_property(*args, **kwargs):
"""
A class decorator that adds the class' name in lowercase as a property of
it's superclass with a value constructed using the subclass' constructor with
the given arguments. So for example:
class A:
pass
@super_class_property(foo=5)
class B(A):
def __init__(self, foo=3):
self.foo=foo
Effectively results in the following, after the definition of B:
A.b = B(foo=5)
Can be used multiple times with different arguments if desired.
"""
def add_superclass_property(cls):
nonlocal args, kwargs
mro = inspect.getmro(cls)
if len(mro) <= 2:
raise TypeError(
(
"Class {} can't be a super_class_property because it has no super "
"class."
).format(cls)
)
parent = mro[1]
instance = cls(*args, **kwargs)
setattr(parent, cls.__name__.lower(), instance)
return cls
return add_superclass_property | ecfd38ba3d7ea96266278ed6be6cf0ba87263d7d | 705,232 |
def merge(sorted1, sorted2):
"""Merge two sorted lists into a single sorted list."""
if sorted1 == ():
return sorted2
elif sorted2 == ():
return sorted1
else:
h1, t1 = sorted1
h2, t2 = sorted2
if h1 <= h2:
return (h1, merge(t1, sorted2))
else:
return (h2, merge(sorted1, t2)) | 7c02b345b3d1e7c67e363e1535c608575a313f75 | 705,235 |
def slice_repr(slice_obj):
"""
Get the best guess of a minimal representation of
a slice, as it would be created by indexing.
"""
slice_items = [slice_obj.start, slice_obj.stop, slice_obj.step]
if slice_items[-1] is None:
slice_items.pop()
if slice_items[-1] is None:
if slice_items[0] is None:
return "all"
else:
return repr(slice_items[0]) + ":"
else:
return ":".join("" if x is None else repr(x) for x in slice_items) | c894f66478ec830a4968d0cfc5d9e146457012b6 | 705,237 |
import math
def squeezenet1_0_fpn_feature_shape_fn(img_shape):
""" Takes an image_shape as an input to calculate the FPN output sizes
Ensure that img_shape is of the format (..., H, W)
Args
img_shape : image shape as torch.Tensor not torch.Size should have
H, W as last 2 axis
Returns
P3_shape, P4_shape, P5_shape, P6_shape, P7_shape : as 5 (2,) Tensors
"""
C0_shape = img_shape[-2:]
C1_shape = (math.floor((C0_shape[0] - 5) / 2), math.floor((C0_shape[1] - 5) / 2))
C2_shape = (math.ceil((C1_shape[0] - 1) / 2), math.ceil((C1_shape[1] - 1) / 2))
P3_shape = (math.ceil((C2_shape[0] - 1) / 2), math.ceil((C2_shape[1] - 1) / 2))
P4_shape = (math.ceil((P3_shape[0] - 1) / 2), math.ceil((P3_shape[1] - 1) / 2))
P5_shape = (math.ceil((P4_shape[0] - 1) / 2), math.ceil((P4_shape[1] - 1) / 2))
P6_shape = (math.ceil(P5_shape[0] / 2), math.ceil(P5_shape[1] / 2))
P7_shape = (math.ceil(P6_shape[0] / 2), math.ceil(P6_shape[1] / 2))
return C2_shape, P3_shape, P4_shape, P5_shape, P6_shape, P7_shape | d56fe3d834bcd9633727defe3ad9a27ea756ed40 | 705,239 |
import types
def _copy_fn(fn):
"""Create a deep copy of fn.
Args:
fn: a callable
Returns:
A `FunctionType`: a deep copy of fn.
Raises:
TypeError: if `fn` is not a callable.
"""
if not callable(fn):
raise TypeError("fn is not callable: %s" % fn)
# The blessed way to copy a function. copy.deepcopy fails to create a
# non-reference copy. Since:
# types.FunctionType == type(lambda: None),
# and the docstring for the function type states:
#
# function(code, globals[, name[, argdefs[, closure]]])
#
# Create a function object from a code object and a dictionary.
# ...
#
# Here we can use this to create a new function with the old function's
# code, globals, closure, etc.
return types.FunctionType(
code=fn.__code__, globals=fn.__globals__,
name=fn.__name__, argdefs=fn.__defaults__,
closure=fn.__closure__) | 37fca64ddaadfc8a6a24dce012af2143038cacd2 | 705,241 |
def getTJstr(text, glyphs, simple, ordering):
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
glyphs: 2-chars, use glyphs instead of char codes (Symbol,
ZapfDingbats)
not simple: ordering < 0: 4-chars, use glyphs not char codes
ordering >=0: a CJK font! 4 chars, use char codes as glyphs
"""
if text.startswith("[<") and text.endswith(">]"): # already done
return text
if not bool(text):
return "[<>]"
if simple: # each char or its glyph is coded as a 2-byte hex
if glyphs is None: # not Symbol, not ZapfDingbats: use char code
otxt = "".join(["%02x" % ord(c) if ord(c) < 256 else "b7" for c in text])
else: # Symbol or ZapfDingbats: use glyphs
otxt = "".join(["%02x" % glyphs[ord(c)][0] if ord(c) < 256 else "b7" for c in text])
return "[<" + otxt + ">]"
# non-simple fonts: each char or its glyph is coded as 4-byte hex
if ordering < 0: # not a CJK font: use the glyphs
otxt = "".join(["%04x" % glyphs[ord(c)][0] for c in text])
else: # CJK: use the char codes
otxt = "".join(["%04x" % ord(c) for c in text])
return "[<" + otxt + ">]" | bd5b7abd1b5ceb0b273e99e30ecc248482ed7476 | 705,245 |
def check_skip(timestamp, filename):
"""
Checks if a timestamp has been given and whether the timestamp corresponds
to the given filename.
Returns True if this condition is met and False Otherwise"
"""
if ((len(timestamp) > 0) and not(timestamp in filename)):
return True
elif ((len(timestamp) > 0) and (timestamp in filename)):
return False | 738043fb554f20b79fa3ac8861f9e60d0d697e5e | 705,246 |
def is_tabledap(url):
"""
Identify a dataset as an ERDDAP TableDAP dataset.
Parameters
----------
url (str) : URL to dataset
Returns
-------
bool
"""
return "tabledap" in url | 9f4650bc3a3bc0794637b042c1779a84d7c02779 | 705,247 |
import torch
def cal_area(group_xyz):
"""
Calculate Area of Triangle
:param group_xyz: [B, N, K, 3] / [B, N, G, K, 3]; K = 3
:return: [B, N, 1] / [B, N, G, 1]
"""
pad_shape = group_xyz[..., 0, None].shape
det_xy = torch.det(torch.cat([group_xyz[..., 0, None], group_xyz[..., 1, None], torch.ones(pad_shape)], dim=-1))
det_yz = torch.det(torch.cat([group_xyz[..., 1, None], group_xyz[..., 2, None], torch.ones(pad_shape)], dim=-1))
det_zx = torch.det(torch.cat([group_xyz[..., 2, None], group_xyz[..., 0, None], torch.ones(pad_shape)], dim=-1))
area = torch.sqrt(det_xy ** 2 + det_yz ** 2 + det_zx ** 2).unsqueeze(-1)
return area | bbafa626c1833b5bde81303b4038081dae7bc965 | 705,251 |
def quicksort(inputArray):
"""input: array
output: new sorted array
features: stable
efficiency O(n^2) (worst case), O(n log(n)) (avg case), O(n) (best case):
space complexity: O(n)
method:
Pick the last element in the array as the pivot.
Separate values into arrays based on whether they are
greater than, less than, or equal to the pivot.
Recursively sort the greater than and less than arrays.
Return an new array merging the sorted arrays and the pivot.
"""
if len(inputArray) <= 1:
return inputArray
pivot = inputArray[-1]
lesser = []
greater = []
equal = []
for value in inputArray[:-1]:
if value > pivot:
greater.append(value)
elif value < pivot:
lesser.append(value)
elif value == pivot:
equal.append(value)
lesser = quicksort(lesser)
greater = quicksort(greater)
return lesser + equal + [pivot] + greater | 2a8036ba038f4f7a8e817175d9a810184911ce4b | 705,253 |
def cubic_spline_breaksToknots(bvec):
"""
Given breakpoints generated from _cubic_spline_breaks,
[x0, x0, x0, x0, x1, x2, ..., xN-2, xf, xf, xf, xf],
return the spline knots [x0, x1, ..., xN-1=xf].
This function ``undoes" _cubic_spline_breaks:
knot_vec = _cubic_spline_breaks2knots(_cubic_spline_breaks(knot_vec))
"""
return bvec[3:-3] | 15a73dea4b001e05bd67075ec21e15247db1f031 | 705,259 |
def _SanitizeDoc(doc, leader):
"""Cleanup the doc string in several ways:
* Convert None to empty string
* Replace new line chars with doxygen comments
* Strip leading white space per line
"""
if doc is None:
return ''
return leader.join([line.lstrip() for line in doc.split('\n')]) | 7ca6f17296c9b23c05239092e28c8d6b4df7c725 | 705,267 |
def pop_execute_query_kwargs(keyword_arguments):
""" pop the optional execute query arguments from arbitrary kwargs;
return non-None query kwargs in a dict
"""
query_kwargs = {}
for key in ('transaction', 'isolate', 'pool'):
val = keyword_arguments.pop(key, None)
if val is not None:
query_kwargs[key] = val
return query_kwargs | d4ae2df3158660f62e21153d943922692f633b76 | 705,268 |
def lico2_ocp_Ramadass2004(sto):
"""
Lithium Cobalt Oxide (LiCO2) Open Circuit Potential (OCP) as a a function of the
stochiometry. The fit is taken from Ramadass 2004. Stretch is considered the
overhang area negative electrode / area positive electrode, in Ramadass 2002.
References
----------
.. [1] P. Ramadass, Bala Haran, Parthasarathy M. Gomadam, Ralph White, and Branko
N. Popov. "Development of First Principles Capacity Fade Model for Li-Ion Cells."
(2004)
Parameters
----------
sto : :class:`pybamm.Symbol`
Stochiometry of material (li-fraction)
"""
stretch = 1.13
sto = stretch * sto
u_eq = ((- 4.656 + 88.669 * (sto ** 2)
- 401.119 * (sto ** 4) + 342.909 * (sto ** 6)
- 462.471 * (sto ** 8) + 433.434 * (sto ** 10)) / (
- 1 + 18.933 * (sto ** 2) - 79.532 * (sto ** 4)
+ 37.311 * (sto ** 6) - 73.083 * (sto ** 8)
+ 95.96 * (sto ** 10))
)
return u_eq | 2c0902e1d1cdec9ac7626038e34092933665bf84 | 705,272 |
import time
def find_workflow_component_figures(page):
""" Returns workflow component figure elements in `page`. """
time.sleep(0.5) # Pause for stable display.
root = page.root or page.browser
return root.find_elements_by_class_name('WorkflowComponentFigure') | 1a56a0a348803394c69478e3443cbe8c6cb0ce9c | 705,276 |
def query_left(tree, index):
"""Returns sum of values between 1-index inclusive.
Args:
tree: BIT
index: Last index to include to the sum
Returns:
Sum of values up to given index
"""
res = 0
while index:
res += tree[index]
index -= (index & -index)
return res | e293194c86ad1c53a005be290ba61ef2fff097c8 | 705,282 |
def find_language(article_content):
"""Given an article's xml content as string, returns the article's language"""
if article_content.Language is None:
return None
return article_content.Language.string | 4a228779992b156d01bc25501677556a5c9b7d39 | 705,286 |
import collections
def extract_stats(output):
"""Extract stats from `git status` output
"""
lines = output.splitlines()
return collections.Counter([x.split()[0] for x in lines]) | 41d8aef4df3401ee8127ad0b72402ff9c54c41e3 | 705,294 |
def add_custom_encoder_arguments(group):
"""Define arguments for Custom encoder."""
group.add_argument(
"--enc-block-arch",
type=eval,
action="append",
default=None,
help="Encoder architecture definition by blocks",
)
group.add_argument(
"--enc-block-repeat",
default=0,
type=int,
help="Repeat N times the provided encoder blocks if N > 1",
)
group.add_argument(
"--custom-enc-input-layer",
type=str,
default="conv2d",
choices=["conv2d", "vgg2l", "linear", "embed"],
help="Custom encoder input layer type",
)
group.add_argument(
"--custom-enc-positional-encoding-type",
type=str,
default="abs_pos",
choices=["abs_pos", "scaled_abs_pos", "rel_pos"],
help="Custom encoder positional encoding layer type",
)
group.add_argument(
"--custom-enc-self-attn-type",
type=str,
default="self_attn",
choices=["self_attn", "rel_self_attn"],
help="Custom encoder self-attention type",
)
group.add_argument(
"--custom-enc-pw-activation-type",
type=str,
default="relu",
choices=["relu", "hardtanh", "selu", "swish"],
help="Custom encoder pointwise activation type",
)
group.add_argument(
"--custom-enc-conv-mod-activation-type",
type=str,
default="swish",
choices=["relu", "hardtanh", "selu", "swish"],
help="Custom encoder convolutional module activation type",
)
return group | f49a778b78351a08bdb411e8004d00da0ccd96a4 | 705,298 |
def sign(x):
"""Returns sign of x"""
if x==0:
return 0
return x/abs(x) | 677dfd796b0ee354fbcaf78b58cf7a5a660446b5 | 705,300 |
def echo_handler(completed_proc):
"""Immediately return ``completed_proc``."""
return completed_proc | 53f3ef51bf349ac5146014ef25b88326d5bc010e | 705,302 |
import random
def random_choice(choices):
"""returns a random choice
from a list of (choice, probability)"""
# sort by probability
choices = sorted(choices, key=lambda x:x[1])
roll = random.random()
acc_prob = 0
for choice, prob in choices:
acc_prob += prob
if roll <= acc_prob:
return choice | f477abe220fa9d87ee3692bed8c41973af4c637c | 705,303 |
import torch
def convert_label_to_color(label, color_map):
"""Convert integer label to RGB image.
"""
n, h, w = label.shape
rgb = torch.index_select(color_map, 0, label.view(-1)).view(n, h, w, 3)
rgb = rgb.permute(0, 3, 1, 2)
return rgb | a37ec3ad382f88bdc9de8fbc2b4e2524213607c3 | 705,304 |
def in_nested_list(my_list, item):
"""
Determines if an item is in my_list, even if nested in a lower-level list.
"""
if item in my_list:
return True
else:
return any(in_nested_list(sublist, item) for sublist in my_list if
isinstance(sublist, list)) | 3daeaf89099bf19ba82eabfedd943adfb32fc146 | 705,306 |
def is_prebuffer() -> bool:
"""
Return whether audio is in pre-buffer (threadsafe).
Returns
-------
is_prebuffer : bool
Whether audio is in pre-buffer.
"""
is_prebuffer = bool(RPR.Audio_IsPreBuffer()) # type:ignore
return is_prebuffer | 8afa4979578be310fd71b22907c99bb747780454 | 705,308 |
def _get_interface_name_index(dbapi, host):
"""
Builds a dictionary of interfaces indexed by interface name.
"""
interfaces = {}
for iface in dbapi.iinterface_get_by_ihost(host.id):
interfaces[iface.ifname] = iface
return interfaces | 0217f6ef8d4e5e32d76a4fc0d66bf74aa45f8c36 | 705,309 |
def delchars(str, chars):
"""Returns a string for which all occurrences of characters in
chars have been removed."""
# Translate demands a mapping string of 256 characters;
# whip up a string that will leave all characters unmolested.
identity = "".join([chr(x) for x in range(256)])
return str.translate(identity, chars) | a220202a05e0ead7afa6226ef309c56940a1d153 | 705,313 |
def bytes2hex(bytes_array):
"""
Converts byte array (output of ``pickle.dumps()``) to spaced hexadecimal string representation.
Parameters
----------
bytes_array: bytes
Array of bytes to be converted.
Returns
-------
str
Hexadecimal representation of the byte array.
"""
s_hex = bytes_array.hex()
# Insert spaces between each hex number. It makes YAML file formatting better.
return " ".join([s_hex[n : n + 2] for n in range(0, len(s_hex), 2)]) | 19019ee1e3cd45d671f53e0ae4fd92b283c3b38d | 705,314 |
from pathlib import Path
def to_posix(d):
"""Convert the Path objects to string."""
if isinstance(d, dict):
for k, v in d.items():
d[k] = to_posix(v)
elif isinstance(d, list):
return [to_posix(x) for x in d]
elif isinstance(d, Path):
return d.as_posix()
return d | 91dbda7738308dd931b58d59dad8e04a277034ea | 705,316 |
def firstLetterCipher(ciphertext):
"""
Returns the first letters of each word in the ciphertext
Example:
Cipher Text: Horses evertime look positive
Decoded text: Help """
return "".join([i[0] for i in ciphertext.split(" ")]) | 87f37d1a428bde43c07231ab2e5156c680c96f91 | 705,318 |
from pathlib import Path
from typing import Tuple
import re
def parse_samtools_flagstat(p: Path) -> Tuple[int, int]:
"""Parse total and mapped number of reads from Samtools flagstat file"""
total = 0
mapped = 0
with open(p) as fh:
for line in fh:
m = re.match(r'(\d+)', line)
if m:
if 'in total' in line:
total = int(m.group(1))
if ' mapped (' in line:
mapped = int(m.group(1))
return total, mapped | 60c6f9b227cefdea9877b05bb2fe66e4c82b4dd1 | 705,319 |
def app_files(proj_name):
"""Create a list with the project files
Args:
proj_name (str): the name of the project, where the code will be hosted
Returns:
files_list (list): list containing the file structure of the app
"""
files_list = [
"README.md",
"setup.py",
"setup.cfg",
f"{proj_name}/__init__.py",
f"{proj_name}/{proj_name}.py",
"tests/tests.py",
]
return files_list | 2c6cbf112c7939bea12672668c8a5db1656b6edd | 705,320 |
import torch
def log_safe(x):
"""The same as torch.log(x), but clamps the input to prevent NaNs."""
x = torch.as_tensor(x)
return torch.log(torch.min(x, torch.tensor(33e37).to(x))) | 98c73b316d22ebe9ef4b322b1ba984a734422e7a | 705,321 |
import requests
def resolve_s1_slc(identifier, download_url, project):
"""Resolve S1 SLC using ASF datapool (ASF or NGAP). Fallback to ESA."""
# determine best url and corresponding queue
vertex_url = "https://datapool.asf.alaska.edu/SLC/SA/{}.zip".format(
identifier)
r = requests.head(vertex_url, allow_redirects=True)
if r.status_code == 403:
url = r.url
queue = "{}-job_worker-small".format(project)
elif r.status_code == 404:
url = download_url
queue = "factotum-job_worker-scihub_throttled"
else:
raise RuntimeError("Got status code {} from {}: {}".format(
r.status_code, vertex_url, r.url))
return url, queue | cf489b0d65a83dee3f87887a080d67acd180b0b3 | 705,322 |
def make_anagram_dict(filename):
"""Takes a text file containing one word per line.
Returns a dictionary:
Key is an alphabetised duple of letters in each word,
Value is a list of all words that can be formed by those letters"""
result = {}
fin = open(filename)
for line in fin:
word = line.strip().lower()
letters_in_word = tuple(sorted(word))
if letters_in_word not in result:
result[letters_in_word] = [word]
else:
result[letters_in_word].append(word)
return result | c6c0ad29fdf63c91c2103cefc506ae36b64a40ec | 705,323 |
def group_property_types(row : str) -> str:
"""
This functions changes each row in the dataframe to have the one
of five options for building type:
- Residential
- Storage
- Retail
- Office
- Other
this was done to reduce the dimensionality down to the top building
types.
:param: row (str) : The row of the pandas series
:rvalue: str
:return: One of 5 building types.
"""
if row == 'Multifamily Housing' or\
row == 'Residence Hall/Dormitory' or\
row == 'Hotel' or\
row == 'Other - Lodging/Residential' or\
row == 'Residential Care Facility':
return 'Residential'
elif row == 'Non-Refrigerated Warehouse' or\
row == 'Self-Storage Facility' or\
row == 'Refrigerated Warehouse':
return 'Storage'
elif row == 'Financial Office' or\
row == 'Office':
return 'Office'
elif row == 'Restaurant' or\
row == 'Retail Store' or\
row == 'Enclosed Mall' or\
row == 'Other - Mall' or\
row == 'Strip Mall' or\
row == 'Personal Services (Health/Beauty, Dry Cleaning, etc.)' or\
row == 'Lifestyle Center' or\
row == 'Wholesale Club/Supercenter':
return 'Retail'
else:
return 'Other' | 44aa5d70baaa24b0c64b7464b093b59ff39d6d1c | 705,324 |
def write_simple_templates(n_rules, body_predicates=1, order=1):
"""Generate rule template of form C < A ^ B of varying size and order"""
text_list = []
const_term = "("
for i in range(order):
const_term += chr(ord('X') + i) + ","
const_term = const_term[:-1] + ")"
write_string = "{0} #1{1} :- #2{1}".format(n_rules, const_term)
if body_predicates > 1:
for i in range(body_predicates - 1):
write_string += ", #" + str(i + 3) + const_term
text_list.append(write_string)
return text_list | 3a911702be9751b0e674171ec961029f5b10a9e7 | 705,325 |
def gen_string(**kwargs) -> str:
"""
Generates the string to put in the secrets file.
"""
return f"""\
apiVersion: v1
kind: Secret
metadata:
name: keys
namespace: {kwargs['namespace']}
type: Opaque
data:
github_client_secret: {kwargs.get('github_client_secret')}
""" | ed2702c171f20b9f036f07ec61e0a4d74424ba03 | 705,327 |
def get_props_from_row(row):
"""Return a dict of key/value pairs that are props, not links."""
return {k: v for k, v in row.iteritems() if "." not in k and v != ""} | a93dfbd1ef4dc87414492b7253b1ede4e4cc1888 | 705,328 |
import math
def F7(x):
"""Easom function"""
s = -math.cos(x[0])*math.cos(x[1])*math.exp(-(x[0] - math.pi)**2 - (x[1]-math.pi)**2)
return s | a17060f046df9c02690e859e789b7ef2591d1a3c | 705,330 |
from datetime import datetime
def _get_stop_as_datetime(event_json)->datetime:
"""Reads the stop timestamp of the event and returns it as a datetime
object.
Args:
event_json (json): The event encapsulated as json.
Returns
datetime: Timestamp of the stop of the event.
"""
name = event_json['info']['name']
payload_stop = 'meta.raw_payload.' + name + '-stop'
stop_timestamp_string = event_json['info'][payload_stop]['timestamp']
stop_date_string, stop_time_string = stop_timestamp_string.split('T')
stop_time_string, _ = stop_time_string.split('.')
date_and_time_string = stop_date_string + ' ' + stop_time_string
return datetime.strptime(date_and_time_string, '%Y-%m-%d %H:%M:%S') | 958915a568c66a04da3f44abecf0acca90181f43 | 705,334 |
import string
import random
def gen_pass(length=8, no_numerical=False, punctuation=False):
"""Generate a random password
Parameters
----------
length : int
The length of the password
no_numerical : bool, optional
If true the password will be generated without 0-9
punctuation : bool, optional
If true the password will be generated with punctuation
Returns
-------
string
The generated password
"""
characters = [string.ascii_letters]
# Add user options to the character set
if not no_numerical:
characters.append(string.digits)
if punctuation:
characters.append(string.punctuation)
# Shuffle the character set
random.SystemRandom().shuffle(characters)
chars_left = length - (len(characters) - 1)
char_amounts = []
# Decide on number of characters per character set
for char_set in characters:
i = random.SystemRandom().randint(1, chars_left)
char_amounts.append(i)
chars_left -= i - 1
char_amounts[-1] += chars_left - 1
# Generate the password's characters
password = ''
for i, length in enumerate(char_amounts):
password +=''.join(random.SystemRandom().choice(characters[i]) for _ in range(length))
# Shuffle the password
password = list(password)
random.SystemRandom().shuffle(password)
password = ''.join(password)
return password | dc0ca0c228be11a5264870112e28f27817d4bbc8 | 705,336 |
def document_version_title(context):
"""Document version title"""
return context.title | 1589a76e8bb4b4a42018783b7dbead9efc91e21a | 705,337 |
def decide_play(lst):
"""
This function will return the boolean to control whether user should continue the game.
----------------------------------------------------------------------------
:param lst: (list) a list stores the input alphabet.
:return: (bool) if the input character is alphabet and if only one character is in the string.
"""
if len(lst) == 4:
for char in lst:
if char.isalpha() and len(char) == 1:
pass
else:
return False
return True
else:
return False | 3062e1335eda572049b93a60a0981e905ff6ca0d | 705,339 |
def _md_fix(text):
"""
sanitize text data that is to be displayed in a markdown code block
"""
return text.replace("```", "``[`][markdown parse fix]") | 2afcad61f4b29ae14c66e04c39413a9a94ae30f8 | 705,343 |
def hexStringToRGB(hex):
"""
Converts hex color string to RGB values
:param hex: color string in format: #rrggbb or rrggbb with 8-bit values in hexadecimal system
:return: tuple containing RGB color values (from 0.0 to 1.0 each)
"""
temp = hex
length = len(hex)
if temp[0] == "#":
temp = hex[1:length]
if not len(temp) == 6:
return None
colorArr = bytearray.fromhex(temp)
return colorArr[0], colorArr[1], colorArr[2] | 7adcb7b247e6fe1aefa1713d754c828d1ac4a5b0 | 705,349 |
from typing import Union
from typing import Mapping
from typing import Iterable
from typing import Tuple
from typing import Any
def update_and_return_dict(
dict_to_update: dict, update_values: Union[Mapping, Iterable[Tuple[Any, Any]]]
) -> dict:
"""Update a dictionary and return the ref to the dictionary that was updated.
Args:
dict_to_update (dict): the dict to update
update_values (Union[Mapping, Iterable[Tuple[Any, Any]]]): the values to update the dict
with
Returns:
dict: the dict that was just updated.
"""
dict_to_update.update(update_values)
return dict_to_update | 8622f96a9d183c8ce5c7f260e97a4cb4420aecc7 | 705,351 |
def cutoff_depth(d: int):
"""A cutoff function that searches to depth d."""
return lambda game, state, depth: depth > d | af7396a92f1cd234263e8448a6d1d22b56f4a12c | 705,354 |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given RGB color values."""
return '#%02x%02x%02x' % (int(red), int(green), int(blue)) | 7523bcb4b7a033655c9f5059fcf8d0ed656502c8 | 705,356 |
def _is_swiftmodule(path):
"""Predicate to identify Swift modules/interfaces."""
return path.endswith((".swiftmodule", ".swiftinterface")) | 085fa4f8735ce371927f606239d51c44bcca5acb | 705,357 |
def get_rest_parameter_state(parameter_parsing_states):
"""
Gets the rest parameter from the given content if there is any.
Parameters
----------
parameter_parsing_states `list` of ``ParameterParsingStateBase``
The created parameter parser state instances.
Returns
-------
parameter_parsing_state : ``ParameterParsingState``, `None`
"""
for parameter_parsing_state in parameter_parsing_states:
if parameter_parsing_state.content_parser_parameter.is_rest:
return parameter_parsing_state | e90d1ee848af7666a72d9d0d4fb74e3fedf496fa | 705,365 |
import io
def read_all_files(filenames):
"""Read all files into a StringIO buffer."""
return io.StringIO('\n'.join(open(f).read() for f in filenames)) | efb2e3e8f35b2def5f1861ecf06d6e4135797ccf | 705,366 |
def path_inside_dir(path, directory):
"""
Returns True if the specified @path is inside @directory,
performing component-wide comparison. Otherwise returns False.
"""
return ((directory == "" and path != "")
or path.rstrip("/").startswith(directory.rstrip("/") + "/")) | 30ad431f9115addd2041e4b6c9c1c8c563b93fe9 | 705,367 |
def butterworth_type_filter(frequency, highcut_frequency, order=2):
"""
Butterworth low pass filter
Parameters
----------
highcut_frequency: float
high-cut frequency for the low pass filter
fs: float
sampling rate, 1./ dt, (default = 1MHz)
period:
period of the signal (e.g. 25Hz base frequency, 0.04s)
order: int
The order of the butterworth filter
Returns
-------
frequency, h: ndarray, ndarray
Filter values (`h`) at frequencies (`frequency`) are provided.
"""
# Nyquist frequency
h = 1.0 / (1 + 1j * (frequency / highcut_frequency)) ** order
highcut_frequency = 300 * 1e3
h *= 1.0 / (1 + 1j * (frequency / highcut_frequency)) ** 1
return h | f8ff570d209560d65b4ccc9fdfd2d26ec8a12d35 | 705,368 |
def add_to_master_list(single_list, master_list):
"""This function appends items in a list to the master list.
:param single_list: List of dictionaries from the paginated query
:type single_list: list
:param master_list: Master list of dictionaries containing group information
:type master_list: list
:returns: The master list with the appended data
"""
for list_item in single_list:
master_list.append(list_item)
return master_list | 4b4e122e334624626c7db4f09278b44b8b141504 | 705,370 |
def unmatched(match):
"""Return unmatched part of re.Match object."""
start, end = match.span(0)
return match.string[:start] + match.string[end:] | 6d34396c2d3c957d55dbef16c2673bb7f571205c | 705,373 |
def cubicgw(ipparams, width, etc = []):
"""
This function fits the variation in Gaussian-measured PRF half-widths using a 2D cubic.
Parameters
----------
x1: linear coefficient in x
x2: quadratic coefficient in x
x3: cubic coefficient in x
y1: linear coefficient in y
y2: quadratic coefficient in y
y3: cubic coefficient in y
c : constant
Returns
-------
returns the flux values for the intra-pixel model
Revisions
---------
2018-11-16 Kevin Stevenson, STScI
[email protected]
Original version
"""
x1 = ipparams[0]
x2 = ipparams[1]
x3 = ipparams[2]
y1 = ipparams[3]
y2 = ipparams[4]
y3 = ipparams[5]
c = ipparams[6]
s0 = ipparams[7]
sy, sx = width
return x1*(sx-s0) + x2*(sx-s0)**2 + x3*(sx-s0)**3 + y1*(sy-s0) + y2*(sy-s0)**2 + y3*(sy-s0)**3 + c | 334be9d8dc8baaddf122243e4f19d681efc707cf | 705,374 |
def get_columns_by_type(df, req_type):
"""
get columns by type of data frame
Parameters:
df : data frame
req_type : type of column like categorical, integer,
Returns:
df: Pandas data frame
"""
g = df.columns.to_series().groupby(df.dtypes).groups
type_dict = {k.name: v for k, v in g.items()}
return type_dict.get(req_type) | aeedea92fbfb720ca6e7a9cd9920827a6ad8c6b0 | 705,376 |
def get_total(lines):
"""
This function takes in a list of lines and returns
a single float value that is the total of a particular
variable for a given year and tech.
Parameters:
-----------
lines : list
This is a list of datalines that we want to total.
Returns:
--------
total : float
This is the sum total from the data lines.
"""
total = 0.0
for line in lines:
data_sep = line.split()
total += float(data_sep[0])
return total | 284f8061f3659999ae7e4df104c86d0077b384da | 705,377 |
def box(t, t_start, t_stop):
"""Box-shape (Theta-function)
The shape is 0 before `t_start` and after `t_stop` and 1 elsewhere.
Args:
t (float): Time point or time grid
t_start (float): First value of `t` for which the box has value 1
t_stop (float): Last value of `t` for which the box has value 1
Note:
You may use :class:`numpy.vectorize`, :func:`functools.partial`, or
:func:`qutip_callback`, cf. :func:`flattop`.
"""
if t < t_start:
return 0.0
if t > t_stop:
return 0.0
return 1.0 | 8f4f0e57323f38c9cfa57b1661c597b756e8c4e7 | 705,378 |
import json
import time
def sfn_result(session, arn, wait=10):
"""Get the results of a StepFunction execution
Args:
session (Session): Boto3 session
arn (string): ARN of the execution to get the results of
wait (int): Seconds to wait between polling
Returns:
dict|None: Dict of Json data or
None if there was an error getting the failure output
"""
client = session.client('stepfunctions')
while True:
resp = client.describe_execution(executionArn = arn)
if resp['status'] != 'RUNNING':
if 'output' in resp:
return json.loads(resp['output'])
else:
resp = client.get_execution_history(executionArn = arn,
reverseOrder = True)
event = resp['events'][0]
for key in ['Failed', 'Aborted', 'TimedOut']:
key = 'execution{}EventDetails'.format(key)
if key in event:
return event[key]
return None
else:
time.sleep(wait) | ba8a80e81aa5929360d5c9f63fb7dff5ebaf91f3 | 705,379 |
def to_numpy(tensor):
"""Convert 3-D torch tensor to a 3-D numpy array.
Args:
tensor: Tensor to be converted.
"""
return tensor.transpose(0, 1).transpose(1, 2).clone().numpy() | 034e016caccdf18e8e33e476673884e2354e21c7 | 705,383 |
import time
def wait_for_result(polling_function, polling_config):
"""
wait_for_result will periodically run `polling_function`
using the parameters described in `polling_config` and return the
output of the polling function.
Args:
polling_config (PollingConfig): The parameters to use to poll
the db.
polling_function (Callable[[], (bool, Any)]): The function being
polled. The function takes no arguments and must return a
status which indicates if the function was succesful or
not, as well as some return value.
Returns:
Any: The output of the polling function, if it is succesful,
None otherwise.
"""
if polling_config.polling_interval == 0:
iterations = 1
else:
iterations = int(polling_config.timeout // polling_config.polling_interval) + 1
for _ in range(iterations):
(status, result) = polling_function()
if status:
return result
time.sleep(polling_config.polling_interval)
if polling_config.strict:
assert False
return None | 663f23b3134dabcf3cc3c2f72db33d09ca480555 | 705,386 |
def file_version_summary(list_of_files):
"""
Given the result of list_file_versions, returns a list
of all file versions, with "+" for upload and "-" for
hide, looking like this:
['+ photos/a.jpg', '- photos/b.jpg', '+ photos/c.jpg']
"""
return [('+ ' if (f['action'] == 'upload') else '- ') + f['fileName'] for f in list_of_files] | 8ca8e75c3395ea13c6db54149b12e62f07aefc13 | 705,387 |
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params):
"""Converts a pwm signal (measured in microseconds)
to a corresponding duty cycle on the gpio pwm pin
Parameters
----------
pulsewidth_micros : float
Width of the pwm signal in microseconds
pwm_params : PWMParams
PWMParams object
Returns
-------
float
PWM duty cycle corresponding to the pulse width
"""
return int(pulsewidth_micros / 1e6 * pwm_params.freq * pwm_params.range) | e627b84bf7e01f3d4dcb98ec94271cd34249fb23 | 705,389 |
def parse_data_name(line):
"""
Parses the name of a data item line, which will be used as an attribute name
"""
first = line.index("<") + 1
last = line.rindex(">")
return line[first:last] | 53a9c7e89f5fa5f47dad6bfc211d3de713c15c67 | 705,402 |
def api_error(api, error):
"""format error message for api error, if error is present"""
if error is not None:
return "calling: %s: got %s" % (api, error)
return None | a9269a93d51e3203646886a893998ffec6488c95 | 705,403 |
def build_template(ranges, template, build_date, use_proxy=False, redir_target=""):
"""
Input: output of process_<provider>_ranges(), output of get_template()
Output: Rendered template string ready to write to disk
"""
return template.render(
ranges=ranges["ranges"],
header_comments=ranges["header_comments"],
build_date=build_date,
use_proxy=use_proxy,
redir_target=redir_target,
) | ec10897cb6f92e2b927f4ef84511a7deab8cd37d | 705,405 |
import re
def finder(input, collection, fuzzy=False, accessor=lambda x: x):
"""
Args:
input (str): A partial string which is typically entered by a user.
collection (iterable): A collection of strings which will be filtered
based on the `input`.
fuzzy (bool): perform a fuzzy search (default=False)
Returns:
suggestions (generator): A generator object that produces a list of
suggestions narrowed down from `collection` using the `input`.
"""
suggestions = []
input = str(input) if not isinstance(input, str) else input
pat = input
if fuzzy:
pat = ".*?".join(map(re.escape, input))
regex = re.compile(pat, re.IGNORECASE)
for item in collection:
r = regex.search(accessor(item))
if r:
suggestions.append((len(r.group()), r.start(), accessor(item), item))
return (z[-1] for z in sorted(suggestions)) | 1bbe22f6b38f447f20071bd810cfee6e4e491f5f | 705,408 |
def str2int(video_path):
"""
argparse returns and string althout webcam uses int (0, 1 ...)
Cast to int if needed
"""
try:
return int(video_path)
except ValueError:
return video_path | 2d4714ec53304fb6cafabd5255a838b478780f8a | 705,409 |
def log_sum_exp(input, dim=None, keepdim=False):
"""Numerically stable LogSumExp.
Args:
input (Tensor)
dim (int): Dimension along with the sum is performed
keepdim (bool): Whether to retain the last dimension on summing
Returns:
Equivalent of log(sum(exp(inputs), dim=dim, keepdim=keepdim)).
"""
# For a 1-D array x (any array along a single dimension),
# log sum exp(x) = s + log sum exp(x - s)
# with s = max(x) being a common choice.
if dim is None:
input = input.view(-1)
dim = 0
max_val = input.max(dim=dim, keepdim=True)[0]
output = max_val + (input - max_val).exp().sum(dim=dim, keepdim=True).log()
if not keepdim:
output = output.squeeze(dim)
return output | c9c867d9d81191922a56716dab128ea71821a638 | 705,412 |
def adriatic_name(p, i, j, a):
""" Return the name for given parameters of Adriatic indices"""
#(j)
name1 = {1:'Randic type ',\
2:'sum ',\
3:'inverse sum ', \
4:'misbalance ', \
5:'inverse misbalance ', \
6:'min-max ', \
7:'max-min ', \
8:'symmetric division '}
# (i,a)
name2 = {(1, 0.5):'lor',\
(1,1):'lo', \
(1,2):'los', \
(2,-1):'in', \
(2, -0.5):'ir', \
(2, 0.5):'ro', \
(2,1):'', \
(2,2):'s', \
(3, 0.5):'ha', \
(3,2):'two'}
#(p)
name3 = {0: 'deg', 1: 'di'}
return (name1[j] + name2[(i, a)] + name3[p]) | d08ed926d80aa19326ab4548288a0b9cb02737e4 | 705,415 |
def gcd(number1: int, number2: int) -> int:
"""Counts a greatest common divisor of two numbers.
:param number1: a first number
:param number2: a second number
:return: greatest common divisor"""
number_pair = (min(abs(number1), abs(number2)), max(abs(number1), abs(number2)))
while number_pair[0] > 0:
number_pair = (number_pair[1] % number_pair[0], number_pair[0])
return number_pair[1] | 9f22c315cc23e2bbf954f06d416a2c44f95ddbb7 | 705,416 |
def get_overlapping_timestamps(timestamps: list, starttime: int, endtime: int):
"""
Find the timestamps in the provided list of timestamps that fall between starttime/endtime. Return these timestamps
as a list. First timestamp in the list is always the nearest to the starttime without going over.
Parameters
----------
timestamps
list of timestamps we want to pull from, to get the timestamps between starttime and endtime
starttime
integer utc timestamp in seconds
endtime
integer utc timestamp in seconds
Returns
-------
list
list of timestamps that are within the starttime/endtime range
"""
final_timestamps = []
# we require a starting time stamp that is either less than the given starttime or no greater than
# the given starttime by 60 seconds
buffer = 60
starting_timestamp = None
for tstmp in timestamps: # first pass, find the nearest timestamp (to starttime) without going over the starttime
if tstmp < starttime + buffer:
if not starting_timestamp:
starting_timestamp = tstmp
elif (tstmp > starting_timestamp) and (tstmp <= starttime):
starting_timestamp = tstmp
if starting_timestamp is None:
# raise ValueError('VesselFile: Found no overlapping timestamps for range {} -> {}, within the available timestamps: {}'.format(starttime, endtime, timestamps))
return final_timestamps
starttime = starting_timestamp
final_timestamps.append(str(starttime))
for tstmp in timestamps: # second pass, append all timestamps that are between the starting timestamp and endtime
if (tstmp > starttime) and (tstmp <= endtime):
final_timestamps.append(str(tstmp))
return final_timestamps | 0ad6836d43d670f811b436e34887e159462c9ec1 | 705,417 |
def is_sequence(arg):
"""Check if an object is iterable (you can loop over it) and not a string."""
return not hasattr(arg, "strip") and hasattr(arg, "__iter__") | 466154b8ef9d19b53744187d44dc6cd172a70f62 | 705,419 |
def fix_stddev_function_name(self, compiler, connection):
"""
Fix function names to 'STDEV' or 'STDEVP' as used by mssql
"""
function = 'STDEV'
if self.function == 'STDDEV_POP':
function = 'STDEVP'
return self.as_sql(compiler, connection, function=function) | b1fa48801fb397590ad5fb249d928906e7c21c8a | 705,420 |
def d_d_theta_inv(y, alpha):
"""
xi'(y) = 1/theta''(xi(y)) > 0
= alpha / (1 - |y|)^2
Nikolova et al 2014, table 1, theta_2 and eq 5.
"""
assert -1 < y < 1 and alpha > 0
denom = 1 - abs(y)
return alpha / (denom*denom) | 8ed796a46021f64ca3e24972abcf70bd6f64976d | 705,424 |
def center_crop(img, crop_height, crop_width):
""" Crop the central part of an image.
Args:
img (ndarray): image to be cropped.
crop_height (int): height of the crop.
crop_width (int): width of the crop.
Return:
(ndarray): the cropped image.
"""
def get_center_crop_coords(height, width, crop_height, crop_width):
y1 = (height - crop_height) // 2
y2 = y1 + crop_height
x1 = (width - crop_width) // 2
x2 = x1 + crop_width
return x1, y1, x2, y2
height, width = img.shape[:2]
x1, y1, x2, y2 = get_center_crop_coords(
height, width, crop_height, crop_width)
return img[y1:y2, x1:x2, ...] | 6e5fafee8c34632b61d047e9eb66e9b08b5d0203 | 705,425 |
def obj_size_avg_residual(coeffs, avg_size, class_id):
"""
:param coeffs: object sizes
:param size_template: dictionary that saves the mean size of each category
:param class_id: nyu class id.
:return: size residual ground truth normalized by the average size
"""
size_residual = (coeffs - avg_size[class_id]) / avg_size[class_id]
return size_residual | 8d44d4ebf273baf460195ec7c6ade58c8d057025 | 705,428 |
def _get_chromosome_dirs(input_directory):
"""Collect chromosome directories"""
dirs = []
for d in input_directory.iterdir():
if not d.is_dir():
continue
# Just in case user re-runs and
# does not delete output files
elif d.name == 'logs':
continue
elif d.name == 'p_distance_output':
continue
else:
dirs.append(d)
return dirs | 5047c0c158f11794e312643dbf7d307b381ba59f | 705,429 |
def format_imports(import_statements):
"""
-----
examples:
@need
from fastest.constants import TestBodies
@end
@let
import_input = TestBodies.TEST_STACK_IMPORTS_INPUT
output = TestBodies.TEST_STACK_IMPORTS_OUTPUT
@end
1) format_imports(import_input) -> output
-----
:param import_statements: list
:return: list
"""
return [
'{}\n'.format(import_statement.strip())
for import_statement in import_statements
if len(import_statement) > 0
] | 91514d19da4a4dab8c832e6fc2d3c6cbe7cca04a | 705,430 |
def extract_signals(data, fs, segmentation_times):
"""
Signal that given the set of segmentation times, extract the signal from the raw trace.
Args:
data : Numpy
The input seismic data containing both, start and end times of the seismic data.
fs : float
The sampling frequency.
segmentation_times : list
A list containing the segmentation of the file
Returns:
List
A list containing the extracted signals.
"""
signals = []
durations = []
for m in segmentation_times:
segmented = data[int(m[0] * fs): int(m[1] * fs)]
signals.append(segmented)
durations.append(segmented.shape[0]/float(fs))
return signals, durations | 81ff3d0b343dbba218eb5d2d988b8ca20d1a7209 | 705,433 |
def follow_card(card, deck_size, shuffles, shuffler):
"""Follow position of the card in deck of deck_size during shuffles."""
position = card
for shuffle, parameter in shuffles:
shuffling = shuffler(shuffle)
position = shuffling(deck_size, position, parameter)
return position | 10774bd899afde0d64cbf800bc3dad1d86543022 | 705,437 |
import torch
def besseli(X, order=0, Nk=64):
""" Approximates the modified Bessel function of the first kind,
of either order zero or one.
OBS: Inputing float32 can lead to numerical issues.
Args:
X (torch.tensor): Input (N, 1).
order (int, optional): 0 or 1, defaults to 0.
Nk (int, optional): Terms in summation, higher number, better approximation.
Defaults to 50.
Returns:
I (torch.tensor): Modified Bessel function of the first kind (N, 1).
See also:
https://mathworld.wolfram.com/ModifiedBesselFunctionoftheFirstKind.html
"""
device = X.device
dtype = X.dtype
if len(X.shape) == 1:
X = X[:, None]
N = X.shape[0]
else:
N = 1
# Compute factorial term
X = X.repeat(1, Nk)
K = torch.arange(0, Nk, dtype=dtype, device=device)
K = K.repeat(N, 1)
K_factorial = (K + 1).lgamma().exp()
if order == 0:
# ..0th order
i = torch.sum((0.25 * X ** 2) ** K / (K_factorial ** 2), dim=1, dtype=torch.float64)
else:
# ..1st order
i = torch.sum(
0.5 * X * ((0.25 * X ** 2) ** K /
(K_factorial * torch.exp(torch.lgamma(K + 2)))), dim=1, dtype=torch.float64)
return i | 5233398b240244f13af595088077b8e43d2a4b2f | 705,440 |
def min_rank(series, ascending=True):
"""
Equivalent to `series.rank(method='min', ascending=ascending)`.
Args:
series: column to rank.
Kwargs:
ascending (bool): whether to rank in ascending order (default is `True`).
"""
ranks = series.rank(method="min", ascending=ascending)
return ranks | a772618570517a324a202d4803983240cb54396b | 705,443 |
import yaml
def load_yaml(filepath):
"""Import YAML config file."""
with open(filepath, "r") as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc) | e1ec81bf36d293788303e4b3379e45ecdfb38dc0 | 705,445 |
import json
import logging
def parse_json(json_path):
"""
parser JSON
Args:
json_path: input json file path
Returns:
json_dict: parser json dict result
"""
try:
with open(json_path) as json_file:
json_dict = json.load(json_file)
except Exception:
logging.error("json file load error !")
else:
return json_dict | 4bb9b14d3a751451dd2a75da9b60a355934ffa65 | 705,446 |
def count_possibilities(dic):
"""
Counts how many unique names can be created from the
combinations of each lists contained in the passed dictionary.
"""
total = 1
for key, value in dic.items():
total *= len(value)
return total | 856eee9bac0ddf3dbc7b714bb26fe6d4f003ef95 | 705,449 |
def get_dgs(align_dg_dict):
"""
Function that creates inverse dictionary of align_dg_dict
align_dg_dict: dict. Dictionary of alignments and clustering DG assignments
Returns dg_align_dict: dict, k=dg_id, v=[alignids]
align_dg_dict comes from get_spectral(graph) or get_cliques(graph)
"""
dgs_list = set(align_dg_dict.values()) #list of all duplex groups
dg_align_dict = {}
for dg in dgs_list:
dg_align_list =[x for (x,y) in align_dg_dict.items() if y == dg]
dg_align_dict[dg] = dg_align_list
return dg_align_dict
#test case: | 85bca47657c83d2b308d38f05d1c88d9a78fa448 | 705,451 |
from typing import Optional
def parse_options(dict_in: Optional[dict], defaults: Optional[dict] = None):
"""
Utility function to be used for e.g. kwargs
1) creates a copy of dict_in, such that it is safe to change its entries
2) converts None to an empty dictionary (this is useful, since empty dictionaries cant be argument defaults)
3) optionally, sets defaults, if keys are not present
Parameters
----------
dict_in
defaults
Returns
-------
"""
if dict_in is None:
dict_in = {}
else:
dict_in = dict_in.copy()
if defaults:
for key in defaults:
dict_in.setdefault(key, defaults[key])
return dict_in | d679539ba29f4acab11f5db59c324473a2e24cc6 | 705,452 |
def GetMaxHarmonic( efit ):
"""Determine highest-order of harmonic amplitudes in an ellipse-fit object"""
# We assume that columns named "ai3_err", "ai4_err", "ai5_err", etc.
# exist, up to "aiM_err", where M is the maximum harmonic number
momentNums = [int(cname.rstrip("_err")[2:]) for cname in efit.colNames
if cname[:2] == "ai" and cname[-4:] == "_err"]
return max(momentNums) | e11645efa40ce3995788a05c8955d0d5a8804955 | 705,453 |
def no_op(loss_tensors):
"""no op on input"""
return loss_tensors | 317474aa2ed41668781042a22fb43834dc672bf2 | 705,455 |
import torch
def generic_fftshift(x,axis=[-2,-1],inverse=False):
"""
Fourier shift to center the low frequency components
Parameters
----------
x : torch Tensor
Input array
inverse : bool
whether the shift is for fft or ifft
Returns
-------
shifted array
"""
if len(axis) > len(x.shape):
raise ValueError('Not enough axis to shift around!')
y = x
for axe in axis:
dim_size = x.shape[axe]
shift = int(dim_size/2)
if inverse:
if not dim_size%2 == 0:
shift += 1
y = torch.roll(y,shift,axe)
return y | 8b5f84f0ed2931a3c1afac7c5632e2b1955b1cd5 | 705,457 |
def make_new_images(dataset, imgs_train, imgs_val):
"""
Split the annotations in dataset into two files train and val
according to the img ids in imgs_train, imgs_val.
"""
table_imgs = {x['id']:x for x in dataset['images']}
table_anns = {x['image_id']:x for x in dataset['annotations']}
keys = ['info', 'licenses', 'images', 'annotations', 'categories']
# Train
dataset_train = dict.fromkeys(keys)
dataset_train['info'] = dataset['info']
dataset_train['licenses'] = dataset['licenses']
dataset_train['categories'] = dataset['categories']
dataset_train['images'] = [table_imgs[x] for x in imgs_train]
dataset_train['annotations'] = [table_anns[x] for x in imgs_train]
# Validation
dataset_val = dict.fromkeys(keys)
dataset_val['info'] = dataset['info']
dataset_val['licenses'] = dataset['licenses']
dataset_val['categories'] = dataset['categories']
dataset_val['images'] = [table_imgs[x] for x in imgs_val]
dataset_val['annotations'] = [table_anns[x] for x in imgs_val]
return dataset_train, dataset_val | d5851974ad63caaadd390f91bdf395a4a6f1514d | 705,458 |
import tkinter as tk
from tkinter import filedialog
def select_file(title: str) -> str:
"""Opens a file select window and return the path to selected file"""
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title=title)
return file_path | 59fdb7945389c2ba75d27e1fe20b596c4497bac1 | 705,459 |
def _loop_over(var):
""" Checks if a variable is in the form of an iterable (list/tuple)
and if not, returns it as a list. Useful for allowing argument
inputs to be either lists (e.g. [1, 3, 4]) or single-valued (e.g. 3).
Parameters
----------
var : int or float or list
Variable to check for iterability.
Returns
-------
var : list
Variable converted to list if single-valued input.
"""
if hasattr(var,"__iter__"):
return var
else:
return [var] | 254143646416af441d3858140b951b7854a0241c | 705,461 |
from typing import Any
from typing import List
from typing import Dict
def transform_database_account_resources(
account_id: Any, name: Any, resource_group: Any, resources: List[Dict],
) -> List[Dict]:
"""
Transform the SQL Database/Cassandra Keyspace/MongoDB Database/Table Resource response for neo4j ingestion.
"""
for resource in resources:
resource['database_account_name'] = name
resource['database_account_id'] = account_id
resource['resource_group_name'] = resource_group
return resources | dac566a1e09e1e395ff6fb78d6f8931a2bca58cb | 705,462 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.