content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def all(iterable: object) -> bool:
"""all."""
for element in iterable:
if not element:
return False
return True
| 5,345,000 |
def ind2slice(Is):
"""Convert boolean and integer index arrays to slices.
Integer and boolean arrays are converted to slices that span the selected elements, but may include additional
elements. If possible, the slices are stepped.
Arguments
---------
Is : tuple
tuple of indices (slice, integer array, boolean array, or single integer)
Returns
-------
Js : tuple
tuple of slices
"""
if isinstance(Is, tuple):
return tuple(_ind2slice(I) for I in Is)
else:
return _ind2slice(Is)
| 5,345,001 |
def cleanup_mediawiki(text):
"""Modify mediawiki markup to make it pandoc ready.
Long term this needs to be highly configurable on a site-by-site
basis, but for now I'll put local hacks here.
Returns tuple: cleaned up text, list of any categories
"""
# This tag was probably setup via SyntaxHighlight GeSHi for biopython.org's wiki
#
# <python>
# import antigravity
# </python>
#
# Replacing it with the following makes pandoc happy,
#
# <source lang=python>
# import antigravity
# </source>
#
# Conversion by pandoc to GitHub Flavour Markdown gives:
#
# ``` python
# import antigravity
# ```
#
# Which is much nicer.
#
# =================================================
#
# I may have been misled by old links, but right now I don't
# think there is an easy way to get a table-of-contents with
# (GitHub Flavoured) Markdown which works on GitHub pages.
#
# Meanwhile the MediaWiki __TOC__ etc get left in the .md
# so I'm just going to remove them here.
#
new = []
categories = []
languages = [
"python", "perl", "sql", "bash", "ruby", "java", "xml", "haskell"
]
for line in text.split("\n"):
# line is already unicode
line = line.replace(b"\xe2\x80\x8e".decode("utf-8"),
"") # LEFT-TO-RIGHT
# TODO - Would benefit from state tracking (for tag mismatches)
for lang in languages:
# Easy case <python> etc
if line.lower().startswith("<%s>" % lang):
line = (("<source lang=%s\n" % lang) +
line[len(lang) + 2:]).strip()
# Also cope with <python id=example> etc:
elif line.startswith("<%s " % lang) and ">" in line:
line = (("<source lang=%s " % lang) +
line[len(lang) + 2:]).strip()
# Want to support <python>print("Hello world")</python>
# where open and closing tags are on the same line:
if line.rstrip() == "</%s>" % lang:
line = "</source>"
elif line.rstrip().endswith("</%s>" % lang):
line = line.replace("</%s>" % lang, "\n</source>")
undiv = un_div(line)
if undiv in ["__TOC__", "__FORCETOC__", "__NOTOC__"]:
continue
elif undiv.startswith("[[Image:") and undiv.endswith("]]"):
# Markdown image wrapped in a div does not render on Github Pages,
# remove the div and any attempt at styling it (e.g. alignment)
line = undiv
# Look for any category tag, usually done as a single line:
if "[[Category:" in line:
tag = line[line.index("[[Category:") + 11:]
tag = tag[:tag.index("]]")]
assert ("[[Category:%s]]" %
tag) in line, "Infered %r from %s" % (tag, line)
categories.append(tag)
line = line.replace("[[Category:%s]]" % tag, "").strip()
if not line:
continue
# Special case fix for any category links,
# See https://github.com/jgm/pandoc/issues/2849
if "[[:Category:" in line:
line = line.replace("[[:Category:", "[[Category%3A")
if "[[User:" in line:
line = line.replace("[[User:", "[[User%3A")
new.append(line)
return "\n".join(new), categories
| 5,345,002 |
def test_constructing_a_priority_q_is_empty():
"""Test that a new PriorityQ is empty."""
from electric_slide.scripts.priority_q import PriorityQ
q = PriorityQ()
assert q.values == {}
| 5,345,003 |
def get_popular_authors():
"""Return all authors, most popular first."""
print "--Most_Popular_Authors--"
query = "select author_name,total_views from popular_author"
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
c.execute(query)
for i, row in c:
print i, "--", row, "views"
db.close()
| 5,345,004 |
def select_devices(devices):
""" 选择设备 """
device_count = len(devices)
print("Device list:")
print("0) All devices")
for i, d in enumerate(devices, start=1):
print("%d) %s\t%s" % (i, d['serial'], d['model']))
print("q) Exit this operation")
selected = input("\nselect: ")
nums = None
if selected == '0':
nums = range(0, device_count)
elif selected == 'q':
print("Exit this operation")
exit(-1)
else:
nums = []
for i in re.split(r'[\s+,]', selected):
if i.isdigit():
seq = int(i) - 1
if 0 <= seq < device_count:
nums.append(seq)
continue
print("error input: %s, retry again\n" % i)
return select_devices(devices)
return nums
| 5,345,005 |
async def test_delay_template(hass):
"""Test the delay as a template."""
event = "test_event"
events = []
delay_alias = "delay step"
@callback
def record_event(event):
"""Add recorded event to set."""
events.append(event)
hass.bus.async_listen(event, record_event)
script_obj = script.Script(
hass,
cv.SCRIPT_SCHEMA(
[
{"event": event},
{"delay": "00:00:{{ 5 }}", "alias": delay_alias},
{"event": event},
]
),
)
await script_obj.async_run()
await hass.async_block_till_done()
assert script_obj.is_running
assert script_obj.can_cancel
assert script_obj.last_action == delay_alias
assert len(events) == 1
future = dt_util.utcnow() + timedelta(seconds=5)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert not script_obj.is_running
assert len(events) == 2
| 5,345,006 |
def Fill( h ):
"""fill every empty value in histogram with
previous value.
"""
new_h = []
x,v = h[0]
if type(v) == ListType or type(v) == TupleType:
l = len(v)
previous_v = [0] * l
else:
previous_v = 0
for x, v in h:
if type(v) == ListType or type(v) == TupleType:
for i in range(0,l):
if v[i] == 0:
v[i] = previous_v[i]
else:
previous_v[i] = v[i]
else:
if v == 0:
v = previous_v
else:
previous_v = v
new_h.append( (x, v) )
return new_h
| 5,345,007 |
def pendulum(theta, S, mg, drag) -> ps.Composition:
"""Draw a free body animation of a pendulum.
params:
theta: the angle from the vertical at which the pendulum is.
S: the force exerted toward the pivot.
mg: the force owing to gravity.
drag: the force acting against the motion of the pendulum.
return: A composition of the pendulum
"""
a = theta
P = ps.Point(W / 2, 0.9 * H) # rotation point
path = ps.Arc(P, L, -ps.Angle(np.pi / 2), a)
mass_pt = path.end
rod = ps.Line(P, mass_pt)
theta = ps.AngularDimension(
r"$\theta$", P + ps.Point(0, -L / 4), P + (mass_pt - P).unit_vector * (L / 4), P
)
theta.extension_lines = False
mass = ps.Circle(mass_pt, L / 30.0).set_fill_color(ps.Style.Color.BLUE)
rod_vec = rod.end - rod.start
length = ps.LinearDimension("$L$", mass_pt, P)
# Displace length indication
length = length.translate(ps.Point(-np.cos(a), -np.sin(a)) * (L / 15.0))
length.style.line_width = 0.1
gravity_start = ps.Point(0.8 * L, 0)
gravity = ps.Gravity(P + gravity_start, L / 3)
dashed_thin_black_line = ps.Style()
dashed_thin_black_line.line_style = ps.Style.LineStyle.DASHED
dashed_thin_black_line.line_color = ps.Style.Color.BLACK
dashed_thin_black_line.line_width = 1.0
path.style = dashed_thin_black_line
vertical = ps.Line(rod.start, rod.start + ps.Point(0, -L))
vertical.style = dashed_thin_black_line
rod.style = dashed_thin_black_line
comp = ps.Composition(
{
"body": mass,
"rod": rod,
"vertical": vertical,
"theta": theta,
"path": path,
"g": gravity,
# "L": length,
}
)
magnitude = 1.2 * L / 6 # length of a unit force in figure
force = mg # constant (scaled eq: about 1)
force *= magnitude
mg_force = (
ps.Force(
"$mg$",
mass_pt,
mass_pt + ps.Point(0, 1) * force,
text_position=ps.TextPosition.END,
)
if force != 0
else None
)
force = S
force *= magnitude
rod_force = (
ps.Force(
"S",
mass_pt,
mass_pt - rod_vec.unit_vector * force,
text_position=ps.TextPosition.END,
)
if force != 0
else None
)
force = drag
force *= magnitude
air_force = (
ps.Force(
"",
mass_pt,
mass_pt - rod_vec.normal * force,
)
if force != 0
else None
)
x0y0 = ps.Text("$(x_0,y_0)$", P + ps.Point(-0.4, -0.1))
ir = ps.Force(
r"$\mathbf{i}_r$",
P,
P + rod_vec.unit_vector * (L / 10),
text_position=ps.TextPosition.END,
# spacing=ps.Point(0.015, 0)
)
ith = ps.Force(
r"$\mathbf{i}_{\theta}$",
P,
P + rod_vec.normal * (L / 10),
text_position=ps.TextPosition.END,
# spacing=ps.Point(0.02, 0.005)
)
body_diagram = ps.Composition(
{
"mg": mg_force,
"S": rod_force,
"air": air_force,
"ir": ir,
"ith": ith,
"origin": x0y0,
}
)
comp = comp.merge(body_diagram)
return comp
| 5,345,008 |
def get_items():
"""Fetches items from `INITIAL_OFFSET` in batches of `PAGINATION_OFFSET` until there are no
more """
offset = INITIAL_OFFSET
items = []
while True:
batch = get_page_of_items(JSON_ENDPOINT.format(offset))
if not batch:
break
items.extend(batch)
offset += PAGINATION_OFFSET
return items
| 5,345,009 |
def make_file_directory_internal(base_path):
"""Generates the database folder structure for internal data."""
# Corrs Data
os.mkdir(os.path.join(base_path, 'Corrs'))
cor_data = ['Genes', 'Terms']
cor_data_type = ['csv', 'npz']
for cor_dat in cor_data:
os.mkdir(os.path.join(base_path, 'Corrs', cor_dat))
for cor_dat_type in cor_data_type:
os.mkdir(os.path.join(base_path, 'Corrs', cor_dat, cor_dat_type))
# Maps Data
os.mkdir(os.path.join(base_path, 'Maps'))
maps_data = ['Genes', 'Oscs', 'Exponents', 'Terms', 'Anat', 'Scouts']
for maps_dat in maps_data:
os.mkdir(os.path.join(base_path, 'Maps', maps_dat))
# Processed Data
os.mkdir(os.path.join(base_path, 'Processed'))
proc_data = ['meg', 'maps']
for proc_dat in proc_data:
os.mkdir(os.path.join(base_path, 'Processed', proc_dat))
| 5,345,010 |
def test_xgb_categorical_split():
"""Test toy XGBoost model with categorical splits"""
dataset = 'xgb_toy_categorical'
tl_model = treelite.Model.load(dataset_db[dataset].model, model_format='xgboost_json')
X, _ = load_svmlight_file(dataset_db[dataset].dtest, zero_based=True)
expected_pred = load_txt(dataset_db[dataset].expected_margin)
out_pred = treelite.gtil.predict(tl_model, X.toarray())
np.testing.assert_almost_equal(out_pred, expected_pred, decimal=5)
| 5,345,011 |
def tcombinations_with_replacement(iterable, r):
"""
>>> tcombinations_with_replacement('ABCD', 0)
((),)
>>> tcombinations_with_replacement('ABCD', 1)
(('A',), ('B',), ('C',), ('D',))
>>> tcombinations_with_replacement('ABCD', 2)
(('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'C'), ('C', 'D'), ('D', 'D'))
>>> tcombinations_with_replacement('ABCD', 3)
(('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'A', 'D'), ('A', 'B', 'B'), ('A', 'B', 'C'), ('A', 'B', 'D'), ('A', 'C', 'C'), ('A', 'C', 'D'), ('A', 'D', 'D'), ('B', 'B', 'B'), ('B', 'B', 'C'), ('B', 'B', 'D'), ('B', 'C', 'C'), ('B', 'C', 'D'), ('B', 'D', 'D'), ('C', 'C', 'C'), ('C', 'C', 'D'), ('C', 'D', 'D'), ('D', 'D', 'D'))
>>> tcombinations_with_replacement('ABCD', 4)
(('A', 'A', 'A', 'A'), ('A', 'A', 'A', 'B'), ('A', 'A', 'A', 'C'), ('A', 'A', 'A', 'D'), ('A', 'A', 'B', 'B'), ('A', 'A', 'B', 'C'), ('A', 'A', 'B', 'D'), ('A', 'A', 'C', 'C'), ('A', 'A', 'C', 'D'), ('A', 'A', 'D', 'D'), ('A', 'B', 'B', 'B'), ('A', 'B', 'B', 'C'), ('A', 'B', 'B', 'D'), ('A', 'B', 'C', 'C'), ('A', 'B', 'C', 'D'), ('A', 'B', 'D', 'D'), ('A', 'C', 'C', 'C'), ('A', 'C', 'C', 'D'), ('A', 'C', 'D', 'D'), ('A', 'D', 'D', 'D'), ('B', 'B', 'B', 'B'), ('B', 'B', 'B', 'C'), ('B', 'B', 'B', 'D'), ('B', 'B', 'C', 'C'), ('B', 'B', 'C', 'D'), ('B', 'B', 'D', 'D'), ('B', 'C', 'C', 'C'), ('B', 'C', 'C', 'D'), ('B', 'C', 'D', 'D'), ('B', 'D', 'D', 'D'), ('C', 'C', 'C', 'C'), ('C', 'C', 'C', 'D'), ('C', 'C', 'D', 'D'), ('C', 'D', 'D', 'D'), ('D', 'D', 'D', 'D'))
>>> tcombinations_with_replacement('ABC', 4)
(('A', 'A', 'A', 'A'), ('A', 'A', 'A', 'B'), ('A', 'A', 'A', 'C'), ('A', 'A', 'B', 'B'), ('A', 'A', 'B', 'C'), ('A', 'A', 'C', 'C'), ('A', 'B', 'B', 'B'), ('A', 'B', 'B', 'C'), ('A', 'B', 'C', 'C'), ('A', 'C', 'C', 'C'), ('B', 'B', 'B', 'B'), ('B', 'B', 'B', 'C'), ('B', 'B', 'C', 'C'), ('B', 'C', 'C', 'C'), ('C', 'C', 'C', 'C'))
"""
return tuple(combinations_with_replacement(iterable, r))
| 5,345,012 |
def discreteFiber(c, s, B=I3, ndiv=120, invert=False, csym=None, ssym=None):
"""
Generate symmetrically reduced discrete orientation fiber.
Parameters
----------
c : TYPE
DESCRIPTION.
s : TYPE
DESCRIPTION.
B : TYPE, optional
DESCRIPTION. The default is I3.
ndiv : TYPE, optional
DESCRIPTION. The default is 120.
invert : TYPE, optional
DESCRIPTION. The default is False.
csym : TYPE, optional
DESCRIPTION. The default is None.
ssym : TYPE, optional
DESCRIPTION. The default is None.
Raises
------
RuntimeError
DESCRIPTION.
Returns
-------
retval : TYPE
DESCRIPTION.
"""
ztol = cnst.sqrt_epsf
# arg handling for c
if hasattr(c, '__len__'):
if hasattr(c, 'shape'):
assert c.shape[0] == 3, \
'scattering vector must be 3-d; yours is %d-d' \
% (c.shape[0])
if len(c.shape) == 1:
c = c.reshape(3, 1)
elif len(c.shape) > 2:
raise RuntimeError(
'incorrect arg shape; must be 1-d or 2-d, yours is %d-d'
% (len(c.shape))
)
else:
# convert list input to array and transpose
if len(c) == 3 and isscalar(c[0]):
c = asarray(c).reshape(3, 1)
else:
c = asarray(c).T
else:
raise RuntimeError('input must be array-like')
# arg handling for s
if hasattr(s, '__len__'):
if hasattr(s, 'shape'):
assert s.shape[0] == 3, \
'scattering vector must be 3-d; yours is %d-d' \
% (s.shape[0])
if len(s.shape) == 1:
s = s.reshape(3, 1)
elif len(s.shape) > 2:
raise RuntimeError(
'incorrect arg shape; must be 1-d or 2-d, yours is %d-d'
% (len(s.shape)))
else:
# convert list input to array and transpose
if len(s) == 3 and isscalar(s[0]):
s = asarray(s).reshape(3, 1)
else:
s = asarray(s).T
else:
raise RuntimeError('input must be array-like')
nptc = c.shape[1]
npts = s.shape[1]
c = unitVector(dot(B, c)) # turn c hkls into unit vector in crys frame
s = unitVector(s) # convert s to unit vector in samp frame
retval = []
for i_c in range(nptc):
dupl_c = tile(c[:, i_c], (npts, 1)).T
ax = s + dupl_c
anrm = columnNorm(ax).squeeze() # should be 1-d
okay = anrm > ztol
nokay = okay.sum()
if nokay == npts:
ax = ax / tile(anrm, (3, 1))
else:
nspace = nullSpace(c[:, i_c].reshape(3, 1))
hperp = nspace[:, 0].reshape(3, 1)
if nokay == 0:
ax = tile(hperp, (1, npts))
else:
ax[:, okay] = ax[:, okay] / tile(anrm[okay], (3, 1))
ax[:, not okay] = tile(hperp, (1, npts - nokay))
q0 = vstack([zeros(npts), ax])
# find rotations
# note: the following line fixes bug with use of arange
# with float increments
phi = arange(0, ndiv) * (2*pi/float(ndiv))
qh = quatOfAngleAxis(phi, tile(c[:, i_c], (ndiv, 1)).T)
# the fibers, arraged as (npts, 4, ndiv)
qfib = dot(
quatProductMatrix(qh, mult='right'),
q0
).transpose(2, 1, 0)
if csym is not None:
retval.append(
toFundamentalRegion(
qfib.squeeze(),
crysSym=csym,
sampSym=ssym
)
)
else:
retval.append(fixQuat(qfib).squeeze())
return retval
| 5,345,013 |
def random_organism(invalid_data):
"""
Generate Random Organism
return: string containing "organism" name from CanCOGeN vocabulary.
"""
return random.choice(covid19_vocab_dict.get('organism')), global_valid_data
| 5,345,014 |
def test_confirm_user_family(app, session, monkeypatch):
"""Ensure a user is automatically confirmed in family mode."""
monkeypatch.setitem(app.config, '_JT_SERVER_MODE', 'family')
u = auth_service.register_user(session, '[email protected]', 'hunter2JT', 'Test User')
assert u.id == 1
assert u.uid_hash is not None
assert u.active is True
assert u.confirmed is True
assert u.confirmed_at is not None
| 5,345,015 |
def test_set_output_volume():
"""
Test if it set the volume of sound (range 0 to 100)
"""
mock = MagicMock(return_value={"retcode": 0})
with patch.dict(mac_desktop.__salt__, {"cmd.run_all": mock}), patch(
"salt.modules.mac_desktop.get_output_volume", MagicMock(return_value="25")
):
assert mac_desktop.set_output_volume("25")
| 5,345,016 |
def fate_bias(adata,
group,
basis='umap',
fate_bias_df=None,
figsize=(6, 4),
save_show_or_return='show',
save_kwargs={},
**cluster_maps_kwargs
):
"""Plot the lineage (fate) bias of cells states whose vector field trajectories are predicted.
This function internally calls `dyn.tl.fate_bias` to calculate fate bias dataframe. You can also visualize the data
frame via pandas stlying (https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html), for example:
>>> df = dyn.tl.fate_bias(adata)
>>> df.style.background_gradient(cmap='viridis')
Parameters
----------
adata: :class:`~anndata.AnnData`
AnnData object that contains the predicted fate trajectories in the `uns` attribute.
group: `str`
The column key that corresponds to the cell type or other group information for quantifying the bias of cell
state.
basis: `str` or None (default: `None`)
The embedding data space that cell fates were predicted and cell fates will be quantified.
fate_bias_df: `pandas.DataFrame` or None (default: `None`)
The DataFrame that stores the fate bias information, calculated via fate_bias_df = dyn.tl.fate_bias(adata).
figsize: `None` or `[float, float]` (default: None)
The width and height of a figure.
save_show_or_return: {'show', 'save', 'return'} (default: `show`)
Whether to save, show or return the figure.
save_kwargs: `dict` (default: `{}`)
A dictionary that will passed to the save_fig function. By default it is an empty dictionary and the save_fig function
will use the {"path": None, "prefix": 'fate_bias', "dpi": None, "ext": 'pdf', "transparent": True, "close":
True, "verbose": True} as its parameters. Otherwise you can provide a dictionary that properly modify those keys
according to your needs.
cluster_maps_kwargs:
Additional arguments passed to sns.clustermap.
Returns
-------
Nothing but plot a heatmap shows the fate bias of each cell state to each of the cell group.
"""
import matplotlib.pyplot as plt
fate_bias = fate_bias_pd(adata, group=group, basis=basis) if fate_bias_df is None else fate_bias_df
if 'confidence' in fate_bias.keys():
fate_bias.set_index([fate_bias.index, fate_bias.confidence], inplace=True)
ax = sns.clustermap(fate_bias, col_cluster=True, row_cluster=True, figsize=figsize, yticklabels=False,
**cluster_maps_kwargs)
if save_show_or_return == "save":
s_kwargs = {"path": None, "prefix": 'fate_bias', "dpi": None,
"ext": 'pdf', "transparent": True, "close": True, "verbose": True}
s_kwargs = update_dict(s_kwargs, save_kwargs)
save_fig(**s_kwargs)
elif save_show_or_return == "show":
plt.tight_layout()
plt.show()
elif save_show_or_return == "return":
return ax
| 5,345,017 |
def test_roundtrip():
"""Assert that forward/inverse Rosenblatt transforms is non-destructive."""
corr = numpy.array([[ 1.0, -0.9, 0.3],
[-0.9, 1.0, 0.0],
[ 0.3, 0.0, 1.0]])
dists = chaospy.J(chaospy.Uniform(0, 1), chaospy.Uniform(1, 2),
chaospy.Uniform(2, 3), rotation=[0, 1, 2])
dist1 = chaospy.Nataf(dists, corr)
dists = chaospy.J(chaospy.Uniform(0, 1), chaospy.Uniform(1, 2),
chaospy.Uniform(2, 3), rotation=[2, 1, 0])
dist2 = chaospy.Nataf(dists, corr)
dists = chaospy.J(chaospy.Uniform(0, 1), chaospy.Uniform(1, 2),
chaospy.Uniform(2, 3), rotation=[2, 0, 1])
dist3 = chaospy.Nataf(dists, corr)
mesh = numpy.mgrid[0.25:0.75:3j, 0.25:0.75:5j, 0.25:0.75:4j].reshape(3, -1)
assert not numpy.allclose(dist1.fwd(dist2.inv(mesh)), mesh)
assert numpy.allclose(dist1.fwd(dist1.inv(mesh)), mesh)
assert numpy.allclose(dist2.fwd(dist2.inv(mesh)), mesh)
assert numpy.allclose(dist3.fwd(dist3.inv(mesh)), mesh)
| 5,345,018 |
def build_psa_platform(target, toolchain, delivery_dir, debug, git_commit,
skip_tests, args):
"""
Calls the correct build function and commits if requested.
:param target: Target name.
:param toolchain: Toolchain to be used.
:param delivery_dir: Artifact directory, where images should be placed.
:param debug: Build with debug profile.
:param git_commit: Commit the changes.
:param skip_tests: skip the test images build phase.
:param args: list of extra arguments.
"""
profile = 'debug' if debug else 'release'
if not skip_tests:
if _psa_backend(target) is 'TFM':
build_tests_tfm_platform(target, toolchain, profile, args)
else:
build_tests_mbed_spm_platform(target, toolchain, profile, args)
logger.info("Building default image for {} using {} with {} profile".format(
target, toolchain, profile))
cmd = _get_default_image_build_command(target, toolchain, profile, args)
verbose_check_call(cmd)
logger.info(
"Finished building default image for {} successfully".format(target))
if git_commit:
commit_binaries(target, delivery_dir)
| 5,345,019 |
def comput_mean_ndcg(df, k):
"""
Input:rating_info
(usr_id, movie_id, rating)
output: 平均ndcg
对每一种人 得到他真实分数和预测分数的dataframe
然后得到values
"""
#df.insert(df.shape[1], 'pred', pred)
#print(df.groupby('user_id'))
piece = dict(list(df.groupby('user_id')))
ndcg_list = []
for user in df["user_id"].unique():
user_rating = piece[user]["rating"].values
user_pred_rating = piece[user]['pred'].values
ndcg_score = ndcg(user_pred_rating, user_rating, k)
ndcg_list.append(ndcg_score)
ndcg_list = np.array(ndcg_list)
#return ndcg_list.mean()
return ndcg_list
| 5,345,020 |
def test_warning(prob):
"""Test that a warning is raised when the probability is not between 0 and 1."""
code = SurfaceCode(3)
with pytest.raises(Exception) as exc:
IidNoise(code, prob)
assert str(exc.value) == "Probability is not between 0 and 1."
| 5,345,021 |
def main():
"""
Pre-processes all texts in the corpus, tokenizing, lemmatizing, and
replacing all NE's by their CoreNLP NER label. The output texts are saved to
a specified folder mimicing the corpus texts directory structure.
"""
cm = CorpusManager()
for root, subdirnames, fnames in os.walk(cm.CORENLP_DIRPATH):
for fname in fnames:
if fname.endswith('.xml'):
in_path = os.path.join(root, fname)
out_path = in_path.replace(cm.CORENLP_DIRPATH,
cm.PREPROCESSED_DIRPATH)[:-4] + '.txt'
if os.path.exists(out_path):
logging.info("%s already exists. Skipping %s..." %
(out_path, in_path))
continue
# If the parent directory doesn't exist, create it.
par_dirpath = os.path.split(out_path)[0]
if not os.path.exists(par_dirpath):
os.makedirs(par_dirpath)
# Temporary.
if not par_dirpath.endswith('piper'):
continue
logging.info("Pre-processing %s..." % in_path)
preprocessed_text = preprocess(in_path)
logging.info("Outputting to %s..." % out_path)
with open(out_path, 'w') as f:
f.write(preprocessed_text.encode('utf-8'))
| 5,345,022 |
def to_im_list(IMs: List[str]):
"""Converts a list of string to IM Objects"""
return [IM.from_str(im) for im in IMs]
| 5,345,023 |
def ref_ellipsoid(refell, UNITS='MKS'):
"""
Computes parameters for a reference ellipsoid
Arguments
---------
refell: reference ellipsoid name
Keyword arguments
-----------------
UNITS: output units
MKS: meters, kilograms, seconds
CGS: centimeters, grams, seconds
"""
if refell.upper() in ('CLK66','NAD27'):
#-- Clarke 1866
a_axis = 6378206.4#-- [m] semimajor axis of the ellipsoid
flat = 1.0/294.9786982#-- flattening of the ellipsoid
elif refell.upper() in ('GRS80','NAD83'):
#-- Geodetic Reference System 1980
#-- North American Datum 1983
a_axis = 6378135.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.26#-- flattening of the ellipsoid
GM = 3.986005e14#-- [m^3/s^2] Geocentric Gravitational Constant
elif (refell.upper() == 'GRS67'):
#-- Geodetic Reference System 1967
#-- International Astronomical Union (IAU ellipsoid)
a_axis = 6378160.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.247167427#-- flattening of the ellipsoid
GM = 3.98603e14#-- [m^3/s^2] Geocentric Gravitational Constant
omega = 7292115.1467e-11#-- angular velocity of the Earth [rad/s]
elif (refell.upper() == 'WGS72'):
#-- World Geodetic System 1972
a_axis = 6378135.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.26#-- flattening of the ellipsoid
elif (refell.upper() == 'WGS84'):
#-- World Geodetic System 1984
a_axis = 6378137.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.257223563#-- flattening of the ellipsoid
elif (refell.upper() == 'ATS77'):
#-- Quasi-earth centred ellipsoid for ATS77
a_axis = 6378135.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.257#-- flattening of the ellipsoid
elif (refell.upper() == 'KRASS'):
#-- Krassovsky (USSR)
a_axis = 6378245.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.3#-- flattening of the ellipsoid
elif (refell.upper() == 'INTER'):
#-- International
a_axis = 6378388.0#-- [m] semimajor axis of the ellipsoid
flat = 1/297.0#-- flattening of the ellipsoid
elif (refell.upper() == 'MAIRY'):
#-- Modified Airy (Ireland 1965/1975)
a_axis = 6377340.189#-- [m] semimajor axis of the ellipsoid
flat = 1/299.3249646#-- flattening of the ellipsoid
elif (refell.upper() == 'TOPEX'):
#-- TOPEX/POSEIDON ellipsoid
a_axis = 6378136.3#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.257#-- flattening of the ellipsoid
GM = 3.986004415e14#-- [m^3/s^2]
elif (refell.upper() == 'EGM96'):
#-- EGM 1996 gravity model
a_axis = 6378136.3#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.256415099#-- flattening of the ellipsoid
GM = 3.986004415e14#-- [m^3/s^2]
elif (refell.upper() == 'HGH80'):
#-- Hughes 1980 Ellipsoid used in some NSIDC data
a_axis = 6378273.0#-- [m] semimajor axis of the ellipsoid
flat = 1.0/298.279411123064#-- flattening of the ellipsoid
else:
raise ValueError('Incorrect reference ellipsoid Name')
if refell.upper() not in ('GRS80','GRS67','NAD83','TOPEX','EGM96'):
#-- for ellipsoids not listing the Geocentric Gravitational Constant
GM = 3.986004418e14#-- [m^3/s^2]
if refell.upper() not in ('GRS67'):
#-- for ellipsoids not listing the angular velocity of the Earth
omega = 7292115e-11#-- [rad/s]
#-- convert units to CGS
if (UNITS == 'CGS'):
a_axis *= 100.0
GM *= 10e6
#-- DERIVED PARAMETERS:
#-- mean radius of the Earth having the same volume
#-- (4pi/3)R^3 = (4pi/3)(a^2)b = (4pi/3)(a^3)(1D -f)
rad_e = a_axis*(1.0 -flat)**(1.0/3.0)
#-- semiminor axis of the ellipsoid
b_axis = (1.0 -flat)*a_axis#-- [m]
#-- Ratio between ellipsoidal axes
ratio = (1.0 -flat)
#-- Polar radius of curvature
pol_rad=a_axis/(1.0 -flat)
#-- Linear eccentricity
lin_ecc = np.sqrt((2.0*flat - flat**2)*a_axis**2)
#-- first numerical eccentricity
ecc1 = lin_ecc/a_axis
#-- second numerical eccentricity
ecc2 = lin_ecc/b_axis
#-- m parameter [omega^2*a^2*b/(GM)]
#-- p. 70, Eqn.(2-137)
mp = omega**2*((1 -flat)*a_axis**3)/GM
#-- q, q_0
#-- p. 67, Eqn.(2-113)
q = 0.5*((1.0 + 3.0/(ecc2**2))*np.arctan(ecc2)-3.0/ecc2)
q_0 = 3*(1.0 +1.0/(ecc2**2))*(1.0 -1.0/ecc2*np.arctan(ecc2))-1.0
#-- J_2 p. 75 Eqn.(2-167), p. 76 Eqn.(2-172)
j_2 = (ecc1**2)*(1.0 - 2.0*mp*ecc2/(15.0*q))/3.0
#-- Normalized C20 terms.
#-- p. 60, Eqn.(2-80)
C20 = -j_2/np.sqrt(5.0)
#-- Normal gravity at the equator.
#-- p. 71, Eqn.(2-141)
ga = GM/(a_axis*b_axis)*(1.0 -mp -mp*ecc2*q_0/(6.0*q))
#-- Normal gravity at the pole.
#-- p. 71, Eqn.(2-142)
gb = GM/(a_axis**2.0)*(1.0 +mp*ecc2*q_0/(3.0*q))
#-- ratio between gravity at pole versus gravity at equator
dk = b_axis*gb/(a_axis*ga) - 1.0
#-- Normal potential at the ellipsoid
#-- p. 68, Eqn.(2-123)
U0 = GM/lin_ecc*np.arctan(ecc2)+(1.0/3.0)*omega**2*a_axis**2
#-- Surface area of the reference ellipsoid [m^2]
area = np.pi*a_axis**2.*(2.+((1.-ecc1**2)/ecc1)*np.log((1.+ecc1)/(1.-ecc1)))
#-- Volume of the reference ellipsoid [m^3]
vol = (4.0*np.pi/3.0)*(a_axis**3.0)*(1.0-ecc1**2.0)**0.5
return {'a':a_axis, 'b':b_axis, 'f':flat, 'rad_p':pol_rad, 'rad_e':rad_e,
'ratio':ratio, 'GM':GM, 'omega':omega, 'C20':C20, 'J2':j_2, 'U0':U0,
'dk':dk, 'norm_a':ga, 'norm_b':gb, 'mp':mp, 'q':q, 'q0':q_0,
'ecc':lin_ecc, 'ecc1':ecc1,'ecc2':ecc2, 'area':area, 'volume':vol}
| 5,345,024 |
def is_number(s):
"""
Check if it is a number.
Args:
s: The variable that needs to be checked.
Returns:
bool: True if float, False otherwise.
"""
try:
float(s)
return True
except ValueError:
return False
| 5,345,025 |
def emit(*args, **kwargs):
"""
The action allows users to add particles to an existing particle object without the use of an emitter.
Returns: `int[]` `Integer array containing the list of the particleId attribute values
for the created particles in the same order that the position flags
were passed.`
"""
pass
| 5,345,026 |
def index():
"""
搜索提示功能
根据输入的值自动联想,支持中文,英文,英文首字母
:return: response
"""
start_time = time.time()
# 输入词转小写
wd = request.args.get('wd').lower()
user_id = request.args.get('user_id')
if user_id and user_id != 'None':
print(user_id)
print(type(user_id))
if not wd:
return make_response("""queryList({"q":"","p":false,"bs":"","csor":"0","status":770,"s":[]});""")
# 搜索词(支持中文,英文,英文首字母)
s = wd
# result = search_script_conf.get_tips_word(search_script_conf.sug, search_script_conf.data, s)
# # print('前缀:',result)
global TREE
if TREE is None:
# 第一次为空,需要在接口中加载一次已经生成好的字典树,pickle.loads这一步耗时接近1s
temp = r.get('tree')
TREE = pickle.loads(temp)
# 内容中有字典树,直接获取
suggest = get_tips_word(TREE[0], TREE[1], s)
print('前缀:', suggest)
data_top = {}
if len(suggest) > 0:
# 从redis获取热度值
heat_list = r_decode.hmget("hot_word_heat", suggest)
_map = dict(zip(suggest, heat_list))
# 按照热度值排序
data = dict(sorted(_map.items(), key=lambda x: int(x[1]), reverse=True))
print("热度值排序:", data)
# TODO 获取个性化搜索结果展示
suggest = list(data.keys())[:15]
data_top = {i: data[i] for i in suggest}
response = make_response(
"""queryList({'q':'""" + wd + """','p':false,'s':""" + str(suggest) + """});""")
response.headers['Content-Type'] = 'text/javascript; charset=utf-8'
end_time = time.time()
# 记录日志
ret = dict()
ret['code'] = 200
ret['msg'] = "ok"
ret['search_word'] = wd
ret['search_suggest'] = suggest
ret['heat_rank'] = data_top
ret['search_type'] = 'search_suggest'
ret['gmt_created'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
ret['user_id'] = ''
ret['platformCode'] = ''
ret['total_time'] = end_time - start_time
info(json.dumps(ret, ensure_ascii=False))
return response
| 5,345,027 |
def combineSets(listOfSets):
"""
Combines sets of strings by taking the cross product of the sets and \
concatenating the elements in the resulting tuples
:param listOfSets: 2-D list of strings
:returns: a list of strings
"""
totalCrossProduct = ['']
for i in range(len(listOfSets)):
currentProduct = []
for crossProduct in itertools.product(totalCrossProduct, listOfSets[i]):
currentProduct.append((crossProduct[0].strip() + ' ' + crossProduct[1].strip()).strip())
totalCrossProduct = currentProduct
return totalCrossProduct
| 5,345,028 |
def list_all_connections(pg_id='root', descendants=True):
"""
Lists all connections for a given Process Group ID
Args:
pg_id (str): ID of the Process Group to retrieve Connections from
descendants (bool): True to recurse child PGs, False to not
Returns:
(list): List of ConnectionEntity objects
"""
return list_all_by_kind('connections', pg_id, descendants)
| 5,345,029 |
def find_file(fname):
"""
Return the full file name (path plus name) to file fname.
fname is the name of the file to find.
If the file fname is not found, then simply return None.
"""
for d in get_cli_search_dirs():
full_filename = os.path.join(d, fname)
if os.path.exists(full_filename):
return full_filename
raise Exception('[WARN] Could not find {}; skipping.'.format(fname))
| 5,345,030 |
def save_uptime(machine_config, num_seconds, idle_time, data_log_date):
"""
Create Uptime record and save it in DB.
"""
uptime = Uptime(
stats_machine_config=machine_config,
date=data_log_date,
number_of_seconds=num_seconds,
idle_time=idle_time)
uptime.save()
| 5,345,031 |
def _GetTombstoneData(device, tombstone_file):
"""Retrieve the tombstone data from the device
Args:
device: An instance of DeviceUtils.
tombstone_file: the tombstone to retrieve
Returns:
A list of lines
"""
return device.old_interface.GetProtectedFileContents(
'/data/tombstones/' + tombstone_file)
| 5,345,032 |
def _strTogYear(v):
"""Test gYear value
@param v: the literal string
@return v
@raise ValueError: invalid value
"""
try:
time.strptime(v+"-01-01", "%Y-%m-%d")
return v
except:
raise ValueError("Invalid gYear %s" % v)
| 5,345,033 |
def aca_full_pivoting(A, epsilon):
"""ACA with full pivoting as in the lecture
Takes in a matrix, and returns the CUR decomposition
"""
# R0 = A
Rk = A.copy()
I_list = []
J_list = []
while frobenius_norm(Rk) > epsilon*frobenius_norm(A):
i, j = np.unravel_index(np.argmax(np.abs(Rk), axis=None), Rk.shape)
I_list.append(i)
J_list.append(j)
delta = Rk[i, j]
u = Rk[:, j]
v = Rk[i, :].T / delta
Rk = Rk - np.outer(u, v)
R = A[I_list, :]
U = np.linalg.inv(A[I_list, :][:, J_list])
C = A[:, J_list]
return C, U, R
| 5,345,034 |
def get_word_cloud(words: List[str], max_words=500, image_path=None, image_name=None):
"""
Create a word cloud based on a set of words.
Args:
words (List[str]):
List of words to be included in the word cloud.
max_words (int):
Maximum number of words to be included in the word cloud.
image_path (str):
Path to the image file where to save the word cloud.
image_name (str):
Name of the image where to save the word cloud.
"""
# change the value to black
def black_color_func(
word, font_size, position, orientation, random_state=None, **kwargs
):
return "hsl(0,100%, 1%)"
# set the wordcloud background color to white
# set width and height to higher quality, 3000 x 2000
wordcloud = WordCloud(
font_path="/Library/Fonts/Arial Unicode.ttf",
background_color="white",
width=3000,
height=2000,
max_words=max_words,
).generate(" ".join(words))
# set the word color to black
wordcloud.recolor(color_func=black_color_func)
# set the figsize
plt.figure(figsize=[15, 10])
# plot the wordcloud
plt.imshow(wordcloud, interpolation="bilinear")
# remove plot axes
plt.axis("off")
if image_path is not None and image_name is not None:
# save the image
plt.savefig(os.path.join(image_path, image_name), bbox_inches="tight")
| 5,345,035 |
def get_data_sets(cnn_n_input, data_directory="data_set/", n_data_sets=5):
"""
Retrieve data and partition it into n_data_sets for cross-validation.
"""
print("Partitioning data into", str(n_data_sets), "splits.")
# Get list of labels
list_labels = extract_data.get_labels(data_directory + "labels.txt")
n_labels = len(list_labels)
# Dictionary that gives labels ID
label_to_int = dict()
for i in range(n_labels):
label_to_int[list_labels[i]] = i
# Dictionary that will count how many times each label appears
count_labels = dict()
# Data partitions : (time series, labels)
data_partition = [(list(), list()) for _ in range(n_data_sets)]
# Loop over data_set directory
files = [f for f in os.listdir(data_directory) if fnmatch.fnmatch(f, "*_label.txt")]
for file in files:
# Get label
label = extract_data.extract_label_from_txt(data_directory + file)[1]
# Increment label count
if label in count_labels:
count_labels[label] += 1
else:
count_labels[label] = 1
# Label_id
label_id = label_to_int[label]
# Get time series (data)
data = extract_data.extract_data_from_txt(data_directory + "MIN " + file.split('_')[0] + ".txt")\
.Value.values.astype(dtype="uint16", copy=False)
# Split data into samples
data = create_samples(data, cnn_n_input)
# Create labels
labels = [label_id] * len(data)
# Append to partition
data_partition[count_labels[label] % n_data_sets][0].extend(data) # Add data
data_partition[count_labels[label] % n_data_sets][1].extend(labels) # Add labels
print("--\nBuilding types inventory :")
print(count_labels)
print("--\nNumber of samples in each split :")
for x in data_partition:
print('\t' + str(len(x[0])))
return data_partition
| 5,345,036 |
def on_disconnect(unused_client, obj, rc):
"""Paho callback for when a device disconnects."""
obj.connected = False
obj.led.off()
print('on_disconnect', error_str(rc))
| 5,345,037 |
def _get_pyo_codes(fmt='', dtype='int16', file_out=''):
"""Convert file and data formats to int codes, e.g., wav int16 -> (0, 0).
"""
if not fmt:
dot_ext = os.path.splitext(file_out)[1]
fmt = dot_ext.lower().strip('.')
if fmt in pyo_formats:
file_fmt = pyo_formats[fmt]
else:
msg = 'format `{0}` not supported'.format(file_out)
raise PyoFormatException(msg)
if fmt in ['sd2', 'flac']:
ok_dfmt = {'int16': 0, 'int24': 1}
else:
ok_dfmt = pyo_dtype
if dtype in ok_dfmt:
data_fmt = pyo_dtype[dtype]
else:
msg = 'data format `{0}` not supported for `{1}`'.format(
dtype, file_out)
raise PyoFormatException(msg)
return file_fmt, data_fmt
| 5,345,038 |
def catch_gpu_memory_error( f ):
"""
Decorator that calls the function `f` and catches any GPU memory
error, during the execution of f.
If a memory error occurs, this decorator prints a corresponding message
and aborts the simulation (using MPI abort if needed)
"""
# Redefine the original function by calling it within a try/except
def g(*args, **kwargs):
try:
return f(*args, **kwargs)
except OutOfMemoryError as e:
handle_cuda_memory_error( e, f.__name__ )
# Decorator: return the new function
return(g)
| 5,345,039 |
def horizontal_tail_planform_raymer(horizontal_stabilizer, wing, l_ht,c_ht):
"""Adjusts reference area before calling generic wing planform function to compute wing planform values.
Assumptions:
None
Source:
Raymer
Inputs:
horizontal_stabilizer [SUAVE data structure]
wing [SUAVE data structure] (should be the main wing)
l_ht [m] length from wing mean aerodynamic chord (MAC) to horizontal stabilizer MAC
c_ht [-] horizontal tail coefficient (Raymer specific) .5 = Sailplane, .5 = homebuilt,
.7 = GA single engine, .8 = GA twin engine .5 = agricultural, .9 = twin turboprop,
.7 = flying boat, .7 = jet trainer, .4 = jet fighter, 1. = military cargo/bomber,
1. = jet transport
Outputs:
horizontal_stabilier.areas.reference [m^2]
Other changes to horizontal_stabilizer (see wing_planform)
Properties Used:
N/A
"""
horizontal_stabilizer.areas.reference = wing.chords.mean_aerodynamic*c_ht*wing.areas.reference/l_ht
wing_planform(horizontal_stabilizer)
return 0
| 5,345,040 |
def inherit_check(role_s, permission):
"""
Check if the role class has the following
permission in inherit mode.
"""
from improved_permissions.roles import ALLOW_MODE
role = get_roleclass(role_s)
if role.inherit is True:
if role.get_inherit_mode() == ALLOW_MODE:
return True if permission in role.inherit_allow else False
return False if permission in role.inherit_deny else True
return False
| 5,345,041 |
def giveHint(indexValue, myBoard):
"""Return a random matching card given the index of a card
and a game board"""
validMatches = []
card = myBoard[indexValue]
for c in myBoard:
if (card[0] == c[0]) and (myBoard.index(c) != indexValue):
validMatches.append(myBoard.index(c))
return random.choice(validMatches)
| 5,345,042 |
async def make_getmatch_embed(data):
"""Generate the embed description and other components for a getmatch() command.
As with its parent, remember that this currently does not support non team-vs.
`data` is expected to be the output of `get_individual_match_data()`.
The following `dict` is returned:
```
{
"embed_description": str,
"footer": str,
"embed_color": int (as color hex),
}
```
"""
scores = data["individual_scores"]
team_1_score_strings = []
team_2_score_strings = []
for individual_score in scores:
#at first i thought doing this would make the actual score_string more readable
#now i'm not very sure
player_name = individual_score["user_name"]
score_val = individual_score["score"]
maxcombo = individual_score["combo"]
accuracy = individual_score["accuracy"]
count_300 = individual_score["hits"]["300_count"]
count_100 = individual_score["hits"]["100_count"]
count_50 = individual_score["hits"]["50_count"]
count_miss = individual_score["hits"]["miss_count"]
accuracy = '{:.2%}'.format(accuracy)
score_val = "{:,}".format(score_val)
maxcombo = "{:,}".format(maxcombo)
score_string = (f'**{player_name}** - {score_val} ({maxcombo}x) ({accuracy} - {count_300}/{count_100}/{count_50}/{count_miss})')
team_1_score_strings.append(score_string) if individual_score["team"] == "1" else team_2_score_strings.append(score_string)
team_1_score_string = "\n".join(team_1_score_strings)
team_2_score_string = "\n".join(team_2_score_strings)
winner_string = {
"Blue": f"Blue team wins by {'{:,}'.format(data['score_difference'])}!",
"Red": f"Red team wins by {'{:,}'.format(data['score_difference'])}!",
"Tie": "Tie!"}
winner_color = {
"Blue": 0x0000FF,
"Red": 0xFF0000,
"Tie": 0x808080}
embed_desc = (
f'**{winner_string[data["winner"]]}**\n\n'
f'__Blue Team__ ({"{:,}".format(data["team_1_score"])} points, {"{:,}".format(data["team_1_score_avg"])} average)\n'
f'{team_1_score_string}\n\n'
f'__Red Team__ ({"{:,}".format(data["team_2_score"])} points, {"{:,}".format(data["team_2_score_avg"])} average)\n'
f'{team_2_score_string}')
#footer stuff
scoring_types = {
'0': 'Score',
'1': 'Accuracy',
'2': 'Combo',
'3': 'Score v2'}
team_types = {
'0': 'Head-to-head',
'1': 'Tag Co-op',
'2': 'Team VS',
'3': 'Tag Team VS'}
play_modes = {
'0': 'osu!',
'1': 'Taiko',
'2': 'CTB',
'3': 'osu!mania'}
embed_footer = (f'Played at {data["start_time"]} UTC | '
f'Win condition: {scoring_types[data["scoring_type"]]} | '
f'{team_types[data["team_type"]]} | '
f'{play_modes[data["play_mode"]]}')
final = {
"embed_description": embed_desc,
"footer": embed_footer,
"embed_color": winner_color[data["winner"]],
}
return final
| 5,345,043 |
def allreduceCommunicate_op(node, comm):
"""Make a new instance of AllReduceCommunicateOp and call the instance.
Parameters:
----
node : Node
The Node to do allreduce
Returns:
----
A new Node instance created by Op.
"""
return AllReduceCommunicateOp(node, comm)
| 5,345,044 |
def _micronaut_library(name,
srcs = [],
deps = [],
proto_deps = [],
runtime_deps = [],
data = [],
templates = [],
exports = [],
**kwargs):
""" Wraps a regular JDK library with injected Micronaut dependencies and plugins. """
_jdk_library(
name = name,
srcs = srcs,
deps = _dedupe_deps(deps + INJECTED_MICRONAUT_DEPS + [("%s-%s" % (
p, JAVAPROTO_POSTFIX_
)) for p in proto_deps] + [
("%s-java" % t) for t in templates
] + [
("%s-java_jcompiled" % t) for t in templates
]),
runtime_deps = _dedupe_deps(runtime_deps + INJECTED_MICRONAUT_RUNTIME_DEPS + [
("%s-java" % t) for t in templates
] + [
("%s-java_jcompiled" % t) for t in templates
]),
exports = _dedupe_deps([("%s-%s" % (
p, JAVAPROTO_POSTFIX_
)) for p in proto_deps] + [
("%s-java" % t) for t in templates
] + [
("%s-java_jcompiled" % t) for t in templates
] + exports),
data = data,
**kwargs
)
| 5,345,045 |
def test_list_all(fake_client):
"""pye
Test organization class 'list_all()' Method
"""
org = Organizations(fake_client, "https://api.buildkite.com/v2/")
org.list_all()
fake_client.get.assert_called_with(
org.path, query_params={"page": 0}, with_pagination=False
)
| 5,345,046 |
def compute_scales(work_dir=".", downscaling_method="average", options={}):
"""Generate lower scales following an input info file"""
accessor = neuroglancer_scripts.accessor.get_accessor_for_url(
work_dir, options
)
pyramid_io = precomputed_io.get_IO_for_existing_dataset(
accessor, encoder_options=options
)
downscaler = neuroglancer_scripts.downscaling.get_downscaler(
downscaling_method, pyramid_io.info, options
)
neuroglancer_scripts.dyadic_pyramid.compute_dyadic_scales(
pyramid_io, downscaler
)
| 5,345,047 |
def reduce_fn(state, values):
"""tf.data.Dataset-friendly implementation of mean and variance."""
k, n, ex, ex2 = state
# If this is the first iteration, we pick the first value to be 'k',
# which helps with precision - we assume that k is close to an average
# value and calculate mean and variance with respect to that.
k = tf.cond(tf.equal(n, 0), lambda: values[0], lambda: k)
sum_v = tf.reduce_sum(values, axis=0)
sum_v2 = tf.reduce_sum(tf.square(values), axis=0)
ones = tf.ones_like(values, dtype=tf.int32)
batch_size = tf.reduce_sum(ones, axis=0)
batch_size_f = tf.cast(batch_size, tf.float32)
ex = 0 + sum_v - tf.multiply(batch_size_f, k)
ex2 = 0 + sum_v2 + tf.multiply(
batch_size_f, (tf.square(k) -
tf.multiply(tf.multiply(2.0, k), sum_v)))
return (k, n + batch_size, ex, ex2)
| 5,345,048 |
def winged_edge(
face_features: np.ndarray,
edge_features: np.ndarray,
coedge_features: np.ndarray,
coedge_to_next: np.ndarray,
coedge_to_mate: np.ndarray,
coedge_to_face: np.ndarray,
coedge_to_edge: np.ndarray,
):
"""Create graph according to the `winged edge` configuration."""
coedge_to_prev = np.zeros_like(coedge_to_next)
for (from_ix, to_ix) in enumerate(coedge_to_next):
coedge_to_prev[to_ix] = from_ix
faces_num = face_features.shape[0]
edges_num = edge_features.shape[0]
coedges_num = coedge_features.shape[0]
face_to_node = np.arange(faces_num)
edge_to_node = np.arange(edges_num) + faces_num
coedge_to_node = np.arange(coedges_num) + (faces_num + edges_num)
edges = []
# Faces
_f(coedge_to_face, coedge_to_node, face_to_node, edges)
_mf(coedge_to_mate, coedge_to_node, coedge_to_face, face_to_node, edges)
# Edges
_e(coedge_to_edge, coedge_to_node, edge_to_node, edges)
_ne(coedge_to_next, coedge_to_node, coedge_to_edge, edges)
_pe(coedge_to_prev, coedge_to_node, coedge_to_edge, edges)
_mne(coedge_to_next, coedge_to_node, coedge_to_mate, coedge_to_edge, edges)
_mpe(coedge_to_prev, coedge_to_node, coedge_to_mate, coedge_to_edge, edges)
# CoEdges
_i(coedges_num, coedge_to_node, edges)
_m(coedge_to_mate, coedge_to_node, edges)
_n(coedge_to_next, coedge_to_node, edges)
_p(coedge_to_prev, coedge_to_node, edges)
_mn(coedge_to_next, coedge_to_node, coedge_to_mate, edges)
_mp(coedge_to_prev, coedge_to_node, coedge_to_mate, edges)
return _create_graph(face_features, edge_features, coedge_features, edges)
| 5,345,049 |
def dollar_format(dollars):
"""
Args:
dollars (any): A dollar value (Any value that can be turned into a float can be used - int, Decimal, str, etc.)
Returns:
str: The formatted string
"""
decimal_dollars = Decimal(dollars)
if decimal_dollars < 0:
return "-${:,.2f}".format(-decimal_dollars)
else:
return "${:,.2f}".format(decimal_dollars)
| 5,345,050 |
def test_delete_training_view_with_deployment(test_app, create_deployment):
"""
Tests deleting a training view where a model has been deployed
"""
APP.dependency_overrides[crud.get_db] = lambda: (yield create_deployment) # Give the "server" the same db session
assert len(create_deployment.query(TrainingView).all()) == 1, 'setup'
assert len(create_deployment.query(TrainingViewKey).all()) == 2, 'setup'
assert len(create_deployment.query(TrainingSet).all()) == 1, 'setup'
assert len(create_deployment.query(TrainingSetFeature).all()) == 1, 'setup'
response = test_app.delete(ROUTE, params=name, auth=basic_auth)
logger.info(f'status: {response.status_code}, -- message: {response.json()}')
assert len(create_deployment.query(TrainingView).all()) == 1, 'should still be there'
assert len(create_deployment.query(TrainingViewKey).all()) == 2, 'should still be there'
assert len(create_deployment.query(TrainingSet).all()) == 1, 'should still be there'
assert len(create_deployment.query(TrainingSetFeature).all()) == 1, 'should still be there'
# postgres has case sensitivity issues that seem incompatible with Splice for testing
# assert not DatabaseFunctions.table_exists('test_fs', '"FSET_1"', create_fset_with_features.get_bind()), \
# 'Table should be dropped!'
| 5,345,051 |
def check_aea_project(
f: Callable, check_aea_version: bool = True, check_finger_prints: bool = False
) -> Callable:
"""
Check the consistency of the project as a decorator.
- try to load agent configuration file
- iterate over all the agent packages and check for consistency.
"""
def wrapper(*args: Any, **kwargs: Any) -> Callable:
_check_aea_project(
args,
check_aea_version=check_aea_version,
check_finger_prints=check_finger_prints,
)
return f(*args, **kwargs)
return update_wrapper(wrapper, f)
| 5,345,052 |
def solve_scene(kb_db_name, obj_file_path):
"""
Solve manipulation for the target object in the scene using analogy.
Args:
kb_db_name(str): The knowledge base database file name.
obj_file_path(str): File path to the .obj file.
"""
# create vpython scene that is used for graphical representation of a scene
# for the user
vpython_scene = vpython.canvas(
title='',
width=800,
height=600,
center=vpython.vector(0, 0, 0),
background=vpython.color.black)
# Draw XYZ axis in the scene
vpython_drawings.draw_xyz_arrows(300.0)
scene = file_parsers.read_obj_file(obj_file_path)
# collision detection for each mesh in the scene
min_distance = 3
for mesh_1 in scene.values():
for mesh_2 in scene.values():
if mesh_1.name != mesh_2.name:
aabb_collision = aabb_col.aabb_intersect(
mesh_1, mesh_2, min_distance=min_distance)
if aabb_collision:
for surface in mesh_1.surfaces:
intersect = aabb_col.aabb_intersect_vertex(
mesh_2, surface.collider, min_distance=min_distance)
if intersect:
surface.collided_objects[mesh_2.name] = True
surface.collision = True
mesh_1.collision = True
mesh_1.collided_objects[mesh_2.name] = True
for side, surfaces in mesh_1.aabb.closest_surfaces.items():
counter = 0
for surface in surfaces:
if surface.collision:
counter += 1
if counter == len(surfaces):
mesh_1.aabb.collided_sides[side] = 2
elif counter > 0 and counter < len(surfaces):
mesh_1.aabb.collided_sides[side] = 1
# vpython_drawings.draw_colliders(mesh_list=scene.values())
vpython_drawings.draw_aabb_colliders(mesh_list=scene.values())
# vpython_drawings.draw_mesh(mesh_list=scene.values())
vpython_drawings.draw_aabb(mesh_list=scene.values(), opacity=0.4)
# select target object
picked_vpython_obj = user_inputs.select_object(vpython_scene)
picked_obj = scene[picked_vpython_obj.name[:-5]]
# get aabbs from KB
db = sqlitedb.sqlitedb(name=kb_db_name)
db_aabbs = db.select_all_aabbs()
# rebuild aabb from db as an AABB object
aabbs = {}
for db_aabb in db_aabbs:
# get positions of manipulation points and vector forces from DB
pos = db.select_position_id(db_aabb[2])
push_point = db.select_position_id(
int(db.select_push_point_id(int(db_aabb[3]))[1]))
push_vec = db.select_push_vec_id(int(db_aabb[4]))
pull_point = db.select_position_id(
int(db.select_pull_point_id(int(db_aabb[5]))[1]))
pull_vec = db.select_pull_vec_id(int(db_aabb[6]))
spatula_point = db.select_position_id(
int(db.select_spatula_point_id(int(db_aabb[7]))[1]))
spatula_vec = db.select_spatula_vec_id(int(db_aabb[8]))
# Create AABB object and assign collided sides
aabb = AABB([pos[1], pos[2], pos[3]],
[db_aabb[9], db_aabb[10], db_aabb[11]])
aabb.collided_sides['top'] = db_aabb[12]
aabb.collided_sides['bottom'] = db_aabb[13]
aabb.collided_sides['front'] = db_aabb[14]
aabb.collided_sides['back'] = db_aabb[15]
aabb.collided_sides['right'] = db_aabb[16]
aabb.collided_sides['left'] = db_aabb[17]
# assign manipulation points and force vectors for the AABB object
if push_point[1] is not None:
aabb.manipulation_points['push'] = [
float(push_point[1]),
float(push_point[2]),
float(push_point[3])
]
aabb.manipulation_vectors['push'] = [
int(push_vec[1]),
int(push_vec[2]),
int(push_vec[3])
]
else:
aabb.manipulation_points['push'] = None
aabb.manipulation_vectors['push'] = None
if pull_point[1] is not None:
aabb.manipulation_points['pull'] = [
float(pull_point[1]),
float(pull_point[2]),
float(pull_point[3])
]
aabb.manipulation_vectors['pull'] = [
int(pull_vec[1]),
int(pull_vec[2]),
int(pull_vec[3])
]
else:
aabb.manipulation_points['pull'] = None
aabb.manipulation_vectors['pull'] = None
if spatula_point[1] is not None:
aabb.manipulation_points['spatula'] = [
float(spatula_point[1]),
float(spatula_point[2]),
float(spatula_point[3])
]
aabb.manipulation_vectors['spatula'] = [
int(spatula_vec[1]),
int(spatula_vec[2]),
int(spatula_vec[3])
]
else:
aabb.manipulation_points['spatula'] = None
aabb.manipulation_vectors['spatula'] = None
aabbs[db_aabb[0]] = aabb
# get all mappings and their scores. Sort them based on highest score
analogy_mapping = Mapping()
mappings_scores = []
for aabb_id, aabb in aabbs.items():
new_aabb_scores = analogy_mapping.get_mappings_score(
target_aabb=picked_obj.aabb, source_aabb=aabb)
# save only top 3 rotation sequences based on highest score
top_3_scores = heapq.nlargest(
3, new_aabb_scores, key=operator.itemgetter(0))
# The result is saved as tuple in a form
# (aabb_id, top score from all 3, list of best 3 rotation sequences with their scores)
mappings_scores.append((aabb_id, top_3_scores[0][0], top_3_scores))
# sort the mapping scores based on the top scores
mappings_scores = sorted(
mappings_scores, key=operator.itemgetter(1), reverse=True)
# print out info about best mapping
print(':' * 120)
for aabb_mapping in mappings_scores:
print('=' * 120)
print('aabb id:', aabb_mapping[0], 'scene:',
db.select_aabb_id(aabb_mapping[0])[1])
print('max score for the AABB:', aabb_mapping[1])
for score in aabb_mapping[2]:
print('-' * 120)
print('score:', score[0], '\nsequence:', score[1], '\nmapping:',
analogy_mapping.all_permutations[score[1]])
# rotate vectors based on the permutation sequence
best_sequence = mappings_scores[0][2][0][1]
rotated_manipulation_vec = {}
for operation, vec in aabbs[mappings_scores[0]
[0]].manipulation_vectors.items():
if vec is not None:
vpython_vec = vpython.vec(vec[0], vec[1], vec[2])
# best_sequence not reversed because we want to rotate the manipulation vectors from
# source scenario to target one. Best sequence is from target to source.
# For example (x,y) means first transform y and then x.
# Since we want to go backwards it is already in the correct order.
for rotation in best_sequence:
if rotation == 'x':
vpython_vec = vpython.rotate(
vpython_vec,
angle=vpython.radians(90),
axis=vpython.vec(1, 0, 0))
elif rotation == 'y':
vpython_vec = vpython.rotate(
vpython_vec,
angle=vpython.radians(90),
axis=vpython.vec(0, 1, 0))
rotated_manipulation_vec[operation] = [
vpython_vec.x, vpython_vec.y, vpython_vec.z
]
else:
rotated_manipulation_vec[operation] = [None, None, None]
picked_obj.aabb.manipulation_vectors = rotated_manipulation_vec
# get dict that maps surfaces from target to source
# For example 'top':'left' top surface is going to be left to map to source
mapping_sides = analogy_mapping.all_permutations[best_sequence]
aabb_half_size = aabbs[mappings_scores[0][0]].half_size
aabb_pos = aabbs[mappings_scores[0][0]].pos
# determine x,y,z ratios for scaling factor that is applied
# for manipulation points positions. It is important to determine which
# rotation took place in order to determine correct scaling ratios.
x_ratio = 0
y_ratio = 0
z_ratio = 0
if (mapping_sides['top'] == 'top' or mapping_sides['top'] == 'bottom') and (
mapping_sides['front'] == 'front' or
mapping_sides['front'] == 'back'):
x_ratio = picked_obj.aabb.half_size[0] / aabb_half_size[0]
y_ratio = picked_obj.aabb.half_size[1] / aabb_half_size[1]
z_ratio = picked_obj.aabb.half_size[2] / aabb_half_size[2]
elif (mapping_sides['top'] == 'top' or mapping_sides['top'] == 'bottom'
) and (mapping_sides['front'] == 'right' or
mapping_sides['front'] == 'left'):
x_ratio = picked_obj.aabb.half_size[2] / aabb_half_size[0]
y_ratio = picked_obj.aabb.half_size[1] / aabb_half_size[1]
z_ratio = picked_obj.aabb.half_size[0] / aabb_half_size[2]
elif (mapping_sides['top'] == 'left' or mapping_sides['top'] == 'right'
) and (mapping_sides['front'] == 'front' or
mapping_sides['front'] == 'back'):
x_ratio = picked_obj.aabb.half_size[1] / aabb_half_size[0]
y_ratio = picked_obj.aabb.half_size[0] / aabb_half_size[1]
z_ratio = picked_obj.aabb.half_size[2] / aabb_half_size[2]
elif (mapping_sides['top'] == 'left' or mapping_sides['top'] == 'right'
) and (mapping_sides['front'] == 'top' or
mapping_sides['front'] == 'bottom'):
x_ratio = picked_obj.aabb.half_size[1] / aabb_half_size[0]
y_ratio = picked_obj.aabb.half_size[2] / aabb_half_size[1]
z_ratio = picked_obj.aabb.half_size[0] / aabb_half_size[2]
elif (mapping_sides['top'] == 'front' or mapping_sides['top'] == 'back'
) and (mapping_sides['front'] == 'bottom' or
mapping_sides['front'] == 'top'):
x_ratio = picked_obj.aabb.half_size[0] / aabb_half_size[0]
y_ratio = picked_obj.aabb.half_size[2] / aabb_half_size[1]
z_ratio = picked_obj.aabb.half_size[1] / aabb_half_size[2]
elif (mapping_sides['top'] == 'front' or mapping_sides['top'] == 'back'
) and (mapping_sides['front'] == 'right' or
mapping_sides['front'] == 'left'):
x_ratio = picked_obj.aabb.half_size[2] / aabb_half_size[0]
y_ratio = picked_obj.aabb.half_size[0] / aabb_half_size[1]
z_ratio = picked_obj.aabb.half_size[1] / aabb_half_size[2]
else:
raise ValueError
rotated_manipulation_points = {}
# iterate through all manipulation points and rotate them based on the best sequence
for operation, pos in aabbs[mappings_scores[0]
[0]].manipulation_points.items():
if pos is not None:
# calculate relative position from manipulation point to centre of AABB
relative_pos = [
pos[0] - aabb_pos[0], pos[1] - aabb_pos[1], pos[2] - aabb_pos[2]
]
# Scale the position to match the size of our target AABB
scaled_relative_pos = [
relative_pos[0] * x_ratio, relative_pos[1] * y_ratio,
relative_pos[2] * z_ratio
]
# create vpython vec that is used in rotation method
vpython_vec = vpython.vec(scaled_relative_pos[0],
scaled_relative_pos[1],
scaled_relative_pos[2])
# rotate the manipulation points positions from source to target scene
for rotation in best_sequence:
if rotation == 'x':
vpython_vec = vpython.rotate(
vpython_vec,
angle=vpython.radians(90),
axis=vpython.vec(1, 0, 0))
elif rotation == 'y':
vpython_vec = vpython.rotate(
vpython_vec,
angle=vpython.radians(90),
axis=vpython.vec(0, 1, 0))
# Shift the manipulation point position from relative pos to absolute pos in the scene
scaled__rotated_abs_pos = [
vpython_vec.x + picked_obj.aabb.pos[0],
vpython_vec.y + picked_obj.aabb.pos[1],
vpython_vec.z + picked_obj.aabb.pos[2]
]
rotated_manipulation_points[operation] = scaled__rotated_abs_pos
# Draw rotated manipulation points and vectors on the screen
radius = stat.mean(picked_obj.aabb.half_size) / 10
if operation == 'push':
color = vpython.color.cyan
elif operation == 'pull':
color = vpython.color.purple
else:
color = vpython.color.orange
vpython_drawings.draw_point(
rotated_manipulation_points[operation], radius, color=color)
vector_length = stat.mean(picked_obj.aabb.half_size)
vpython_drawings.draw_arrow(
rotated_manipulation_points[operation],
picked_obj.aabb.manipulation_vectors[operation],
vector_length,
color=color)
else:
rotated_manipulation_points[operation] = [None, None, None]
# assig the calculated manipulation points to the target AABB
picked_obj.aabb.manipulation_points = rotated_manipulation_points
# save it to the DB if it is correct.
correct_result = input(
'Are these manipulation points and vectors correct? Yes/No: ')
if correct_result.lower() == 'y' or correct_result.lower() == 'yes':
file_path_list = obj_file_path.split('/')
file_name_obj = file_path_list[-1]
file_name_list = file_name_obj.split('.')
scene_name = file_name_list[0]
db.save_scene(scene, scene_name, picked_obj)
print('Successfully Saved in knowledge base DB.')
else:
print('This is not going to be saved in the knowledge base DB.')
print('Done')
# close DB
db.conn.close()
| 5,345,053 |
def sftp():
"""
Fixture allowing setup of a mocked remote SFTP session.
Yields a 3-tuple of: Transfer() object, SFTPClient object, and mocked OS
module.
For many/most tests which only want the Transfer and/or SFTPClient objects,
see `sftp_objs` and `transfer` which wrap this fixture.
"""
mock = MockSFTP(autostart=False)
client, mock_os = mock.start()
transfer = Transfer(Connection("host"))
yield transfer, client, mock_os
# TODO: old mock_sftp() lacked any 'stop'...why? feels bad man
| 5,345,054 |
async def test_bike_is_in_use(rental_manager, random_rental, random_bike, random_bike_factory, bike_connection_manager):
"""Assert that you can check if a bike is in use."""
assert rental_manager.is_in_use(random_bike)
assert not rental_manager.is_in_use(await random_bike_factory(bike_connection_manager))
| 5,345,055 |
def find_closest_cross(wire1_path, wire2_path):
"""
Compare the coordinates of two wire paths to find the crossing point
closest (Manhattan Distance) to the origin (0,0).
Returns a list of crossing points, the closest crossing point and its distance to the start point
"""
best_result = -1
crossing_list = []
for i in range(len(wire1_path)):
if wire1_path[i] in wire2_path and wire1_path[i] != [0,0]:
test_result = abs(wire1_path[i][0]) + abs(wire1_path[i][1])
crossing_list.append(wire1_path[i])
if best_result == -1:
best_cross = wire1_path[i][:]
best_result = test_result
elif test_result < best_result:
best_cross = wire1_path[i][:]
best_result = test_result
return crossing_list, best_cross, best_result
| 5,345,056 |
def test_solution(data: str) -> None:
"""Test the solution"""
solution = Day10()
solution.set_input_data(data.split("\n"))
assert solution.part_one() == 26397
assert solution.part_two() == 288957
| 5,345,057 |
async def check_is_user_exist(user_collection: UserCollection, test_data: dict):
"""
Check that checking for an existing user is correct.
:param user_collection: MongoDB collection.
:type user_collection: UserCollection
:param test_data: Database test data.
:type test_data: dict
"""
data_setup, data, expected_data = parse_test_sample(test_data)
await setup_database(user_collection, data_setup)
is_user_exist = await user_collection.is_user_exist(**data)
assert_massage = "The saved and found document does not match, should be same."
assert is_user_exist == expected_data, assert_massage
| 5,345,058 |
def add_signature_source(service, **_):
"""
Add a signature source for a given service
Variables:
service => Service to which we want to add the source to
Arguments:
None
Data Block:
{
"uri": "http://somesite/file_to_get", # URI to fetch for parsing the rules
"name": "signature_file.yar", # Name of the file we will parse the rules as
"username": null, # Username used to get to the URI
"password": null, # Password used to get to the URI
"header": { # Header sent during the request to the URI
"X_TOKEN": "SOME RANDOM TOKEN" # Exemple of header
},
"private_key": null, # Private key used to get to the URI
"pattern": "^*.yar$" # Regex pattern use to get appropriate files from the URI
}
Result example:
{"success": True/False} # if the operation succeeded of not
"""
try:
data = request.json
except (ValueError, KeyError):
return make_api_response({"success": False},
err="Invalid source object data",
status_code=400)
# Ensure data source doesn't have spaces in name
data['name'] = re.sub('[^0-9a-zA-Z_]+', '', data['name'].replace(" ", "_"))
# Ensure private_key (if any) ends with a \n
if data.get('private_key', None) and not data['private_key'].endswith("\n"):
data['private_key'] += "\n"
service_data = STORAGE.get_service_with_delta(service, as_obj=False)
if not service_data.get('update_config', {}).get('generates_signatures', False):
return make_api_response({"success": False},
err="This service does not generate alerts therefor "
"you cannot add a source to get the alerts from.",
status_code=400)
current_sources = service_data.get('update_config', {}).get('sources', [])
for source in current_sources:
if source['name'] == data['name']:
return make_api_response({"success": False},
err=f"Update source name already exist: {data['name']}",
status_code=400)
current_sources.append(data)
service_delta = STORAGE.service_delta.get(service, as_obj=False)
if service_delta.get('update_config') is None:
service_delta['update_config'] = {"sources": current_sources}
else:
service_delta['update_config']['sources'] = current_sources
_reset_service_updates(service)
# Save the signature
success = STORAGE.service_delta.save(service, service_delta)
if success:
service_event_sender.send(data['name'], {
'operation': Operation.Modified,
'name': data['name']
})
return make_api_response({"success": success})
| 5,345,059 |
def edit_screen_item(self, request, form):
""" Edit a screen. """
layout = ManageScreensLayout(self, request)
if form.submitted(request):
form.update_model(self)
request.message(_('Screen modified.'), 'success')
request.app.pages_cache.flush()
return redirect(layout.manage_model_link)
if not form.errors:
form.apply_model(self)
return {
'layout': layout,
'form': form,
'title': _(
"Screen ${number}",
mapping={'number': self.number}
),
'subtitle': _('Edit screen'),
'cancel': layout.manage_model_link
}
| 5,345,060 |
def get_xyz_t():
"""
CIELAB to XYZ の逆関数の中の値を
XYZ のぞれぞれについて求める。
"""
c, l, h = symbols('c, l, h', real=True)
xt = (l + 16) / 116 + (c * cos(h)) / 500
yt = (l + 16) / 116
zt = (l + 16) / 116 - (c * sin(h)) / 200
xyz_t = [xt, yt, zt]
return xyz_t, c, l, h
| 5,345,061 |
async def home():
"""
Home page, welcome
Returns:
Rendered template of homepage
"""
return await render_template('home.html')
| 5,345,062 |
def compute_inverse_interpolation_img(weights, indices, img, b, h_i, w_i):
"""
weights: [b, h*w]
indices: [b, h*w]
img: [b, h*w, a, b, c, ...]
"""
w0, w1, w2, w3 = weights
ff_idx, cf_idx, fc_idx, cc_idx = indices
k = len(img.size()) - len(w0.size())
img_0 = w0[(...,) + (None,) * k] * img
img_1 = w1[(...,) + (None,) * k] * img
img_2 = w2[(...,) + (None,) * k] * img
img_3 = w3[(...,) + (None,) * k] * img
img_out = torch.zeros(b, h_i * w_i, *img.shape[2:]).type_as(img)
ff_idx = torch.clamp(ff_idx, min=0, max=h_i * w_i - 1)
cf_idx = torch.clamp(cf_idx, min=0, max=h_i * w_i - 1)
fc_idx = torch.clamp(fc_idx, min=0, max=h_i * w_i - 1)
cc_idx = torch.clamp(cc_idx, min=0, max=h_i * w_i - 1)
img_out.scatter_add_(1, ff_idx[(...,) + (None,) * k].expand_as(img_0), img_0)
img_out.scatter_add_(1, cf_idx[(...,) + (None,) * k].expand_as(img_1), img_1)
img_out.scatter_add_(1, fc_idx[(...,) + (None,) * k].expand_as(img_2), img_2)
img_out.scatter_add_(1, cc_idx[(...,) + (None,) * k].expand_as(img_3), img_3)
return img_out
| 5,345,063 |
def layer_prepostprocess(previous_value,
x,
sequence,
dropout_rate,
norm_type,
depth,
epsilon,
default_name,
name=None,
dropout_broadcast_dims=None,
layer_collection=None):
"""Apply a sequence of functions to the input or output of a layer.
The sequence is specified as a string which may contain the following
characters:
a: add previous_value
n: apply normalization
d: apply dropout
z: zero add
For example, if sequence=="dna", then the output is
previous_value + normalize(dropout(x))
Args:
previous_value: A Tensor, to be added as a residual connection ('a')
x: A Tensor to be transformed.
sequence: a string.
dropout_rate: a float
norm_type: a string (see apply_norm())
depth: an integer (size of last dimension of x).
epsilon: a float (parameter for normalization)
default_name: a string
name: a string
dropout_broadcast_dims: an optional list of integers less than 3
specifying in which dimensions to broadcast the dropout decisions.
saves memory.
layer_collection: A tensorflow_kfac.LayerCollection. Only used by the
KFAC optimizer. Default is None.
Returns:
a Tensor
"""
with tf.variable_scope(name, default_name=default_name):
if sequence == "none":
return x
for c in sequence:
if c == "a":
x += previous_value
elif c == "z":
x = zero_add(previous_value, x)
elif c == "n":
x = apply_norm(
x, norm_type, depth, epsilon, layer_collection=layer_collection)
else:
assert c == "d", ("Unknown sequence step %s" % c)
x = dropout_with_broadcast_dims(
x, 1.0 - dropout_rate, broadcast_dims=dropout_broadcast_dims)
return x
| 5,345,064 |
def build_norm_layer(cfg, num_channels, postfix=''):
""" Build normalization layer
Args:
Returns:
layer (fluid.dygrah.Layer): created norm layer
"""
assert isinstance(cfg, dict) and 'type' in cfg
cfg_ = cfg.copy()
layer_type = cfg_.pop('type')
if layer_type not in norm_cfg:
raise KeyError('Unrecognized norm type {}'.format(layer_type))
else:
abbr, norm_layer = norm_cfg[layer_type]
if norm_layer is None:
raise NotImplementedError
assert isinstance(postfix, (int, str))
name = abbr + str(postfix)
stop_gradient = cfg_.pop('stop_gradient', False)
cfg_.setdefault('epsilon', 1e-5)
layer = norm_layer(num_channels=num_channels, **cfg_)
# for param in layer.parameters():
# param.stop_gradient = stop_gradient
return name, layer
| 5,345,065 |
def get_split_cifar100_tasks(num_tasks, batch_size):
"""
Returns data loaders for all tasks of split CIFAR-100
:param num_tasks:
:param batch_size:
:return:
"""
datasets = {}
# convention: tasks starts from 1 not 0 !
# task_id = 1 (i.e., first task) => start_class = 0, end_class = 4
cifar_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor(),])
cifar_train = torchvision.datasets.CIFAR100('./data/', train=True, download=True, transform=cifar_transforms)
cifar_test = torchvision.datasets.CIFAR100('./data/', train=False, download=True, transform=cifar_transforms)
for task_id in range(1, num_tasks+1):
train_loader, test_loader = get_split_cifar100(task_id, batch_size, cifar_train, cifar_test)
datasets[task_id] = {'train': train_loader, 'test': test_loader}
return datasets
| 5,345,066 |
def _find_loose_date(date_string):
"""Look for four digit numbers in the string. If there's only one, return it."""
if re.search(r'digit', date_string):
# Might be something like "digitized 2010", which we want to avoid.
return None
# find all the (unique) four digit numbers in the date_string.
matches = set(re.findall(r'\b\d{4}\b', date_string))
if len(matches) != 1:
return None
year = list(matches)[0]
if is_valid_year(int(year)):
LOG.debug('Parsed %s from "%s" as a loose date.' % (year, date_string))
return (year, year)
| 5,345,067 |
def invoke(command_requested, timeout=DEFAULT_TIMEOUT):
"""
"""
p = subprocess.Popen(command_requested, shell=True, stdin=subprocess.PIPE, stdout=None, stderr=None)
p.stdin.close() # since we do not allow invoked processes to listen to stdin, we close stdin to the subprocess
try:
return_code = p.wait(timeout)
except TypeError:
# most likely this is a python version lower than 3.3
start = time.time()
while p.poll() is None and (time.time() - start) < timeout:
time.sleep(0.1) # nicer than a pass, which would cause a lot of CPU usage
return_code = p.poll()
if return_code is None:
return_code = -1
syslog.syslog('Invocation timed out1')
except subprocess.TimeoutExpired: # works on python < 3.3 because a known exception is caught first
return_code = -1
syslog.syslog('Invocation timed out')
# We are also interested in data sent to stdin. This isn't allowed, and may
# be interesting for forensics
# Beware, this code is a bit iffy. In fact, reading from stdin seems iffy
# to me.
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
stdin_lines = sys.stdin.readline()
else:
stdin_lines = []
return return_code, stdin_lines
| 5,345,068 |
def _cmd_dump(m, line):
"""Dump entries from the defaults files.
Syntax:
config dump [*|regex] [section="*|regex"] [ic="1"]
Examples:
config dump *
- dump the entire JSON config data structure.
config dump reg[.*] ic="1"
- dump variables that match the regular expression 'reg[.*]' ignoring case
config dump reg[.*] section="nt|posix"
- dumps variables from user.var in either the 'nt' or 'posix' section
that match the regular expression 'reg.*'
"""
myname = funcname(_cmd_dump)
logger.debug(f"{myname}: m={m}::m.groups()={m.groups()}::line={line}")
msg, varName, parameters, instance = _parseSubCommand(line)
if msg is not None:
print(f"{myname}: {msg}\n\n", _cmd_get.__doc__)
return
if varName == "*":
instance.dump()
return
ic = IGNORECASE if parameters.get('ic') == '1' else 0
section = _getSection(parameters)
try:
if section:
instance.dumpSection(section, varName, ic)
else:
instance.dumpDefault(varName, ic)
except Exception as err:
print(f"{myname} caught Exception: {err}")
| 5,345,069 |
def zip_addon(addon: str, addon_dir: str):
""" Zips 'addon' dir or '.py' file to 'addon.zip' if not yet zipped, then moves the archive to 'addon_dir'.
:param addon: Absolute or relative path to a directory to zip or a .zip file.
:param addon_dir: Path to Blender's addon directory to move the zipped archive to.
:return (bpy_module, zip_file) Tuple of strings - an importable module name, an addon zip file path.
"""
addon_path = Path(addon).resolve()
addon_basename = addon_path.name
# Check if addon is already zipped
already_zipped = False
if addon_basename.endswith(".zip"):
already_zipped = True
# Delete target addon dir if exists
if os.path.isdir(addon_dir):
shutil.rmtree(addon_dir)
os.mkdir(addon_dir)
print(f"Addon dir is - {os.path.realpath(addon_dir)}")
if not already_zipped: # Zip the addon
# Get bpy python module from addon file name
bpy_module = re.sub(".py", "", addon_basename)
# Create zip archive using the module name
zfile = Path(f"{bpy_module}.zip").resolve()
print(f"Future zip path is - {zfile}")
print(f"Zipping addon - {bpy_module}")
# Zip addon content
# -------------------
zf = zipfile.ZipFile(zfile, "w")
if addon_path.is_dir(): # Addon is a directory, zip hierarchy
cwd = os.getcwd()
temp_dir = Path(gettempdir(), "blender_addon_tester")
# Clean temp dir if already exists
if temp_dir.is_dir():
shutil.rmtree(temp_dir)
# Creating the addon under the temp dir with its hierarchy
shutil.copytree(addon_path, temp_dir.joinpath(addon_path.relative_to(addon_path.anchor)))
# Move to temp dir
os.chdir(temp_dir)
# Clear python cache
if os.path.isdir("__pycache__"):
shutil.rmtree("__pycache__")
# Write addon content into archive
for dirname, subdirs, files in os.walk(addon_path):
for filename in files:
filename = os.path.join(dirname, filename)
# Clean file
clean_file(filename)
# Write file into zip under its hierarchy
zf.write(filename, arcname=os.path.relpath(filename, addon_path.parent))
# Go back to start dir
os.chdir(cwd)
# Remove temp dir
shutil.rmtree(temp_dir)
else: # Addon is a file, zip only the file
# Clean file
#y = addon_path.as_posix()
y = addon_basename
#print(y)
clean_file(y)
# Write single addon file into zip
zf.write(y)
# End zip building
zf.close()
else: # Addon is already zipped, take it as it is
zfile = addon_path
print(f"Detected zip path is - {zfile}. No need to zip the addon beforehand.")
# Get bpy python module from zip file name
bpy_module = addon_basename.split(".zip")[0]
# Copy zipped addon with name extended by blender revision number
bl_revision = f"{bpy.app.version[0]}.{bpy.app.version[1]}"
bfile = f"{zfile.stem}_{bl_revision}.zip"
shutil.copy(zfile, bfile)
return bpy_module, bfile
| 5,345,070 |
def set_simulation_data(
state_energies, T_array, state1_index, state2_index
):
"""
Create and set SimulationData objects for a pair of specified states
"""
# Set default UnitData object
default_UnitData = UnitData(
kb=kB.value_in_unit(unit.kilojoule_per_mole/unit.kelvin),
energy_conversion=1,
length_conversion=1,
volume_conversion=1,
temperature_conversion=1,
pressure_conversion=1,
time_conversion=1,
energy_str='KJ/mol',
length_str='nm',
volume_str='nm^3',
temperature_str='K',
pressure_str='bar',
time_str='ps'
)
# State 1
sim_data1 = SimulationData()
sim_data1.observables = ObservableData(
potential_energy=state_energies[state1_index,:],
)
sim_data1.ensemble = EnsembleData(
ensemble='NVT',
energy=state_energies[state1_index,:],
temperature=T_array[state1_index]
)
sim_data1.units = default_UnitData
# State 2
sim_data2 = SimulationData()
sim_data2.observables = ObservableData(
potential_energy=state_energies[state2_index,:],
)
sim_data2.ensemble = EnsembleData(
ensemble='NVT',
energy=state_energies[state2_index,:],
temperature=T_array[state2_index]
)
sim_data2.units = default_UnitData
return sim_data1, sim_data2
| 5,345,071 |
def card_banlist_status(banlist_status):
"""Validate banlist status
Args:
banlist_status {str}: Banlist status
Raises:
exceptions.BanlistStatusInvalid: Banlist status must be banned,
limited, semi-limited or unlimited
"""
if not constants.BanlistStatus.is_valid_value(banlist_status):
raise exceptions.BanlistStatusInvalid()
| 5,345,072 |
def pfl(flist, num, reverse = False, end = "\n"):
"""Print formatted list, accepts list of floats, number of elements to
print and bool to print from the end of list."""
if reverse:
num = -num
[print("{:3.3f}".format(i), end = " ") for i in flist[num:]]
else:
[print("{:3.3f}".format(i), end = " ") for i in flist[:num]]
print(end, end = "")
| 5,345,073 |
def park2_euc(x):
""" Comutes the park2 function """
max_val = 5.925698
x1 = x[0]
x2 = x[1]
x3 = x[2]
x4 = x[3]
ret = (2.0/3.0) * np.exp(x1 + x2) - x4*np.sin(x3) + x3
return min(ret, max_val)
| 5,345,074 |
def num_compositions_jit(m, n):
"""
Numba jit version of `num_compositions`. Return `0` if the outcome
exceeds the maximum value of `np.intp`.
"""
return comb_jit(n+m-1, m-1)
| 5,345,075 |
def _report_failed_challs(failed_achalls):
"""Notifies the user about failed challenges.
:param set failed_achalls: A set of failed
:class:`certbot.achallenges.AnnotatedChallenge`.
"""
problems = dict()
for achall in failed_achalls:
if achall.error:
problems.setdefault(achall.error.typ, []).append(achall)
reporter = zope.component.getUtility(interfaces.IReporter)
for achalls in six.itervalues(problems):
reporter.add_message(
_generate_failed_chall_msg(achalls), reporter.MEDIUM_PRIORITY)
| 5,345,076 |
def fake_get_vim_object(arg):
"""Stubs out the VMwareAPISession's get_vim_object method."""
return fake_vmware_api.FakeVim()
| 5,345,077 |
def get_version(*file_paths):
"""Retrieves the version from replicat_documents/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
| 5,345,078 |
def get_old_ids(title):
"""
Returns all the old ids of a particular site given the title of the
Wikipedia page
"""
raw_data = json.loads( readInDataFromURL("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvlimit=100000&titles=" + title) )
old_ids = dict() # initialize
for page_id, revisions in data['query']['pages'].items():
print(revisions)
# for revision in revisions:
# old_ids[revision.]
# try:
# for extlink in page['extlinks']:
# # print to the output file
# print('%s\t%s\t%s'%(page_id, name, extlink['*']), file=outputfile)
# except:
# if options.verbose:
# print('Page %s does not have any external links...'%name)
# print(data)
return old_ids
| 5,345,079 |
def max_expectation_under_constraint(f: np.ndarray, q: np.ndarray, c: float, eps: float = 1e-2,
display: bool = False) -> np.ndarray:
"""
Solve the following constrained optimisation problem:
max_p E_p[f] s.t. KL(q || p) <= c
:param f: an array of values f(x), np.array of size n
:param q: a discrete distribution q(x), np.array of size n
:param c: a threshold for the KL divergence between p and q.
:param eps: desired accuracy on the constraint
:param display: plot the function
:return: the argmax p*
"""
np.seterr(all="warn")
if np.all(q == 0):
q = np.ones(q.size) / q.size
x_plus = np.where(q > 0)
x_zero = np.where(q == 0)
p_star = np.zeros(q.shape)
lambda_, z = None, 0
q_p = q[x_plus]
f_p = f[x_plus]
f_star = np.amax(f)
theta = partial(theta_func, q_p=q_p, f_p=f_p, c=c)
d_theta_dl = partial(d_theta_dl_func, q_p=q_p, f_p=f_p)
if f_star > np.amax(f_p):
theta_star = theta_func(f_star, q_p=q_p, f_p=f_p, c=c)
if theta_star < 0:
lambda_ = f_star
z = 1 - np.exp(theta_star)
p_star[x_zero] = 1.0 * (f[x_zero] == np.amax(f[x_zero]))
p_star[x_zero] *= z / p_star[x_zero].sum()
if lambda_ is None:
if np.isclose(f_p, f_p[0]).all():
return q
else:
# Binary search seems slightly (10%) faster than newton
# lambda_ = binary_search(theta, eps, a=f_star, display=display)
lambda_ = newton_iteration(theta, d_theta_dl, eps, x0=f_star + 1, a=f_star, display=display)
# numba jit binary search is twice as fast as python version
# lambda_ = binary_search_theta(q_p=q_p, f_p=f_p, c=c, eps=eps, a=f_star)
beta = (1 - z) / (q_p @ (1 / (lambda_ - f_p)))
if beta == 0:
x_uni = np.where((q > 0) & (f == f_star))
if np.size(x_uni) > 0:
p_star[x_uni] = (1 - z) / np.size(x_uni)
else:
p_star[x_plus] = beta * q_p / (lambda_ - f_p)
return p_star
| 5,345,080 |
def payload_to_plain(payload=None):
"""
Converts the myADS results into the plain text message payload
:param payload: list of dicts
:return: plain text formatted payload
"""
formatted = u''
for p in payload:
formatted += u"{0} ({1}) \n".format(p['name'], p['query_url'].format(p['qtype'], p['id']))
for r in p['results']:
first_author = _get_first_author_formatted(r)
if type(r.get('title', '')) == list:
title = r.get('title')[0]
else:
title = r.get('title', '')
formatted += u"\"{0},\" {1} ({2})\n".format(title, first_author, r['bibcode'])
formatted += u"\n"
return formatted
| 5,345,081 |
async def parse_blog_post(blog_link):
"""
Given a blog post's URL, this function GETs it and pulls the body out.
We then analyze each word with NTLK and write some data into redis.
:param blog_link: String
:return: Raw text from the blog post w/html tags stripped out
"""
global blogs_scraped_counter
global word_count
print('Fetching raw text for {}'.format(blog_link))
soup = BeautifulSoup(r.get(blog_link).content,
features='html.parser')
post_text = soup.find(
'div', attrs={'class': parser_util.POST_BODY_CLASS}).get_text()
sanitized_post_text = parser_util.sanitize_blogpost(
post_text, translator=parser_util.sentence_translator)
print('Successfully parsed post.')
if parser_util.DEBUG_MODE:
print('\nSanitized blogpost:\n{clean}\n\nOriginal text:{orig}'.format(clean=sanitized_post_text,
orig=post_text))
print('Adding sentence information to postgres.')
for sentence in sanitized_post_text.split('.'):
# TODO: Implement word2vec and send actual vector instead of empty tuple
pg.update_sentence_details(sentence, blog_link, '{}')
for word in sentence.split(' '):
analyze_word(word.strip(), blog_link)
blogs_scraped_counter = blogs_scraped_counter + 1
| 5,345,082 |
def get_credentials_from_request(cloud, request):
"""
Extracts and returns the credentials from the current request for a given
cloud. Returns an empty dict if not available.
"""
if request.META.get('HTTP_CL_CREDENTIALS_ID'):
return get_credentials_by_id(
cloud, request, request.META.get('HTTP_CL_CREDENTIALS_ID'))
# In case a base class instance is sent in, attempt to retrieve the actual
# subclass.
if type(cloud) is models.Cloud:
cloud = models.Cloud.objects.get_subclass(slug=cloud.slug)
if isinstance(cloud, models.OpenStack):
os_username = request.META.get('HTTP_CL_OS_USERNAME')
os_password = request.META.get('HTTP_CL_OS_PASSWORD')
if os_username or os_password:
os_project_name = request.META.get('HTTP_CL_OS_PROJECT_NAME')
os_project_domain_name = request.META.get(
'HTTP_CL_OS_PROJECT_DOMAIN_NAME')
os_user_domain_name = request.META.get(
'HTTP_CL_OS_USER_DOMAIN_NAME')
d = {'os_username': os_username, 'os_password': os_password}
if os_project_name:
d['os_project_name'] = os_project_name
if os_project_domain_name:
d['os_project_domain_name'] = os_project_domain_name
if os_user_domain_name:
d['os_user_domain_name'] = os_user_domain_name
return d
else:
return {}
elif isinstance(cloud, models.AWS):
aws_access_key = request.META.get('HTTP_CL_AWS_ACCESS_KEY')
aws_secret_key = request.META.get('HTTP_CL_AWS_SECRET_KEY')
if aws_access_key or aws_secret_key:
return {'aws_access_key': aws_access_key,
'aws_secret_key': aws_secret_key,
}
else:
return {}
elif isinstance(cloud, models.Azure):
azure_subscription_id = request.META.get(
'HTTP_CL_AZURE_SUBSCRIPTION_ID')
azure_client_id = request.META.get('HTTP_CL_AZURE_CLIENT_ID')
azure_secret = request.META.get('HTTP_CL_AZURE_SECRET')
azure_tenant = request.META.get('HTTP_CL_AZURE_TENANT')
azure_resource_group = request.META.get('HTTP_CL_AZURE_RESOURCE_GROUP')
azure_storage_account = request.META.get(
'HTTP_CL_AZURE_STORAGE_ACCOUNT')
azure_vm_default_username = request.META.get(
'HTTP_CL_AZURE_VM_DEFAULT_USERNAME')
if (azure_subscription_id and azure_client_id and azure_secret and
azure_tenant):
return {'azure_subscription_id': azure_subscription_id,
'azure_client_id': azure_client_id,
'azure_secret': azure_secret,
'azure_tenant': azure_tenant,
'azure_resource_group': azure_resource_group,
'azure_storage_account': azure_storage_account,
'azure_vm_default_username': azure_vm_default_username
}
else:
return {}
elif isinstance(cloud, models.GCP):
gcp_credentials_json = request.META.get('HTTP_CL_GCP_CREDENTIALS_JSON')
if gcp_credentials_json:
return json.loads(gcp_credentials_json)
else:
return {}
else:
raise Exception("Unrecognised cloud provider: %s" % cloud)
| 5,345,083 |
def build_wvc_model(wvc_model_file, atm_lut_file, rdn_header_file, vis=40):
""" Build water vapor models.
Arguments:
wvc_model_file: str
Water vapor column model filename.
atm_lut_file: str
Atmosphere lookup table file.
rdn_header_file: str
Radiance header filename.
vis: float
Visibility in [km].
"""
if os.path.exists(wvc_model_file):
logger.info('Write WVC models to %s.' %wvc_model_file)
return
from AtmLUT import read_binary_metadata, get_interp_range
from ENVI import read_envi_header
from Spectra import get_closest_wave, resample_spectra
import json
# Get sensor wavelengths and fwhms.
header = read_envi_header(rdn_header_file)
sensor_waves = np.array(header['wavelength'])
sensor_fwhms = np.array(header['fwhm'])
# Read atmosphere look-up-table metadata.
metadata = read_binary_metadata(atm_lut_file+'.meta')
metadata['shape'] = tuple([int(v) for v in metadata['shape']])
atm_lut_WVC = np.array([float(v) for v in metadata['WVC']])
atm_lut_VIS = np.array([float(v) for v in metadata['VIS']])
atm_lut_VZA = np.array([float(v) for v in metadata['VZA']])
atm_lut_RAA = np.array([float(v) for v in metadata['RAA']])
atm_lut_WAVE = np.array([float(v) for v in metadata['WAVE']])
# vza index
vza_index = np.where(atm_lut_VZA==min(atm_lut_VZA))[0][-1]
# raa index
raa_index = np.where(atm_lut_RAA==min(atm_lut_RAA))[0][-1]
# Load atmosphere look-up-table.
atm_lut = np.memmap(atm_lut_file,
dtype='float32',
mode='r',
shape=metadata['shape']) # dimension=[RHO, WVC, VIS, VZA, RAA, WAVE]
# Subtract path radiance.
atm_lut_rdn = atm_lut[1,:,vza_index,raa_index,:] - atm_lut[0,:,vza_index,raa_index,:] # dimesion=[WVC, VIS, WAVE]
atm_lut.flush()
del atm_lut
# vis intepolation range
vis_dict = get_interp_range(atm_lut_VIS, vis)
# Do interpolation.
interp_rdn = np.zeros((len(atm_lut_WVC), len(atm_lut_WAVE)))
for vis_index, vis_delta in vis_dict.items():
interp_rdn += atm_lut_rdn[:,vis_index,:]*vis_delta
del atm_lut_rdn, vis_index, vis_delta
# Build WVC models.
model_waves = [(890, 940, 1000),
(1070, 1130, 1200)]
wvc_model = dict()
for waves in model_waves:
# Get model wavelengths.
wave_1, wave_2, wave_3 = waves
left_wave, left_band = get_closest_wave(sensor_waves, wave_1)
middle_wave, middle_band = get_closest_wave(sensor_waves, wave_2)
right_wave, right_band = get_closest_wave(sensor_waves, wave_3)
# Build the model.
if np.abs(left_wave-wave_1)<20 and np.abs(middle_wave-wave_2)<20 and np.abs(right_wave-wave_3)<20:
model = dict()
# bands
model['band'] = [int(left_band), int(middle_band), int(right_band)]
# wavelengths
model['wavelength'] = [left_wave, middle_wave, right_wave]
# weights
left_weight = (right_wave-middle_wave)/(right_wave-left_wave)
right_weight = (middle_wave-left_wave)/(right_wave-left_wave)
model['weight'] = [left_weight, right_weight]
# ratios and wvcs
resampled_rdn = resample_spectra(interp_rdn, atm_lut_WAVE,
sensor_waves[model['band']],
sensor_fwhms[model['band']])
ratio = resampled_rdn[:,1]/(left_weight*resampled_rdn[:,0]+right_weight*resampled_rdn[:,2])
index = np.argsort(ratio)
model['ratio'] = list(ratio[index])
model['wvc'] = list(atm_lut_WVC[index])
# Save model parameters.
wvc_model['WVC_Model_%d' %wave_2] = model
# Clear data.
del left_weight, right_weight, resampled_rdn, ratio, index, model
del interp_rdn
# Save WVC models to a json file.
with open(wvc_model_file, 'w') as fid:
json.dump(wvc_model, fid, indent=4)
logger.info('Write WVC models to %s.' %wvc_model_file)
| 5,345,084 |
def nCr(n, r):
"""n-choose-r.
Thanks for the "compact" solution go to:
http://stackoverflow.com/questions/2096573/counting-combinations-and-permutations-efficiently
"""
return reduce(
lambda x, y: x * y[0] / y[1],
izip(xrange(n - r + 1, n + 1),
xrange(1, r + 1)),
1)
| 5,345,085 |
def test_echo_substitutions_pass():
"""Format string interpolations should work."""
context = Context({
'key1': 'down the',
'echoMe': 'piping {key1} valleys wild'})
with patch_logger(
'pypyr.steps.echo', logging.NOTIFY) as mock_logger_notify:
pypyr.steps.echo.run_step(context)
mock_logger_notify.assert_called_once_with('piping down the valleys wild')
| 5,345,086 |
def check_python_version(conf, minver=None):
"""
Check if the python interpreter is found matching a given minimum version.
minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver.
If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR'
(eg. '2.4') of the actual python version found, and PYTHONDIR is
defined, pointing to the site-packages directory appropriate for
this python version, where modules/packages/extensions should be
installed.
"""
assert minver is None or isinstance(minver, tuple)
python = conf.env['PYTHON']
if not python:
conf.fatal('could not find the python executable')
# Get python version string
cmd = [python, "-c", "import sys\nfor x in sys.version_info: print(str(x))"]
debug('python: Running python command %r' % cmd)
proc = Utils.pproc.Popen(cmd, stdout=Utils.pproc.PIPE)
lines = proc.communicate()[0].split()
assert len(lines) == 5, "found %i lines, expected 5: %r" % (len(lines), lines)
pyver_tuple = (int(lines[0]), int(lines[1]), int(lines[2]), lines[3], int(lines[4]))
# compare python version with the minimum required
result = (minver is None) or (pyver_tuple >= minver)
if result:
# define useful environment variables
pyver = '.'.join([str(x) for x in pyver_tuple[:2]])
conf.env['PYTHON_VERSION'] = pyver
if 'PYTHONDIR' in conf.environ:
pydir = conf.environ['PYTHONDIR']
else:
if sys.platform == 'win32':
(python_LIBDEST, pydir) = \
_get_python_variables(python,
["get_config_var('LIBDEST')",
"get_python_lib(standard_lib=0, prefix=%r)" % conf.env['PREFIX']],
['from distutils.sysconfig import get_config_var, get_python_lib'])
else:
python_LIBDEST = None
(pydir,) = \
_get_python_variables(python,
["get_python_lib(standard_lib=0, prefix=%r)" % conf.env['PREFIX']],
['from distutils.sysconfig import get_config_var, get_python_lib'])
if python_LIBDEST is None:
if conf.env['LIBDIR']:
python_LIBDEST = os.path.join(conf.env['LIBDIR'], "python" + pyver)
else:
python_LIBDEST = os.path.join(conf.env['PREFIX'], "lib", "python" + pyver)
if hasattr(conf, 'define'): # conf.define is added by the C tool, so may not exist
conf.define('PYTHONDIR', pydir)
conf.env['PYTHONDIR'] = pydir
# Feedback
pyver_full = '.'.join(map(str, pyver_tuple[:3]))
if minver is None:
conf.check_message_custom('Python version', '', pyver_full)
else:
minver_str = '.'.join(map(str, minver))
conf.check_message('Python version', ">= %s" % minver_str, result, option=pyver_full)
if not result:
conf.fatal('The python version is too old (%r)' % pyver_full)
| 5,345,087 |
def bcFactory(name):
"""Factory for boundary condition items.
"""
from pythia.pyre.inventory import facility
from pylith.bc.DirichletTimeDependent import DirichletTimeDependent
return facility(name, family="boundary_condition", factory=DirichletTimeDependent)
| 5,345,088 |
def decode(value):
"""Decode utf-8 value to string.
Args:
value: String to decode
Returns:
result: decoded value
"""
# Initialize key variables
result = value
# Start decode
if value is not None:
if isinstance(value, bytes) is True:
result = value.decode('utf-8')
# Return
return result
| 5,345,089 |
def notebook_display_image_svg(listOfImageNames):
"""
Takes as input a list of images (e.g. png) and displays them in the current cell
"""
for imageName in listOfImageNames:
display(SVG(filename=imageName))
| 5,345,090 |
def sequence_rec_sqrt(x_init, iter, dtype=int):
"""
Mathematical sequence: x_n = x_{n-1} * sqrt(n)
:param x_init: initial values of the sequence
:param iter: iteration until the sequence should be evaluated
:param dtype: data type to cast to (either int of float)
:return: element at the given iteration and array of the whole sequence
"""
# exponential growth
def iter_function(x_seq, i, x_init):
return x_seq[i - 1, :] * np.sqrt(i + 1) # i+1 because sqrt(1) = 1
return sequence(x_init, iter, iter_function, dtype)
| 5,345,091 |
def convert_string_to_type(string_value, schema_type):
"""
Attempts to convert a string value into a schema type.
This method may evaluate code in order to do the conversion
and is therefore not safe!
"""
# assume that the value is a string unless otherwise stated.
if schema_type == "float":
evaluated_value = float(string_value)
elif schema_type == "int":
evaluated_value = int(string_value)
elif schema_type == "bool":
if string_value == "False":
evaluated_value = False
elif string_value == "True":
evaluated_value = True
else:
raise TankError("Invalid boolean value %s! Valid values are True and False" % string_value)
elif schema_type == "list":
evaluated_value = eval(string_value)
elif schema_type == "dict":
evaluated_value = eval(string_value)
else:
# assume string-like
evaluated_value = string_value
return evaluated_value
| 5,345,092 |
def plot3d(shower):
"""
Display a 3d plot of a shower
Parameters
----------
shower: list of position points (3-floats arrays)
"""
X = []
Y = []
Z = []
for points in shower:
X.append(points[0])
Y.append(points[1])
Z.append(points[2])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X, Y, Z)
plt.show()
| 5,345,093 |
def counter(path):
"""Get number of files by searching directory recursively"""
if not os.path.exists(path):
return 0
count = 0
for r, dirs, files in os.walk(path):
for dr in dirs:
count += len(glob.glob(os.path.join(r, dr + "/*")))
return count
| 5,345,094 |
def add_square_plot(x_start, x_stop, y_start, y_stop, ax, colour = 'k'):
"""Draw localization square around an area of interest, x_start etc are in pixels, so (0,0) is top left.
Inputs:
x_start | int | start of box
x_stop | int | etc.
y_start | int |
y_ stop | int |
ax | axes object | axes on which to draw
colour | string | colour of bounding box. Useful to change when plotting labels, and predictions from a model.
Returns:
box on figure
History:
2019/??/?? | MEG | Written
2020/04/20 | MEG | Document, copy to from small_plot_functions to LiCSAlert_aux_functions
"""
ax.plot((x_start, x_start), (y_start, y_stop), c= colour) # left hand side
ax.plot((x_start, x_stop), (y_stop, y_stop), c= colour) # bottom
ax.plot((x_stop, x_stop), (y_stop, y_start), c= colour) # righ hand side
ax.plot((x_stop, x_start), (y_start, y_start), c= colour) # top
| 5,345,095 |
def get_local_coordinate_system(time_dep_orientation: bool, time_dep_coordinates: bool):
"""
Get a local coordinate system.
Parameters
----------
time_dep_orientation :
If True, the coordinate system has a time dependent orientation.
time_dep_coordinates :
If True, the coordinate system has a time dependent coordinates.
Returns
-------
weldx.transformations.LocalCoordinateSystem:
A local coordinate system
"""
if not time_dep_coordinates:
coords = Q_(np.asarray([2.0, 5.0, 1.0]), "mm")
else:
coords = Q_(
np.asarray(
[[2.0, 5.0, 1.0], [1.0, -4.0, 1.2], [0.3, 4.4, 4.2], [1.1, 2.3, 0.2]]
),
"mm",
)
if not time_dep_orientation:
orientation = tf.rotation_matrix_z(np.pi / 3)
else:
orientation = tf.rotation_matrix_z(np.pi / 2 * np.array([1, 2, 3, 4]))
if not time_dep_orientation and not time_dep_coordinates:
return tf.LocalCoordinateSystem(orientation=orientation, coordinates=coords)
time = pd.DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04"])
return tf.LocalCoordinateSystem(
orientation=orientation, coordinates=coords, time=time
)
| 5,345,096 |
def start_debugging(address):
"""
Connects to debugpy in Maya, then starts the threads needed to
send and receive information from it
"""
log("Connecting to " + address[0] + ":" + str(address[1]))
# Create the socket used to communicate with debugpy
global debugpy_socket
debugpy_socket = socket.create_connection(address)
log("Successfully connected to Maya for debugging. Starting...")
# Start a thread that sends requests to debugpy
run_in_new_thread(debugpy_send_loop)
fstream = debugpy_socket.makefile()
while True:
try:
# Wait for the CONTENT_HEADER to show up,
# then get the length of the content following it
content_length = 0
while True:
header = fstream.readline()
if header:
header = header.strip()
if not header:
break
if header.startswith(CONTENT_HEADER):
content_length = int(header[len(CONTENT_HEADER):])
# Read the content of the response, then call the callback
if content_length > 0:
total_content = ""
while content_length > 0:
content = fstream.read(content_length)
content_length -= len(content)
total_content += content
if content_length == 0:
message = total_content
on_receive_from_debugpy(message)
except Exception as e:
# Problem with socket. Close it then return
log("Failure reading maya's debugpy output: \n" + str(e))
debugpy_socket.close()
break
| 5,345,097 |
def _get_tooltip(tooltip_col, gpd):
"""Show everything or columns in the list."""
if tooltip_col is not None:
tooltip = folium.GeoJsonTooltip(fields=tooltip_col)
else:
tooltip = tooltip_col
return tooltip
| 5,345,098 |
def encryption(message: str, key: int) -> str:
"""Return the ciphertext by xor the message with a repeating key"""
return b"".join(
[bytes([message[i] ^ key[i % len(key)]]) for i in range(len(message))]
)
| 5,345,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.