repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
python-astrodynamics/spacetrack | shovel/docs.py | gen | def gen(skipdirhtml=False):
"""Generate html and dirhtml output."""
docs_changelog = 'docs/changelog.rst'
check_git_unchanged(docs_changelog)
pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')
if not skipdirhtml:
sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG
sphinx_build['-b', 'html', '-W', '-E', 'docs', 'docs/_build/html'] & FG | python | def gen(skipdirhtml=False):
"""Generate html and dirhtml output."""
docs_changelog = 'docs/changelog.rst'
check_git_unchanged(docs_changelog)
pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md')
if not skipdirhtml:
sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG
sphinx_build['-b', 'html', '-W', '-E', 'docs', 'docs/_build/html'] & FG | [
"def",
"gen",
"(",
"skipdirhtml",
"=",
"False",
")",
":",
"docs_changelog",
"=",
"'docs/changelog.rst'",
"check_git_unchanged",
"(",
"docs_changelog",
")",
"pandoc",
"(",
"'--from=markdown'",
",",
"'--to=rst'",
",",
"'--output='",
"+",
"docs_changelog",
",",
"'CHANG... | Generate html and dirhtml output. | [
"Generate",
"html",
"and",
"dirhtml",
"output",
"."
] | 18f63b7de989a31b983d140a11418e01bd6fd398 | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/docs.py#L35-L42 | train | 46,200 |
johntruckenbrodt/spatialist | spatialist/explorer.py | RasterViewer.__reset_crosshair | def __reset_crosshair(self):
"""
redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
-------
"""
self.lhor.set_ydata(self.y_coord)
self.lver.set_xdata(self.x_coord) | python | def __reset_crosshair(self):
"""
redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
-------
"""
self.lhor.set_ydata(self.y_coord)
self.lver.set_xdata(self.x_coord) | [
"def",
"__reset_crosshair",
"(",
"self",
")",
":",
"self",
".",
"lhor",
".",
"set_ydata",
"(",
"self",
".",
"y_coord",
")",
"self",
".",
"lver",
".",
"set_xdata",
"(",
"self",
".",
"x_coord",
")"
] | redraw the cross-hair on the horizontal slice plot
Parameters
----------
x: int
the x image coordinate
y: int
the y image coordinate
Returns
------- | [
"redraw",
"the",
"cross",
"-",
"hair",
"on",
"the",
"horizontal",
"slice",
"plot"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/explorer.py#L243-L258 | train | 46,201 |
johntruckenbrodt/spatialist | spatialist/explorer.py | RasterViewer.__init_vertical_plot | def __init_vertical_plot(self):
"""
set up the vertical profile plot
Returns
-------
"""
# clear the plot if lines have already been drawn on it
if len(self.ax2.lines) > 0:
self.ax2.cla()
# set up the vertical profile plot
self.ax2.set_ylabel(self.datalabel, fontsize=self.fontsize)
self.ax2.set_xlabel(self.spectrumlabel, fontsize=self.fontsize)
self.ax2.set_title('vertical point profiles', fontsize=self.fontsize)
self.ax2.set_xlim([1, self.bands])
# plot vertical line at the slider position
self.vline = self.ax2.axvline(self.slider.value, color='black') | python | def __init_vertical_plot(self):
"""
set up the vertical profile plot
Returns
-------
"""
# clear the plot if lines have already been drawn on it
if len(self.ax2.lines) > 0:
self.ax2.cla()
# set up the vertical profile plot
self.ax2.set_ylabel(self.datalabel, fontsize=self.fontsize)
self.ax2.set_xlabel(self.spectrumlabel, fontsize=self.fontsize)
self.ax2.set_title('vertical point profiles', fontsize=self.fontsize)
self.ax2.set_xlim([1, self.bands])
# plot vertical line at the slider position
self.vline = self.ax2.axvline(self.slider.value, color='black') | [
"def",
"__init_vertical_plot",
"(",
"self",
")",
":",
"# clear the plot if lines have already been drawn on it",
"if",
"len",
"(",
"self",
".",
"ax2",
".",
"lines",
")",
">",
"0",
":",
"self",
".",
"ax2",
".",
"cla",
"(",
")",
"# set up the vertical profile plot",... | set up the vertical profile plot
Returns
------- | [
"set",
"up",
"the",
"vertical",
"profile",
"plot"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/explorer.py#L260-L276 | train | 46,202 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/formatters.py | PythonPercentFormat | def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None | python | def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None | [
"def",
"PythonPercentFormat",
"(",
"format_str",
")",
":",
"if",
"format_str",
".",
"startswith",
"(",
"'printf '",
")",
":",
"fmt",
"=",
"format_str",
"[",
"len",
"(",
"'printf '",
")",
":",
"]",
"return",
"lambda",
"value",
":",
"fmt",
"%",
"value",
"e... | Use Python % format strings as template format specifiers. | [
"Use",
"Python",
"%",
"format",
"strings",
"as",
"template",
"format",
"specifiers",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/formatters.py#L51-L58 | train | 46,203 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/formatters.py | Plural | def Plural(format_str):
"""Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than one are
too.
"""
if format_str.startswith('plural?'):
i = len('plural?')
try:
splitchar = format_str[i] # Usually a space, but could be something else
_, plural_val, singular_val = format_str.split(splitchar)
except IndexError:
raise Error('plural? must have exactly 2 arguments')
def Formatter(value):
plural = False
if isinstance(value, int) and value > 1:
plural = True
if isinstance(value, list) and len(value) > 1:
plural = True
if plural:
return plural_val
else:
return singular_val
return Formatter
else:
return None | python | def Plural(format_str):
"""Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than one are
too.
"""
if format_str.startswith('plural?'):
i = len('plural?')
try:
splitchar = format_str[i] # Usually a space, but could be something else
_, plural_val, singular_val = format_str.split(splitchar)
except IndexError:
raise Error('plural? must have exactly 2 arguments')
def Formatter(value):
plural = False
if isinstance(value, int) and value > 1:
plural = True
if isinstance(value, list) and len(value) > 1:
plural = True
if plural:
return plural_val
else:
return singular_val
return Formatter
else:
return None | [
"def",
"Plural",
"(",
"format_str",
")",
":",
"if",
"format_str",
".",
"startswith",
"(",
"'plural?'",
")",
":",
"i",
"=",
"len",
"(",
"'plural?'",
")",
"try",
":",
"splitchar",
"=",
"format_str",
"[",
"i",
"]",
"# Usually a space, but could be something else"... | Returns whether the value should be considered a plural value.
Integers greater than 1 are plural, and lists with length greater than one are
too. | [
"Returns",
"whether",
"the",
"value",
"should",
"be",
"considered",
"a",
"plural",
"value",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/formatters.py#L117-L147 | train | 46,204 |
vladsaveliev/TargQC | targqc/summarize.py | _correct_qualimap_genome_results | def _correct_qualimap_genome_results(samples):
""" fixing java.lang.Double.parseDouble error on entries like "6,082.49"
"""
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = False
with open(s.qualimap_genome_results_fpath, 'r') as f:
content = f.readlines()
metrics_started = False
for line in content:
if ">> Reference" in line:
metrics_started = True
if metrics_started:
if line.find(',') != -1:
correction_is_needed = True
break
if correction_is_needed:
with open(s.qualimap_genome_results_fpath, 'w') as f:
metrics_started = False
for line in content:
if ">> Reference" in line:
metrics_started = True
if metrics_started:
if line.find(',') != -1:
line = line.replace(',', '')
f.write(line) | python | def _correct_qualimap_genome_results(samples):
""" fixing java.lang.Double.parseDouble error on entries like "6,082.49"
"""
for s in samples:
if verify_file(s.qualimap_genome_results_fpath):
correction_is_needed = False
with open(s.qualimap_genome_results_fpath, 'r') as f:
content = f.readlines()
metrics_started = False
for line in content:
if ">> Reference" in line:
metrics_started = True
if metrics_started:
if line.find(',') != -1:
correction_is_needed = True
break
if correction_is_needed:
with open(s.qualimap_genome_results_fpath, 'w') as f:
metrics_started = False
for line in content:
if ">> Reference" in line:
metrics_started = True
if metrics_started:
if line.find(',') != -1:
line = line.replace(',', '')
f.write(line) | [
"def",
"_correct_qualimap_genome_results",
"(",
"samples",
")",
":",
"for",
"s",
"in",
"samples",
":",
"if",
"verify_file",
"(",
"s",
".",
"qualimap_genome_results_fpath",
")",
":",
"correction_is_needed",
"=",
"False",
"with",
"open",
"(",
"s",
".",
"qualimap_g... | fixing java.lang.Double.parseDouble error on entries like "6,082.49" | [
"fixing",
"java",
".",
"lang",
".",
"Double",
".",
"parseDouble",
"error",
"on",
"entries",
"like",
"6",
"082",
".",
"49"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/summarize.py#L165-L190 | train | 46,205 |
vladsaveliev/TargQC | targqc/summarize.py | _correct_qualimap_insert_size_histogram | def _correct_qualimap_insert_size_histogram(work_dir, samples):
""" replacing Qualimap insert size histogram with Picard one.
"""
for s in samples:
qualimap1_dirname = dirname(s.qualimap_ins_size_hist_fpath).replace('raw_data_qualimapReport', 'raw_data')
qualimap2_dirname = dirname(s.qualimap_ins_size_hist_fpath)
if exists(qualimap1_dirname):
if not exists(qualimap2_dirname):
shutil.move(qualimap1_dirname, qualimap2_dirname)
else:
shutil.rmtree(qualimap1_dirname)
elif not exists(qualimap2_dirname):
continue # no data from both Qualimap v.1 and Qualimap v.2
# if qualimap histogram exits and reuse_intermediate, skip
if verify_file(s.qualimap_ins_size_hist_fpath, silent=True) and tc.reuse_intermediate:
pass
else:
if verify_file(s.picard_ins_size_hist_txt_fpath):
with open(s.picard_ins_size_hist_txt_fpath, 'r') as picard_f:
one_line_to_stop = False
for line in picard_f:
if one_line_to_stop:
break
if line.startswith('## HISTOGRAM'):
one_line_to_stop = True
with file_transaction(work_dir, s.qualimap_ins_size_hist_fpath) as tx:
with open(tx, 'w') as qualimap_f:
for line in picard_f:
qualimap_f.write(line) | python | def _correct_qualimap_insert_size_histogram(work_dir, samples):
""" replacing Qualimap insert size histogram with Picard one.
"""
for s in samples:
qualimap1_dirname = dirname(s.qualimap_ins_size_hist_fpath).replace('raw_data_qualimapReport', 'raw_data')
qualimap2_dirname = dirname(s.qualimap_ins_size_hist_fpath)
if exists(qualimap1_dirname):
if not exists(qualimap2_dirname):
shutil.move(qualimap1_dirname, qualimap2_dirname)
else:
shutil.rmtree(qualimap1_dirname)
elif not exists(qualimap2_dirname):
continue # no data from both Qualimap v.1 and Qualimap v.2
# if qualimap histogram exits and reuse_intermediate, skip
if verify_file(s.qualimap_ins_size_hist_fpath, silent=True) and tc.reuse_intermediate:
pass
else:
if verify_file(s.picard_ins_size_hist_txt_fpath):
with open(s.picard_ins_size_hist_txt_fpath, 'r') as picard_f:
one_line_to_stop = False
for line in picard_f:
if one_line_to_stop:
break
if line.startswith('## HISTOGRAM'):
one_line_to_stop = True
with file_transaction(work_dir, s.qualimap_ins_size_hist_fpath) as tx:
with open(tx, 'w') as qualimap_f:
for line in picard_f:
qualimap_f.write(line) | [
"def",
"_correct_qualimap_insert_size_histogram",
"(",
"work_dir",
",",
"samples",
")",
":",
"for",
"s",
"in",
"samples",
":",
"qualimap1_dirname",
"=",
"dirname",
"(",
"s",
".",
"qualimap_ins_size_hist_fpath",
")",
".",
"replace",
"(",
"'raw_data_qualimapReport'",
... | replacing Qualimap insert size histogram with Picard one. | [
"replacing",
"Qualimap",
"insert",
"size",
"histogram",
"with",
"Picard",
"one",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/summarize.py#L193-L223 | train | 46,206 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bppt.py | norm_vec | def norm_vec(vector):
"""Normalize the length of a vector to one"""
assert len(vector) == 3
v = np.array(vector)
return v/np.sqrt(np.sum(v**2)) | python | def norm_vec(vector):
"""Normalize the length of a vector to one"""
assert len(vector) == 3
v = np.array(vector)
return v/np.sqrt(np.sum(v**2)) | [
"def",
"norm_vec",
"(",
"vector",
")",
":",
"assert",
"len",
"(",
"vector",
")",
"==",
"3",
"v",
"=",
"np",
".",
"array",
"(",
"vector",
")",
"return",
"v",
"/",
"np",
".",
"sqrt",
"(",
"np",
".",
"sum",
"(",
"v",
"**",
"2",
")",
")"
] | Normalize the length of a vector to one | [
"Normalize",
"the",
"length",
"of",
"a",
"vector",
"to",
"one"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bppt.py#L26-L30 | train | 46,207 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bppt.py | sphere_points_from_angles_and_tilt | def sphere_points_from_angles_and_tilt(angles, tilted_axis):
"""
For a given tilt of the rotational axis `tilted_axis`, compute
the points on a unit sphere that correspond to the distribution
`angles` along the great circle about this axis.
Parameters
----------
angles: 1d ndarray
The angles that will be distributed on the great circle.
tilted_axis: list of length 3
The tilted axis of rotation that determines the great
circle.
Notes
-----
The reference axis is always [0,1,0].
`theta` is the azimuthal angle measured down from the y-axis.
`phi` is the polar angle in the x-z plane measured from z towards x.
"""
assert len(angles.shape) == 1
# Normalize tilted axis.
tilted_axis = norm_vec(tilted_axis)
[u, v, w] = tilted_axis
# Initial distribution of points about great circle (x-z).
newang = np.zeros((angles.shape[0], 3), dtype=float)
# We subtract angles[0], because in step (a) we want that
# newang[0]==[0,0,1]. This only works if we actually start
# at that point.
newang[:, 0] = np.sin(angles-angles[0])
newang[:, 2] = np.cos(angles-angles[0])
# Compute rotational angles w.r.t. [0,1,0].
# - Draw a unit sphere with the y-axis pointing up and the
# z-axis pointing right
# - The rotation of `tilted_axis` can be described by two
# separate rotations. We will use these two angles:
# (a) Rotation from y=1 within the y-z plane: theta
# This is the rotation that is critical for data
# reconstruction. If this angle is zero, then we
# have a rotational axis in the imaging plane. If
# this angle is PI/2, then our sinogram consists
# of a rotating image and 3D reconstruction is
# impossible. This angle is counted from the y-axis
# onto the x-z plane.
# (b) Rotation in the x-z plane: phi
# This angle is responsible for matching up the angles
# with the correct sinogram images. If this angle is zero,
# then the projection of the rotational axis onto the
# x-y plane is aligned with the y-axis. If this angle is
# PI/2, then the axis and its projection onto the x-y
# plane are identical. This angle is counted from the
# positive z-axis towards the positive x-axis. By default,
# angles[0] is the point that touches the great circle
# that lies in the x-z plane. angles[1] is the next point
# towards the x-axis if phi==0.
# (a) This angle is the azimuthal angle theta measured from the
# y-axis.
theta = np.arccos(v)
# (b) This is the polar angle measured in the x-z plane starting
# at the x-axis and measured towards the positive z-axis.
if np.allclose(u, 0) and np.allclose(w, 0):
# Avoid flipping the axis of rotation due to numerical
# errors during its computation.
phi = 0
else:
phi = np.arctan2(u, w)
# Determine the projection points on the unit sphere.
# The resulting circle meets the x-z-plane at phi, and
# is tilted by theta w.r.t. the y-axis.
# (a) Create a tilted data set. This is achieved in 3 steps.
# a1) Determine radius of tilted circle and get the centered
# circle with a smaller radius.
rtilt = np.cos(theta)
newang *= rtilt
# a2) Rotate this circle about the x-axis by theta
# (right-handed/counter-clockwise/basic/elemental rotation)
Rx = np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
])
for ii in range(newang.shape[0]):
newang[ii] = np.dot(Rx, newang[ii])
# a3) Shift newang such that newang[0] is located at (0,0,1)
newang = newang - (newang[0] - np.array([0, 0, 1])).reshape(1, 3)
# (b) Rotate the entire thing with phi about the y-axis
# (right-handed/counter-clockwise/basic/elemental rotation)
Ry = np.array([
[+np.cos(phi), 0, np.sin(phi)],
[0, 1, 0],
[-np.sin(phi), 0, np.cos(phi)]
])
for jj in range(newang.shape[0]):
newang[jj] = np.dot(Ry, newang[jj])
# For visualiztaion:
# import matplotlib.pylab as plt
# from mpl_toolkits.mplot3d import Axes3D
# from matplotlib.patches import FancyArrowPatch
# from mpl_toolkits.mplot3d import proj3d
#
# class Arrow3D(FancyArrowPatch):
# def __init__(self, xs, ys, zs, *args, **kwargs):
# FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
# self._verts3d = xs, ys, zs
#
# def draw(self, renderer):
# xs3d, ys3d, zs3d = self._verts3d
# xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
# self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
# FancyArrowPatch.draw(self, renderer)
#
# fig = plt.figure(figsize=(10,10))
# ax = fig.add_subplot(111, projection='3d')
# for vec in newang:
# u,v,w = vec
# a = Arrow3D([0,u],[0,v],[0,w],
# mutation_scale=20, lw=1, arrowstyle="-|>")
# ax.add_artist(a)
#
# radius=1
# ax.set_xlabel('X')
# ax.set_ylabel('Y')
# ax.set_zlabel('Z')
# ax.set_xlim(-radius*1.5, radius*1.5)
# ax.set_ylim(-radius*1.5, radius*1.5)
# ax.set_zlim(-radius*1.5, radius*1.5)
# plt.tight_layout()
# plt.show()
return newang | python | def sphere_points_from_angles_and_tilt(angles, tilted_axis):
"""
For a given tilt of the rotational axis `tilted_axis`, compute
the points on a unit sphere that correspond to the distribution
`angles` along the great circle about this axis.
Parameters
----------
angles: 1d ndarray
The angles that will be distributed on the great circle.
tilted_axis: list of length 3
The tilted axis of rotation that determines the great
circle.
Notes
-----
The reference axis is always [0,1,0].
`theta` is the azimuthal angle measured down from the y-axis.
`phi` is the polar angle in the x-z plane measured from z towards x.
"""
assert len(angles.shape) == 1
# Normalize tilted axis.
tilted_axis = norm_vec(tilted_axis)
[u, v, w] = tilted_axis
# Initial distribution of points about great circle (x-z).
newang = np.zeros((angles.shape[0], 3), dtype=float)
# We subtract angles[0], because in step (a) we want that
# newang[0]==[0,0,1]. This only works if we actually start
# at that point.
newang[:, 0] = np.sin(angles-angles[0])
newang[:, 2] = np.cos(angles-angles[0])
# Compute rotational angles w.r.t. [0,1,0].
# - Draw a unit sphere with the y-axis pointing up and the
# z-axis pointing right
# - The rotation of `tilted_axis` can be described by two
# separate rotations. We will use these two angles:
# (a) Rotation from y=1 within the y-z plane: theta
# This is the rotation that is critical for data
# reconstruction. If this angle is zero, then we
# have a rotational axis in the imaging plane. If
# this angle is PI/2, then our sinogram consists
# of a rotating image and 3D reconstruction is
# impossible. This angle is counted from the y-axis
# onto the x-z plane.
# (b) Rotation in the x-z plane: phi
# This angle is responsible for matching up the angles
# with the correct sinogram images. If this angle is zero,
# then the projection of the rotational axis onto the
# x-y plane is aligned with the y-axis. If this angle is
# PI/2, then the axis and its projection onto the x-y
# plane are identical. This angle is counted from the
# positive z-axis towards the positive x-axis. By default,
# angles[0] is the point that touches the great circle
# that lies in the x-z plane. angles[1] is the next point
# towards the x-axis if phi==0.
# (a) This angle is the azimuthal angle theta measured from the
# y-axis.
theta = np.arccos(v)
# (b) This is the polar angle measured in the x-z plane starting
# at the x-axis and measured towards the positive z-axis.
if np.allclose(u, 0) and np.allclose(w, 0):
# Avoid flipping the axis of rotation due to numerical
# errors during its computation.
phi = 0
else:
phi = np.arctan2(u, w)
# Determine the projection points on the unit sphere.
# The resulting circle meets the x-z-plane at phi, and
# is tilted by theta w.r.t. the y-axis.
# (a) Create a tilted data set. This is achieved in 3 steps.
# a1) Determine radius of tilted circle and get the centered
# circle with a smaller radius.
rtilt = np.cos(theta)
newang *= rtilt
# a2) Rotate this circle about the x-axis by theta
# (right-handed/counter-clockwise/basic/elemental rotation)
Rx = np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
])
for ii in range(newang.shape[0]):
newang[ii] = np.dot(Rx, newang[ii])
# a3) Shift newang such that newang[0] is located at (0,0,1)
newang = newang - (newang[0] - np.array([0, 0, 1])).reshape(1, 3)
# (b) Rotate the entire thing with phi about the y-axis
# (right-handed/counter-clockwise/basic/elemental rotation)
Ry = np.array([
[+np.cos(phi), 0, np.sin(phi)],
[0, 1, 0],
[-np.sin(phi), 0, np.cos(phi)]
])
for jj in range(newang.shape[0]):
newang[jj] = np.dot(Ry, newang[jj])
# For visualiztaion:
# import matplotlib.pylab as plt
# from mpl_toolkits.mplot3d import Axes3D
# from matplotlib.patches import FancyArrowPatch
# from mpl_toolkits.mplot3d import proj3d
#
# class Arrow3D(FancyArrowPatch):
# def __init__(self, xs, ys, zs, *args, **kwargs):
# FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
# self._verts3d = xs, ys, zs
#
# def draw(self, renderer):
# xs3d, ys3d, zs3d = self._verts3d
# xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
# self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
# FancyArrowPatch.draw(self, renderer)
#
# fig = plt.figure(figsize=(10,10))
# ax = fig.add_subplot(111, projection='3d')
# for vec in newang:
# u,v,w = vec
# a = Arrow3D([0,u],[0,v],[0,w],
# mutation_scale=20, lw=1, arrowstyle="-|>")
# ax.add_artist(a)
#
# radius=1
# ax.set_xlabel('X')
# ax.set_ylabel('Y')
# ax.set_zlabel('Z')
# ax.set_xlim(-radius*1.5, radius*1.5)
# ax.set_ylim(-radius*1.5, radius*1.5)
# ax.set_zlim(-radius*1.5, radius*1.5)
# plt.tight_layout()
# plt.show()
return newang | [
"def",
"sphere_points_from_angles_and_tilt",
"(",
"angles",
",",
"tilted_axis",
")",
":",
"assert",
"len",
"(",
"angles",
".",
"shape",
")",
"==",
"1",
"# Normalize tilted axis.",
"tilted_axis",
"=",
"norm_vec",
"(",
"tilted_axis",
")",
"[",
"u",
",",
"v",
","... | For a given tilt of the rotational axis `tilted_axis`, compute
the points on a unit sphere that correspond to the distribution
`angles` along the great circle about this axis.
Parameters
----------
angles: 1d ndarray
The angles that will be distributed on the great circle.
tilted_axis: list of length 3
The tilted axis of rotation that determines the great
circle.
Notes
-----
The reference axis is always [0,1,0].
`theta` is the azimuthal angle measured down from the y-axis.
`phi` is the polar angle in the x-z plane measured from z towards x. | [
"For",
"a",
"given",
"tilt",
"of",
"the",
"rotational",
"axis",
"tilted_axis",
"compute",
"the",
"points",
"on",
"a",
"unit",
"sphere",
"that",
"correspond",
"to",
"the",
"distribution",
"angles",
"along",
"the",
"great",
"circle",
"about",
"this",
"axis",
"... | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bppt.py#L230-L371 | train | 46,208 |
python-astrodynamics/spacetrack | shovel/_helpers.py | check_git_unchanged | def check_git_unchanged(filename, yes=False):
"""Check git to avoid overwriting user changes."""
if check_staged(filename):
s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise RuntimeError('There are staged changes in '
'{}, aborting.'.format(filename))
if check_unstaged(filename):
s = 'There are unstaged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise RuntimeError('There are unstaged changes in '
'{}, aborting.'.format(filename)) | python | def check_git_unchanged(filename, yes=False):
"""Check git to avoid overwriting user changes."""
if check_staged(filename):
s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise RuntimeError('There are staged changes in '
'{}, aborting.'.format(filename))
if check_unstaged(filename):
s = 'There are unstaged changes in {}, overwrite? [y/n] '.format(filename)
if yes or input(s) in ('y', 'yes'):
return
else:
raise RuntimeError('There are unstaged changes in '
'{}, aborting.'.format(filename)) | [
"def",
"check_git_unchanged",
"(",
"filename",
",",
"yes",
"=",
"False",
")",
":",
"if",
"check_staged",
"(",
"filename",
")",
":",
"s",
"=",
"'There are staged changes in {}, overwrite? [y/n] '",
".",
"format",
"(",
"filename",
")",
"if",
"yes",
"or",
"input",
... | Check git to avoid overwriting user changes. | [
"Check",
"git",
"to",
"avoid",
"overwriting",
"user",
"changes",
"."
] | 18f63b7de989a31b983d140a11418e01bd6fd398 | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/_helpers.py#L7-L22 | train | 46,209 |
python-astrodynamics/spacetrack | shovel/_helpers.py | check_staged | def check_staged(filename=None):
"""Check if there are 'changes to be committed' in the index."""
retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',
filename].run(retcode=None)
if retcode == 1:
return True
elif retcode == 0:
return False
else:
raise RuntimeError(stdout) | python | def check_staged(filename=None):
"""Check if there are 'changes to be committed' in the index."""
retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',
filename].run(retcode=None)
if retcode == 1:
return True
elif retcode == 0:
return False
else:
raise RuntimeError(stdout) | [
"def",
"check_staged",
"(",
"filename",
"=",
"None",
")",
":",
"retcode",
",",
"_",
",",
"stdout",
"=",
"git",
"[",
"'diff-index'",
",",
"'--quiet'",
",",
"'--cached'",
",",
"'HEAD'",
",",
"filename",
"]",
".",
"run",
"(",
"retcode",
"=",
"None",
")",
... | Check if there are 'changes to be committed' in the index. | [
"Check",
"if",
"there",
"are",
"changes",
"to",
"be",
"committed",
"in",
"the",
"index",
"."
] | 18f63b7de989a31b983d140a11418e01bd6fd398 | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/_helpers.py#L25-L34 | train | 46,210 |
svenkreiss/databench | databench/meta.py | Meta.run_process | def run_process(analysis, action_name, message='__nomessagetoken__'):
"""Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to trigger.
:param message: Message.
:param callback:
A callback function when done (e.g.
:meth:`~tornado.testing.AsyncTestCase.stop` in tests).
:rtype: tornado.concurrent.Future
"""
if analysis is None:
return
# detect process_id
process_id = None
if isinstance(message, dict) and '__process_id' in message:
process_id = message['__process_id']
del message['__process_id']
if process_id:
yield analysis.emit('__process',
{'id': process_id, 'status': 'start'})
fns = [
functools.partial(handler, analysis)
for handler in (analysis._action_handlers.get(action_name, []) +
analysis._action_handlers.get('*', []))
]
if fns:
args, kwargs = [], {}
# Check whether this is a list (positional arguments)
# or a dictionary (keyword arguments).
if isinstance(message, list):
args = message
elif isinstance(message, dict):
kwargs = message
elif message == '__nomessagetoken__':
pass
else:
args = [message]
for fn in fns:
log.debug('calling {}'.format(fn))
try:
yield tornado.gen.maybe_future(fn(*args, **kwargs))
except Exception as e:
yield analysis.emit('error', 'an Exception occured')
raise e
else:
yield analysis.emit('warn',
'no handler for {}'.format(action_name))
if process_id:
yield analysis.emit('__process',
{'id': process_id, 'status': 'end'}) | python | def run_process(analysis, action_name, message='__nomessagetoken__'):
"""Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to trigger.
:param message: Message.
:param callback:
A callback function when done (e.g.
:meth:`~tornado.testing.AsyncTestCase.stop` in tests).
:rtype: tornado.concurrent.Future
"""
if analysis is None:
return
# detect process_id
process_id = None
if isinstance(message, dict) and '__process_id' in message:
process_id = message['__process_id']
del message['__process_id']
if process_id:
yield analysis.emit('__process',
{'id': process_id, 'status': 'start'})
fns = [
functools.partial(handler, analysis)
for handler in (analysis._action_handlers.get(action_name, []) +
analysis._action_handlers.get('*', []))
]
if fns:
args, kwargs = [], {}
# Check whether this is a list (positional arguments)
# or a dictionary (keyword arguments).
if isinstance(message, list):
args = message
elif isinstance(message, dict):
kwargs = message
elif message == '__nomessagetoken__':
pass
else:
args = [message]
for fn in fns:
log.debug('calling {}'.format(fn))
try:
yield tornado.gen.maybe_future(fn(*args, **kwargs))
except Exception as e:
yield analysis.emit('error', 'an Exception occured')
raise e
else:
yield analysis.emit('warn',
'no handler for {}'.format(action_name))
if process_id:
yield analysis.emit('__process',
{'id': process_id, 'status': 'end'}) | [
"def",
"run_process",
"(",
"analysis",
",",
"action_name",
",",
"message",
"=",
"'__nomessagetoken__'",
")",
":",
"if",
"analysis",
"is",
"None",
":",
"return",
"# detect process_id",
"process_id",
"=",
"None",
"if",
"isinstance",
"(",
"message",
",",
"dict",
... | Executes an action in the analysis with the given message.
It also handles the start and stop signals in the case that message
is a `dict` with a key ``__process_id``.
:param str action_name: Name of the action to trigger.
:param message: Message.
:param callback:
A callback function when done (e.g.
:meth:`~tornado.testing.AsyncTestCase.stop` in tests).
:rtype: tornado.concurrent.Future | [
"Executes",
"an",
"action",
"in",
"the",
"analysis",
"with",
"the",
"given",
"message",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/meta.py#L109-L168 | train | 46,211 |
RI-imaging/ODTbrain | examples/example_helper.py | dl_file | def dl_file(url, dest, chunk_size=6553):
"""Download `url` to `dest`"""
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data is None or len(data) == 0:
break
out.write(data)
r.release_conn() | python | def dl_file(url, dest, chunk_size=6553):
"""Download `url` to `dest`"""
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', url, preload_content=False)
with dest.open('wb') as out:
while True:
data = r.read(chunk_size)
if data is None or len(data) == 0:
break
out.write(data)
r.release_conn() | [
"def",
"dl_file",
"(",
"url",
",",
"dest",
",",
"chunk_size",
"=",
"6553",
")",
":",
"import",
"urllib3",
"http",
"=",
"urllib3",
".",
"PoolManager",
"(",
")",
"r",
"=",
"http",
".",
"request",
"(",
"'GET'",
",",
"url",
",",
"preload_content",
"=",
"... | Download `url` to `dest` | [
"Download",
"url",
"to",
"dest"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/examples/example_helper.py#L17-L28 | train | 46,212 |
RI-imaging/ODTbrain | examples/example_helper.py | extract_lzma | def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfile.mkstemp(prefix="odt_ex_", suffix=".tar")
with open(fd, "wb") as fo:
fo.write(data)
return tmpname | python | def extract_lzma(path):
"""Extract an lzma file and return the temporary file name"""
tlfile = pathlib.Path(path)
# open lzma file
with tlfile.open("rb") as td:
data = lzma.decompress(td.read())
# write temporary tar file
fd, tmpname = tempfile.mkstemp(prefix="odt_ex_", suffix=".tar")
with open(fd, "wb") as fo:
fo.write(data)
return tmpname | [
"def",
"extract_lzma",
"(",
"path",
")",
":",
"tlfile",
"=",
"pathlib",
".",
"Path",
"(",
"path",
")",
"# open lzma file",
"with",
"tlfile",
".",
"open",
"(",
"\"rb\"",
")",
"as",
"td",
":",
"data",
"=",
"lzma",
".",
"decompress",
"(",
"td",
".",
"re... | Extract an lzma file and return the temporary file name | [
"Extract",
"an",
"lzma",
"file",
"and",
"return",
"the",
"temporary",
"file",
"name"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/examples/example_helper.py#L31-L41 | train | 46,213 |
RI-imaging/ODTbrain | examples/example_helper.py | get_file | def get_file(fname, datapath=datapath):
"""Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository.
"""
# download location
datapath = pathlib.Path(datapath)
datapath.mkdir(parents=True, exist_ok=True)
dlfile = datapath / fname
if not dlfile.exists():
print("Attempting to download file {} from {} to {}.".
format(fname, webloc, datapath))
try:
dl_file(url=webloc+fname, dest=dlfile)
except BaseException:
warnings.warn("Download failed: {}".format(fname))
raise
return dlfile | python | def get_file(fname, datapath=datapath):
"""Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository.
"""
# download location
datapath = pathlib.Path(datapath)
datapath.mkdir(parents=True, exist_ok=True)
dlfile = datapath / fname
if not dlfile.exists():
print("Attempting to download file {} from {} to {}.".
format(fname, webloc, datapath))
try:
dl_file(url=webloc+fname, dest=dlfile)
except BaseException:
warnings.warn("Download failed: {}".format(fname))
raise
return dlfile | [
"def",
"get_file",
"(",
"fname",
",",
"datapath",
"=",
"datapath",
")",
":",
"# download location",
"datapath",
"=",
"pathlib",
".",
"Path",
"(",
"datapath",
")",
"datapath",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"... | Return path of an example data file
Return the full path to an example data file name.
If the file does not exist in the `datapath` directory,
tries to download it from the ODTbrain GitHub repository. | [
"Return",
"path",
"of",
"an",
"example",
"data",
"file"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/examples/example_helper.py#L44-L64 | train | 46,214 |
RI-imaging/ODTbrain | examples/example_helper.py | load_data | def load_data(fname, **kwargs):
"""Load example data"""
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_data(fname, **kwargs) | python | def load_data(fname, **kwargs):
"""Load example data"""
fname = get_file(fname)
if fname.suffix == ".lzma":
return load_tar_lzma_data(fname)
elif fname.suffix == ".zip":
return load_zip_data(fname, **kwargs) | [
"def",
"load_data",
"(",
"fname",
",",
"*",
"*",
"kwargs",
")",
":",
"fname",
"=",
"get_file",
"(",
"fname",
")",
"if",
"fname",
".",
"suffix",
"==",
"\".lzma\"",
":",
"return",
"load_tar_lzma_data",
"(",
"fname",
")",
"elif",
"fname",
".",
"suffix",
"... | Load example data | [
"Load",
"example",
"data"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/examples/example_helper.py#L67-L73 | train | 46,215 |
RI-imaging/ODTbrain | examples/example_helper.py | load_tar_lzma_data | def load_tar_lzma_data(tlfile):
"""Load example sinogram data from a .tar.lzma file"""
tmpname = extract_lzma(tlfile)
# open tar file
fields_real = []
fields_imag = []
phantom = []
parms = {}
with tarfile.open(tmpname, "r") as t:
members = t.getmembers()
members.sort(key=lambda x: x.name)
for m in members:
n = m.name
f = t.extractfile(m)
if n.startswith("fdtd_info"):
for ln in f.readlines():
ln = ln.decode()
if ln.count("=") == 1:
key, val = ln.split("=")
parms[key.strip()] = float(val.strip())
elif n.startswith("phantom"):
phantom.append(np.loadtxt(f))
elif n.startswith("field"):
if n.endswith("imag.txt"):
fields_imag.append(np.loadtxt(f))
elif n.endswith("real.txt"):
fields_real.append(np.loadtxt(f))
try:
os.remove(tmpname)
except OSError:
pass
phantom = np.array(phantom)
sino = np.array(fields_real) + 1j * np.array(fields_imag)
angles = np.linspace(0, 2 * np.pi, sino.shape[0], endpoint=False)
return sino, angles, phantom, parms | python | def load_tar_lzma_data(tlfile):
"""Load example sinogram data from a .tar.lzma file"""
tmpname = extract_lzma(tlfile)
# open tar file
fields_real = []
fields_imag = []
phantom = []
parms = {}
with tarfile.open(tmpname, "r") as t:
members = t.getmembers()
members.sort(key=lambda x: x.name)
for m in members:
n = m.name
f = t.extractfile(m)
if n.startswith("fdtd_info"):
for ln in f.readlines():
ln = ln.decode()
if ln.count("=") == 1:
key, val = ln.split("=")
parms[key.strip()] = float(val.strip())
elif n.startswith("phantom"):
phantom.append(np.loadtxt(f))
elif n.startswith("field"):
if n.endswith("imag.txt"):
fields_imag.append(np.loadtxt(f))
elif n.endswith("real.txt"):
fields_real.append(np.loadtxt(f))
try:
os.remove(tmpname)
except OSError:
pass
phantom = np.array(phantom)
sino = np.array(fields_real) + 1j * np.array(fields_imag)
angles = np.linspace(0, 2 * np.pi, sino.shape[0], endpoint=False)
return sino, angles, phantom, parms | [
"def",
"load_tar_lzma_data",
"(",
"tlfile",
")",
":",
"tmpname",
"=",
"extract_lzma",
"(",
"tlfile",
")",
"# open tar file",
"fields_real",
"=",
"[",
"]",
"fields_imag",
"=",
"[",
"]",
"phantom",
"=",
"[",
"]",
"parms",
"=",
"{",
"}",
"with",
"tarfile",
... | Load example sinogram data from a .tar.lzma file | [
"Load",
"example",
"sinogram",
"data",
"from",
"a",
".",
"tar",
".",
"lzma",
"file"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/examples/example_helper.py#L76-L116 | train | 46,216 |
RI-imaging/ODTbrain | examples/example_helper.py | load_zip_data | def load_zip_data(zipname, f_sino_real, f_sino_imag,
f_angles=None, f_phantom=None, f_info=None):
"""Load example sinogram data from a .zip file"""
ret = []
with zipfile.ZipFile(str(zipname)) as arc:
sino_real = np.loadtxt(arc.open(f_sino_real))
sino_imag = np.loadtxt(arc.open(f_sino_imag))
sino = sino_real + 1j * sino_imag
ret.append(sino)
if f_angles:
angles = np.loadtxt(arc.open(f_angles))
ret.append(angles)
if f_phantom:
phantom = np.loadtxt(arc.open(f_phantom))
ret.append(phantom)
if f_info:
with arc.open(f_info) as info:
cfg = {}
for li in info.readlines():
li = li.decode()
if li.count("=") == 1:
key, val = li.split("=")
cfg[key.strip()] = float(val.strip())
ret.append(cfg)
return ret | python | def load_zip_data(zipname, f_sino_real, f_sino_imag,
f_angles=None, f_phantom=None, f_info=None):
"""Load example sinogram data from a .zip file"""
ret = []
with zipfile.ZipFile(str(zipname)) as arc:
sino_real = np.loadtxt(arc.open(f_sino_real))
sino_imag = np.loadtxt(arc.open(f_sino_imag))
sino = sino_real + 1j * sino_imag
ret.append(sino)
if f_angles:
angles = np.loadtxt(arc.open(f_angles))
ret.append(angles)
if f_phantom:
phantom = np.loadtxt(arc.open(f_phantom))
ret.append(phantom)
if f_info:
with arc.open(f_info) as info:
cfg = {}
for li in info.readlines():
li = li.decode()
if li.count("=") == 1:
key, val = li.split("=")
cfg[key.strip()] = float(val.strip())
ret.append(cfg)
return ret | [
"def",
"load_zip_data",
"(",
"zipname",
",",
"f_sino_real",
",",
"f_sino_imag",
",",
"f_angles",
"=",
"None",
",",
"f_phantom",
"=",
"None",
",",
"f_info",
"=",
"None",
")",
":",
"ret",
"=",
"[",
"]",
"with",
"zipfile",
".",
"ZipFile",
"(",
"str",
"(",... | Load example sinogram data from a .zip file | [
"Load",
"example",
"sinogram",
"data",
"from",
"a",
".",
"zip",
"file"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/examples/example_helper.py#L119-L143 | train | 46,217 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | transform_to | def transform_to(ext):
"""
Decorator to create an output filename from an output filename with
the specified extension. Changes the extension, in_file is transformed
to a new type.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:
@transform(".bam")
f("the/input/path/file.sam") ->
f("the/input/path/file.sam", out_file="the/input/path/file.bam")
@transform(".bam")
f("the/input/path/file.sam", out_dir="results") ->
f("the/input/path/file.sam", out_file="results/file.bam")
"""
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
out_dir = kwargs.get("out_dir", os.path.dirname(in_path))
safe_mkdir(out_dir)
out_name = replace_suffix(os.path.basename(in_path), ext)
out_file = os.path.join(out_dir, out_name)
kwargs["out_file"] = out_file
if not file_exists(out_file):
out_file = f(*args, **kwargs)
return out_file
return wrapper
return decor | python | def transform_to(ext):
"""
Decorator to create an output filename from an output filename with
the specified extension. Changes the extension, in_file is transformed
to a new type.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:
@transform(".bam")
f("the/input/path/file.sam") ->
f("the/input/path/file.sam", out_file="the/input/path/file.bam")
@transform(".bam")
f("the/input/path/file.sam", out_dir="results") ->
f("the/input/path/file.sam", out_file="results/file.bam")
"""
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
out_dir = kwargs.get("out_dir", os.path.dirname(in_path))
safe_mkdir(out_dir)
out_name = replace_suffix(os.path.basename(in_path), ext)
out_file = os.path.join(out_dir, out_name)
kwargs["out_file"] = out_file
if not file_exists(out_file):
out_file = f(*args, **kwargs)
return out_file
return wrapper
return decor | [
"def",
"transform_to",
"(",
"ext",
")",
":",
"def",
"decor",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out_file",
"=",
"kwargs",
".",
"get",
"(",
"... | Decorator to create an output filename from an output filename with
the specified extension. Changes the extension, in_file is transformed
to a new type.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:
@transform(".bam")
f("the/input/path/file.sam") ->
f("the/input/path/file.sam", out_file="the/input/path/file.bam")
@transform(".bam")
f("the/input/path/file.sam", out_dir="results") ->
f("the/input/path/file.sam", out_file="results/file.bam") | [
"Decorator",
"to",
"create",
"an",
"output",
"filename",
"from",
"an",
"output",
"filename",
"with",
"the",
"specified",
"extension",
".",
"Changes",
"the",
"extension",
"in_file",
"is",
"transformed",
"to",
"a",
"new",
"type",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L59-L95 | train | 46,218 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | filter_to | def filter_to(word):
"""
Decorator to create an output filename from an input filename by
adding a word onto the stem. in_file is filtered by the function
and the results are written to out_file. You would want to use
this over transform_to if you don't know the extension of the file
going in. This also memoizes the output file.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:
@filter_to(".foo")
f("the/input/path/file.sam") ->
f("the/input/path/file.sam", out_file="the/input/path/file.foo.bam")
@filter_to(".foo")
f("the/input/path/file.sam", out_dir="results") ->
f("the/input/path/file.sam", out_file="results/file.foo.bam")
"""
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
out_dir = kwargs.get("out_dir", os.path.dirname(in_path))
safe_mkdir(out_dir)
out_name = append_stem(os.path.basename(in_path), word)
out_file = os.path.join(out_dir, out_name)
kwargs["out_file"] = out_file
if not file_exists(out_file):
out_file = f(*args, **kwargs)
return out_file
return wrapper
return decor | python | def filter_to(word):
"""
Decorator to create an output filename from an input filename by
adding a word onto the stem. in_file is filtered by the function
and the results are written to out_file. You would want to use
this over transform_to if you don't know the extension of the file
going in. This also memoizes the output file.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:
@filter_to(".foo")
f("the/input/path/file.sam") ->
f("the/input/path/file.sam", out_file="the/input/path/file.foo.bam")
@filter_to(".foo")
f("the/input/path/file.sam", out_dir="results") ->
f("the/input/path/file.sam", out_file="results/file.foo.bam")
"""
def decor(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
out_file = kwargs.get("out_file", None)
if not out_file:
in_path = kwargs.get("in_file", args[0])
out_dir = kwargs.get("out_dir", os.path.dirname(in_path))
safe_mkdir(out_dir)
out_name = append_stem(os.path.basename(in_path), word)
out_file = os.path.join(out_dir, out_name)
kwargs["out_file"] = out_file
if not file_exists(out_file):
out_file = f(*args, **kwargs)
return out_file
return wrapper
return decor | [
"def",
"filter_to",
"(",
"word",
")",
":",
"def",
"decor",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out_file",
"=",
"kwargs",
".",
"get",
"(",
"\"... | Decorator to create an output filename from an input filename by
adding a word onto the stem. in_file is filtered by the function
and the results are written to out_file. You would want to use
this over transform_to if you don't know the extension of the file
going in. This also memoizes the output file.
Takes functions like this to decorate:
f(in_file, out_dir=None, out_file=None) or,
f(in_file=in_file, out_dir=None, out_file=None)
examples:
@filter_to(".foo")
f("the/input/path/file.sam") ->
f("the/input/path/file.sam", out_file="the/input/path/file.foo.bam")
@filter_to(".foo")
f("the/input/path/file.sam", out_dir="results") ->
f("the/input/path/file.sam", out_file="results/file.foo.bam") | [
"Decorator",
"to",
"create",
"an",
"output",
"filename",
"from",
"an",
"input",
"filename",
"by",
"adding",
"a",
"word",
"onto",
"the",
"stem",
".",
"in_file",
"is",
"filtered",
"by",
"the",
"function",
"and",
"the",
"results",
"are",
"written",
"to",
"out... | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L98-L136 | train | 46,219 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | get_in | def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
"""
result = reduce(lambda d, t: d.get(t, {}), t, d)
if not result:
return default
else:
return result | python | def get_in(d, t, default=None):
"""
look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {}
"""
result = reduce(lambda d, t: d.get(t, {}), t, d)
if not result:
return default
else:
return result | [
"def",
"get_in",
"(",
"d",
",",
"t",
",",
"default",
"=",
"None",
")",
":",
"result",
"=",
"reduce",
"(",
"lambda",
"d",
",",
"t",
":",
"d",
".",
"get",
"(",
"t",
",",
"{",
"}",
")",
",",
"t",
",",
"d",
")",
"if",
"not",
"result",
":",
"r... | look up if you can get a tuple of values from a nested dictionary,
each item in the tuple a deeper layer
example: get_in({1: {2: 3}}, (1, 2)) -> 3
example: get_in({1: {2: 3}}, (2, 3)) -> {} | [
"look",
"up",
"if",
"you",
"can",
"get",
"a",
"tuple",
"of",
"values",
"from",
"a",
"nested",
"dictionary",
"each",
"item",
"in",
"the",
"tuple",
"a",
"deeper",
"layer"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L320-L332 | train | 46,220 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | which | def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None | python | def which(program):
"""
returns the path to an executable or None if it can't be found
"""
def is_exe(_fpath):
return os.path.isfile(_fpath) and os.access(_fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None | [
"def",
"which",
"(",
"program",
")",
":",
"def",
"is_exe",
"(",
"_fpath",
")",
":",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"_fpath",
")",
"and",
"os",
".",
"access",
"(",
"_fpath",
",",
"os",
".",
"X_OK",
")",
"fpath",
",",
"fname",
"="... | returns the path to an executable or None if it can't be found | [
"returns",
"the",
"path",
"to",
"an",
"executable",
"or",
"None",
"if",
"it",
"can",
"t",
"be",
"found"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L439-L455 | train | 46,221 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | expanduser | def expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif not 'HOMEPATH' in os.environ:
return path
else:
try:
drive = os.environ['HOMEDRIVE']
except KeyError:
drive = ''
userhome = join(drive, os.environ['HOMEPATH'])
if i != 1: # ~user
userhome = join(dirname(userhome), path[1:i])
return userhome + path[i:] | python | def expanduser(path):
"""Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if 'HOME' in os.environ:
userhome = os.environ['HOME']
elif 'USERPROFILE' in os.environ:
userhome = os.environ['USERPROFILE']
elif not 'HOMEPATH' in os.environ:
return path
else:
try:
drive = os.environ['HOMEDRIVE']
except KeyError:
drive = ''
userhome = join(drive, os.environ['HOMEPATH'])
if i != 1: # ~user
userhome = join(dirname(userhome), path[1:i])
return userhome + path[i:] | [
"def",
"expanduser",
"(",
"path",
")",
":",
"if",
"path",
"[",
":",
"1",
"]",
"!=",
"'~'",
":",
"return",
"path",
"i",
",",
"n",
"=",
"1",
",",
"len",
"(",
"path",
")",
"while",
"i",
"<",
"n",
"and",
"path",
"[",
"i",
"]",
"not",
"in",
"'/\... | Expand ~ and ~user constructs.
If user or $HOME is unknown, do nothing. | [
"Expand",
"~",
"and",
"~user",
"constructs",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L542-L568 | train | 46,222 |
vladsaveliev/TargQC | targqc/utilz/file_utils.py | dots_to_empty_cells | def dots_to_empty_cells(config, tsv_fpath):
"""Put dots instead of empty cells in order to view TSV with column -t
"""
def proc_line(l, i):
while '\t\t' in l:
l = l.replace('\t\t', '\t.\t')
return l
return iterate_file(config, tsv_fpath, proc_line, suffix='dots') | python | def dots_to_empty_cells(config, tsv_fpath):
"""Put dots instead of empty cells in order to view TSV with column -t
"""
def proc_line(l, i):
while '\t\t' in l:
l = l.replace('\t\t', '\t.\t')
return l
return iterate_file(config, tsv_fpath, proc_line, suffix='dots') | [
"def",
"dots_to_empty_cells",
"(",
"config",
",",
"tsv_fpath",
")",
":",
"def",
"proc_line",
"(",
"l",
",",
"i",
")",
":",
"while",
"'\\t\\t'",
"in",
"l",
":",
"l",
"=",
"l",
".",
"replace",
"(",
"'\\t\\t'",
",",
"'\\t.\\t'",
")",
"return",
"l",
"ret... | Put dots instead of empty cells in order to view TSV with column -t | [
"Put",
"dots",
"instead",
"of",
"empty",
"cells",
"in",
"order",
"to",
"view",
"TSV",
"with",
"column",
"-",
"t"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/file_utils.py#L843-L850 | train | 46,223 |
svenkreiss/databench | databench/datastore.py | Datastore.trigger_all_callbacks | def trigger_all_callbacks(self, callbacks=None):
"""Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future]
"""
return [ret
for key in self
for ret in self.trigger_callbacks(key, callbacks=None)] | python | def trigger_all_callbacks(self, callbacks=None):
"""Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future]
"""
return [ret
for key in self
for ret in self.trigger_callbacks(key, callbacks=None)] | [
"def",
"trigger_all_callbacks",
"(",
"self",
",",
"callbacks",
"=",
"None",
")",
":",
"return",
"[",
"ret",
"for",
"key",
"in",
"self",
"for",
"ret",
"in",
"self",
".",
"trigger_callbacks",
"(",
"key",
",",
"callbacks",
"=",
"None",
")",
"]"
] | Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future] | [
"Trigger",
"callbacks",
"for",
"all",
"keys",
"on",
"all",
"or",
"a",
"subset",
"of",
"subscribers",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L63-L71 | train | 46,224 |
svenkreiss/databench | databench/datastore.py | Datastore.set_state | def set_state(self, updater=None, **kwargs):
"""Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future]
"""
if callable(updater):
state_change = updater(self)
elif updater is not None:
state_change = updater
else:
state_change = kwargs
return [callback_result
for k, v in state_change.items()
for callback_result in self.set(k, v)] | python | def set_state(self, updater=None, **kwargs):
"""Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future]
"""
if callable(updater):
state_change = updater(self)
elif updater is not None:
state_change = updater
else:
state_change = kwargs
return [callback_result
for k, v in state_change.items()
for callback_result in self.set(k, v)] | [
"def",
"set_state",
"(",
"self",
",",
"updater",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"callable",
"(",
"updater",
")",
":",
"state_change",
"=",
"updater",
"(",
"self",
")",
"elif",
"updater",
"is",
"not",
"None",
":",
"state_change",
... | Update the datastore.
:param func|dict updater: (state) => state_change or dict state_change
:rtype: Iterable[tornado.concurrent.Future] | [
"Update",
"the",
"datastore",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/datastore.py#L111-L126 | train | 46,225 |
vladsaveliev/TargQC | targqc/qualimap/runner.py | run_multisample_qualimap | def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in samples]
if isdir(plots_dirpath) and not any(
not can_reuse(join(plots_dirpath, f), individual_report_fpaths)
for f in listdir(plots_dirpath) if not f.startswith('.')):
debug('Qualimap miltisample plots exist - ' + plots_dirpath + ', reusing...')
else:
# Qualimap2 run for multi-sample plots
if len([s.qualimap_html_fpath for s in samples if s.qualimap_html_fpath]) > 0:
if find_executable() is not None: # and get_qualimap_type(find_executable()) == 'full':
qualimap_output_dir = join(work_dir, 'qualimap_multi_bamqc')
_correct_qualimap_genome_results(samples)
_correct_qualimap_insert_size_histogram(samples)
safe_mkdir(qualimap_output_dir)
rows = []
for sample in samples:
if sample.qualimap_html_fpath:
rows += [[sample.name, sample.qualimap_html_fpath]]
data_fpath = write_tsv_rows(([], rows), join(qualimap_output_dir, 'qualimap_results_by_sample.tsv'))
qualimap_plots_dirpath = join(qualimap_output_dir, 'images_multisampleBamQcReport')
cmdline = find_executable() + ' multi-bamqc --data {data_fpath} -outdir {qualimap_output_dir}'.format(**locals())
run(cmdline, env_vars=dict(DISPLAY=None),
checks=[lambda _1, _2: verify_dir(qualimap_output_dir)], reuse=cfg.reuse_intermediate)
if not verify_dir(qualimap_plots_dirpath):
warn('Warning: Qualimap for multi-sample analysis failed to finish. TargQC will not contain plots.')
return None
else:
if exists(plots_dirpath):
shutil.rmtree(plots_dirpath)
shutil.move(qualimap_plots_dirpath, plots_dirpath)
else:
warn('Warning: Qualimap for multi-sample analysis was not found. TargQC will not contain plots.')
return None
targqc_full_report.plots = []
for plot_fpath in listdir(plots_dirpath):
plot_fpath = join(plots_dirpath, plot_fpath)
if verify_file(plot_fpath) and plot_fpath.endswith('.png'):
targqc_full_report.plots.append(relpath(plot_fpath, output_dir)) | python | def run_multisample_qualimap(output_dir, work_dir, samples, targqc_full_report):
""" 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots
"""
plots_dirpath = join(output_dir, 'plots')
individual_report_fpaths = [s.qualimap_html_fpath for s in samples]
if isdir(plots_dirpath) and not any(
not can_reuse(join(plots_dirpath, f), individual_report_fpaths)
for f in listdir(plots_dirpath) if not f.startswith('.')):
debug('Qualimap miltisample plots exist - ' + plots_dirpath + ', reusing...')
else:
# Qualimap2 run for multi-sample plots
if len([s.qualimap_html_fpath for s in samples if s.qualimap_html_fpath]) > 0:
if find_executable() is not None: # and get_qualimap_type(find_executable()) == 'full':
qualimap_output_dir = join(work_dir, 'qualimap_multi_bamqc')
_correct_qualimap_genome_results(samples)
_correct_qualimap_insert_size_histogram(samples)
safe_mkdir(qualimap_output_dir)
rows = []
for sample in samples:
if sample.qualimap_html_fpath:
rows += [[sample.name, sample.qualimap_html_fpath]]
data_fpath = write_tsv_rows(([], rows), join(qualimap_output_dir, 'qualimap_results_by_sample.tsv'))
qualimap_plots_dirpath = join(qualimap_output_dir, 'images_multisampleBamQcReport')
cmdline = find_executable() + ' multi-bamqc --data {data_fpath} -outdir {qualimap_output_dir}'.format(**locals())
run(cmdline, env_vars=dict(DISPLAY=None),
checks=[lambda _1, _2: verify_dir(qualimap_output_dir)], reuse=cfg.reuse_intermediate)
if not verify_dir(qualimap_plots_dirpath):
warn('Warning: Qualimap for multi-sample analysis failed to finish. TargQC will not contain plots.')
return None
else:
if exists(plots_dirpath):
shutil.rmtree(plots_dirpath)
shutil.move(qualimap_plots_dirpath, plots_dirpath)
else:
warn('Warning: Qualimap for multi-sample analysis was not found. TargQC will not contain plots.')
return None
targqc_full_report.plots = []
for plot_fpath in listdir(plots_dirpath):
plot_fpath = join(plots_dirpath, plot_fpath)
if verify_file(plot_fpath) and plot_fpath.endswith('.png'):
targqc_full_report.plots.append(relpath(plot_fpath, output_dir)) | [
"def",
"run_multisample_qualimap",
"(",
"output_dir",
",",
"work_dir",
",",
"samples",
",",
"targqc_full_report",
")",
":",
"plots_dirpath",
"=",
"join",
"(",
"output_dir",
",",
"'plots'",
")",
"individual_report_fpaths",
"=",
"[",
"s",
".",
"qualimap_html_fpath",
... | 1. Generates Qualimap2 plots and put into plots_dirpath
2. Adds records to targqc_full_report.plots | [
"1",
".",
"Generates",
"Qualimap2",
"plots",
"and",
"put",
"into",
"plots_dirpath",
"2",
".",
"Adds",
"records",
"to",
"targqc_full_report",
".",
"plots"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/qualimap/runner.py#L97-L143 | train | 46,226 |
RI-imaging/ODTbrain | odtbrain/_postproc.py | odt_to_ri | def odt_to_ri(f, res, nm):
r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1
\right]
with :math:`k_\mathrm{m} = \frac{2\pi n_\mathrm{m}}{\lambda}`.
By inverting this equation, we obtain the refractive index
:math:`n(\mathbf{r})`.
.. math::
n(\mathbf{r}) = n_\mathrm{m}
\sqrt{\frac{f(\mathbf{r})}{k_\mathrm{m}^2} + 1 }
Parameters
----------
f: n-dimensional ndarray
The reconstructed object function :math:`f(\mathbf{r})`.
res: float
The size of the vacuum wave length :math:`\lambda` in pixels.
nm: float
The refractive index of the medium :math:`n_\mathrm{m}` that
surrounds the object in :math:`f(\mathbf{r})`.
Returns
-------
ri: n-dimensional ndarray
The complex refractive index :math:`n(\mathbf{r})`.
Notes
-----
Because this function computes the root of a complex number, there
are several solutions to the refractive index. Always the positive
(real) root of the refractive index is used.
"""
km = (2 * np.pi * nm) / res
ri = nm * np.sqrt(f / km**2 + 1)
# Always take the positive root as the refractive index.
# Because f can be imaginary, numpy cannot return the correct
# positive root of f. However, we know that *ri* must be postive and
# thus we take the absolute value of ri.
# This also is what happens in Slaneys
# diffract/Src/back.c in line 414.
negrootcoord = np.where(ri.real < 0)
ri[negrootcoord] *= -1
return ri | python | def odt_to_ri(f, res, nm):
r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1
\right]
with :math:`k_\mathrm{m} = \frac{2\pi n_\mathrm{m}}{\lambda}`.
By inverting this equation, we obtain the refractive index
:math:`n(\mathbf{r})`.
.. math::
n(\mathbf{r}) = n_\mathrm{m}
\sqrt{\frac{f(\mathbf{r})}{k_\mathrm{m}^2} + 1 }
Parameters
----------
f: n-dimensional ndarray
The reconstructed object function :math:`f(\mathbf{r})`.
res: float
The size of the vacuum wave length :math:`\lambda` in pixels.
nm: float
The refractive index of the medium :math:`n_\mathrm{m}` that
surrounds the object in :math:`f(\mathbf{r})`.
Returns
-------
ri: n-dimensional ndarray
The complex refractive index :math:`n(\mathbf{r})`.
Notes
-----
Because this function computes the root of a complex number, there
are several solutions to the refractive index. Always the positive
(real) root of the refractive index is used.
"""
km = (2 * np.pi * nm) / res
ri = nm * np.sqrt(f / km**2 + 1)
# Always take the positive root as the refractive index.
# Because f can be imaginary, numpy cannot return the correct
# positive root of f. However, we know that *ri* must be postive and
# thus we take the absolute value of ri.
# This also is what happens in Slaneys
# diffract/Src/back.c in line 414.
negrootcoord = np.where(ri.real < 0)
ri[negrootcoord] *= -1
return ri | [
"def",
"odt_to_ri",
"(",
"f",
",",
"res",
",",
"nm",
")",
":",
"km",
"=",
"(",
"2",
"*",
"np",
".",
"pi",
"*",
"nm",
")",
"/",
"res",
"ri",
"=",
"nm",
"*",
"np",
".",
"sqrt",
"(",
"f",
"/",
"km",
"**",
"2",
"+",
"1",
")",
"# Always take t... | r"""Convert the ODT object function to refractive index
In :abbr:`ODT (Optical Diffraction Tomography)`, the object function
is defined by the Helmholtz equation
.. math::
f(\mathbf{r}) = k_\mathrm{m}^2 \left[
\left( \frac{n(\mathbf{r})}{n_\mathrm{m}} \right)^2 - 1
\right]
with :math:`k_\mathrm{m} = \frac{2\pi n_\mathrm{m}}{\lambda}`.
By inverting this equation, we obtain the refractive index
:math:`n(\mathbf{r})`.
.. math::
n(\mathbf{r}) = n_\mathrm{m}
\sqrt{\frac{f(\mathbf{r})}{k_\mathrm{m}^2} + 1 }
Parameters
----------
f: n-dimensional ndarray
The reconstructed object function :math:`f(\mathbf{r})`.
res: float
The size of the vacuum wave length :math:`\lambda` in pixels.
nm: float
The refractive index of the medium :math:`n_\mathrm{m}` that
surrounds the object in :math:`f(\mathbf{r})`.
Returns
-------
ri: n-dimensional ndarray
The complex refractive index :math:`n(\mathbf{r})`.
Notes
-----
Because this function computes the root of a complex number, there
are several solutions to the refractive index. Always the positive
(real) root of the refractive index is used. | [
"r",
"Convert",
"the",
"ODT",
"object",
"function",
"to",
"refractive",
"index"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_postproc.py#L5-L57 | train | 46,227 |
RI-imaging/ODTbrain | odtbrain/_postproc.py | opt_to_ri | def opt_to_ri(f, res, nm):
r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
\frac{f(\mathbf{r}) \cdot \lambda}{2 \pi}
Parameters
----------
f: n-dimensional ndarray
The reconstructed object function :math:`f(\mathbf{r})`.
res: float
The size of the vacuum wave length :math:`\lambda` in pixels.
nm: float
The refractive index of the medium :math:`n_\mathrm{m}` that
surrounds the object in :math:`f(\mathbf{r})`.
Returns
-------
ri: n-dimensional ndarray
The complex refractive index :math:`n(\mathbf{r})`.
Notes
-----
This function is not meant to be used with diffraction tomography
data. For ODT, use :py:func:`odt_to_ri` instead.
"""
ri = nm + f / (2 * np.pi) * res
return ri | python | def opt_to_ri(f, res, nm):
r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
\frac{f(\mathbf{r}) \cdot \lambda}{2 \pi}
Parameters
----------
f: n-dimensional ndarray
The reconstructed object function :math:`f(\mathbf{r})`.
res: float
The size of the vacuum wave length :math:`\lambda` in pixels.
nm: float
The refractive index of the medium :math:`n_\mathrm{m}` that
surrounds the object in :math:`f(\mathbf{r})`.
Returns
-------
ri: n-dimensional ndarray
The complex refractive index :math:`n(\mathbf{r})`.
Notes
-----
This function is not meant to be used with diffraction tomography
data. For ODT, use :py:func:`odt_to_ri` instead.
"""
ri = nm + f / (2 * np.pi) * res
return ri | [
"def",
"opt_to_ri",
"(",
"f",
",",
"res",
",",
"nm",
")",
":",
"ri",
"=",
"nm",
"+",
"f",
"/",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"*",
"res",
"return",
"ri"
] | r"""Convert the OPT object function to refractive index
In :abbr:`OPT (Optical Projection Tomography)`, the object function
is computed from the raw phase data. This method converts phase data
to refractive index data.
.. math::
n(\mathbf{r}) = n_\mathrm{m} +
\frac{f(\mathbf{r}) \cdot \lambda}{2 \pi}
Parameters
----------
f: n-dimensional ndarray
The reconstructed object function :math:`f(\mathbf{r})`.
res: float
The size of the vacuum wave length :math:`\lambda` in pixels.
nm: float
The refractive index of the medium :math:`n_\mathrm{m}` that
surrounds the object in :math:`f(\mathbf{r})`.
Returns
-------
ri: n-dimensional ndarray
The complex refractive index :math:`n(\mathbf{r})`.
Notes
-----
This function is not meant to be used with diffraction tomography
data. For ODT, use :py:func:`odt_to_ri` instead. | [
"r",
"Convert",
"the",
"OPT",
"object",
"function",
"to",
"refractive",
"index"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_postproc.py#L60-L93 | train | 46,228 |
johntruckenbrodt/spatialist | spatialist/raster.py | rasterize | def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
"""
rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo information and extent from
outname: str or None
the name of the GeoTiff output file; if None, an in-memory object of type :class:`Raster` is returned and
parameter outname is ignored
burn_values: int or list
the values to be written to the raster file
expressions: list
SQL expressions to filter the vector object by attributes
nodata: int
the nodata value of the target raster file
append: bool
if the output file already exists, update this file with new rasterized values?
If True and the output file exists, parameters `reference` and `nodata` are ignored.
Returns
-------
Raster or None
if outname is `None`, a raster object pointing to an in-memory dataset else `None`
Example
-------
>>> from spatialist import Vector, Raster, rasterize
>>> vec = Vector('source.shp')
>>> ref = Raster('reference.tif')
>>> outname = 'target.tif'
>>> expressions = ['ATTRIBUTE=1', 'ATTRIBUTE=2']
>>> burn_values = [1, 2]
>>> rasterize(vec, reference, outname, burn_values, expressions)
"""
if expressions is None:
expressions = ['']
if isinstance(burn_values, (int, float)):
burn_values = [burn_values]
if len(expressions) != len(burn_values):
raise RuntimeError('expressions and burn_values of different length')
failed = []
for exp in expressions:
try:
vectorobject.layer.SetAttributeFilter(exp)
except RuntimeError:
failed.append(exp)
if len(failed) > 0:
raise RuntimeError('failed to set the following attribute filter(s): ["{}"]'.format('", '.join(failed)))
if append and outname is not None and os.path.isfile(outname):
target_ds = gdal.Open(outname, GA_Update)
else:
if not isinstance(reference, Raster):
raise RuntimeError("parameter 'reference' must be of type Raster")
if outname is not None:
target_ds = gdal.GetDriverByName('GTiff').Create(outname, reference.cols, reference.rows, 1, gdal.GDT_Byte)
else:
target_ds = gdal.GetDriverByName('MEM').Create('', reference.cols, reference.rows, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform(reference.raster.GetGeoTransform())
target_ds.SetProjection(reference.raster.GetProjection())
band = target_ds.GetRasterBand(1)
band.SetNoDataValue(nodata)
band.FlushCache()
band = None
for expression, value in zip(expressions, burn_values):
vectorobject.layer.SetAttributeFilter(expression)
gdal.RasterizeLayer(target_ds, [1], vectorobject.layer, burn_values=[value])
vectorobject.layer.SetAttributeFilter('')
if outname is None:
return Raster(target_ds)
else:
target_ds = None | python | def rasterize(vectorobject, reference, outname=None, burn_values=1, expressions=None, nodata=0, append=False):
"""
rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo information and extent from
outname: str or None
the name of the GeoTiff output file; if None, an in-memory object of type :class:`Raster` is returned and
parameter outname is ignored
burn_values: int or list
the values to be written to the raster file
expressions: list
SQL expressions to filter the vector object by attributes
nodata: int
the nodata value of the target raster file
append: bool
if the output file already exists, update this file with new rasterized values?
If True and the output file exists, parameters `reference` and `nodata` are ignored.
Returns
-------
Raster or None
if outname is `None`, a raster object pointing to an in-memory dataset else `None`
Example
-------
>>> from spatialist import Vector, Raster, rasterize
>>> vec = Vector('source.shp')
>>> ref = Raster('reference.tif')
>>> outname = 'target.tif'
>>> expressions = ['ATTRIBUTE=1', 'ATTRIBUTE=2']
>>> burn_values = [1, 2]
>>> rasterize(vec, reference, outname, burn_values, expressions)
"""
if expressions is None:
expressions = ['']
if isinstance(burn_values, (int, float)):
burn_values = [burn_values]
if len(expressions) != len(burn_values):
raise RuntimeError('expressions and burn_values of different length')
failed = []
for exp in expressions:
try:
vectorobject.layer.SetAttributeFilter(exp)
except RuntimeError:
failed.append(exp)
if len(failed) > 0:
raise RuntimeError('failed to set the following attribute filter(s): ["{}"]'.format('", '.join(failed)))
if append and outname is not None and os.path.isfile(outname):
target_ds = gdal.Open(outname, GA_Update)
else:
if not isinstance(reference, Raster):
raise RuntimeError("parameter 'reference' must be of type Raster")
if outname is not None:
target_ds = gdal.GetDriverByName('GTiff').Create(outname, reference.cols, reference.rows, 1, gdal.GDT_Byte)
else:
target_ds = gdal.GetDriverByName('MEM').Create('', reference.cols, reference.rows, 1, gdal.GDT_Byte)
target_ds.SetGeoTransform(reference.raster.GetGeoTransform())
target_ds.SetProjection(reference.raster.GetProjection())
band = target_ds.GetRasterBand(1)
band.SetNoDataValue(nodata)
band.FlushCache()
band = None
for expression, value in zip(expressions, burn_values):
vectorobject.layer.SetAttributeFilter(expression)
gdal.RasterizeLayer(target_ds, [1], vectorobject.layer, burn_values=[value])
vectorobject.layer.SetAttributeFilter('')
if outname is None:
return Raster(target_ds)
else:
target_ds = None | [
"def",
"rasterize",
"(",
"vectorobject",
",",
"reference",
",",
"outname",
"=",
"None",
",",
"burn_values",
"=",
"1",
",",
"expressions",
"=",
"None",
",",
"nodata",
"=",
"0",
",",
"append",
"=",
"False",
")",
":",
"if",
"expressions",
"is",
"None",
":... | rasterize a vector object
Parameters
----------
vectorobject: Vector
the vector object to be rasterized
reference: Raster
a reference Raster object to retrieve geo information and extent from
outname: str or None
the name of the GeoTiff output file; if None, an in-memory object of type :class:`Raster` is returned and
parameter outname is ignored
burn_values: int or list
the values to be written to the raster file
expressions: list
SQL expressions to filter the vector object by attributes
nodata: int
the nodata value of the target raster file
append: bool
if the output file already exists, update this file with new rasterized values?
If True and the output file exists, parameters `reference` and `nodata` are ignored.
Returns
-------
Raster or None
if outname is `None`, a raster object pointing to an in-memory dataset else `None`
Example
-------
>>> from spatialist import Vector, Raster, rasterize
>>> vec = Vector('source.shp')
>>> ref = Raster('reference.tif')
>>> outname = 'target.tif'
>>> expressions = ['ATTRIBUTE=1', 'ATTRIBUTE=2']
>>> burn_values = [1, 2]
>>> rasterize(vec, reference, outname, burn_values, expressions) | [
"rasterize",
"a",
"vector",
"object"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L902-L977 | train | 46,229 |
johntruckenbrodt/spatialist | spatialist/raster.py | reproject | def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff'):
"""
reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
either a projection string or a spatial object with an attribute 'projection'
outname: str
the name of the output file
targetres: tuple
the output resolution in the target SRS; a two-entry tuple is required: (xres, yres)
resampling: str
the resampling algorithm to be used
format: str
the output file format
Returns
-------
"""
if isinstance(rasterobject, str):
rasterobject = Raster(rasterobject)
if not isinstance(rasterobject, Raster):
raise RuntimeError('rasterobject must be of type Raster or str')
if isinstance(reference, (Raster, Vector)):
projection = reference.projection
if targetres is not None:
xres, yres = targetres
elif hasattr(reference, 'res'):
xres, yres = reference.res
else:
raise RuntimeError('parameter targetres is missing and cannot be read from the reference')
elif isinstance(reference, (int, str, osr.SpatialReference)):
try:
projection = crsConvert(reference, 'proj4')
except TypeError:
raise RuntimeError('reference projection cannot be read')
if targetres is None:
raise RuntimeError('parameter targetres is missing and cannot be read from the reference')
else:
xres, yres = targetres
else:
raise TypeError('reference must be of type Raster, Vector, osr.SpatialReference, str or int')
options = {'format': format,
'resampleAlg': resampling,
'xRes': xres,
'yRes': yres,
'srcNodata': rasterobject.nodata,
'dstNodata': rasterobject.nodata,
'dstSRS': projection}
gdalwarp(rasterobject, outname, options) | python | def reproject(rasterobject, reference, outname, targetres=None, resampling='bilinear', format='GTiff'):
"""
reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
either a projection string or a spatial object with an attribute 'projection'
outname: str
the name of the output file
targetres: tuple
the output resolution in the target SRS; a two-entry tuple is required: (xres, yres)
resampling: str
the resampling algorithm to be used
format: str
the output file format
Returns
-------
"""
if isinstance(rasterobject, str):
rasterobject = Raster(rasterobject)
if not isinstance(rasterobject, Raster):
raise RuntimeError('rasterobject must be of type Raster or str')
if isinstance(reference, (Raster, Vector)):
projection = reference.projection
if targetres is not None:
xres, yres = targetres
elif hasattr(reference, 'res'):
xres, yres = reference.res
else:
raise RuntimeError('parameter targetres is missing and cannot be read from the reference')
elif isinstance(reference, (int, str, osr.SpatialReference)):
try:
projection = crsConvert(reference, 'proj4')
except TypeError:
raise RuntimeError('reference projection cannot be read')
if targetres is None:
raise RuntimeError('parameter targetres is missing and cannot be read from the reference')
else:
xres, yres = targetres
else:
raise TypeError('reference must be of type Raster, Vector, osr.SpatialReference, str or int')
options = {'format': format,
'resampleAlg': resampling,
'xRes': xres,
'yRes': yres,
'srcNodata': rasterobject.nodata,
'dstNodata': rasterobject.nodata,
'dstSRS': projection}
gdalwarp(rasterobject, outname, options) | [
"def",
"reproject",
"(",
"rasterobject",
",",
"reference",
",",
"outname",
",",
"targetres",
"=",
"None",
",",
"resampling",
"=",
"'bilinear'",
",",
"format",
"=",
"'GTiff'",
")",
":",
"if",
"isinstance",
"(",
"rasterobject",
",",
"str",
")",
":",
"rastero... | reproject a raster file
Parameters
----------
rasterobject: Raster or str
the raster image to be reprojected
reference: Raster, Vector, str, int or osr.SpatialReference
either a projection string or a spatial object with an attribute 'projection'
outname: str
the name of the output file
targetres: tuple
the output resolution in the target SRS; a two-entry tuple is required: (xres, yres)
resampling: str
the resampling algorithm to be used
format: str
the output file format
Returns
------- | [
"reproject",
"a",
"raster",
"file"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L980-L1033 | train | 46,230 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.allstats | def allstats(self, approximate=False):
"""
Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a dictionary of statistics for each band. Keys: `min`, `max`, `mean`, `sdev`.
See :osgeo:meth:`gdal.Band.ComputeStatistics`.
"""
statcollect = []
for x in self.layers():
try:
stats = x.ComputeStatistics(approximate)
except RuntimeError:
stats = None
stats = dict(zip(['min', 'max', 'mean', 'sdev'], stats))
statcollect.append(stats)
return statcollect | python | def allstats(self, approximate=False):
"""
Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a dictionary of statistics for each band. Keys: `min`, `max`, `mean`, `sdev`.
See :osgeo:meth:`gdal.Band.ComputeStatistics`.
"""
statcollect = []
for x in self.layers():
try:
stats = x.ComputeStatistics(approximate)
except RuntimeError:
stats = None
stats = dict(zip(['min', 'max', 'mean', 'sdev'], stats))
statcollect.append(stats)
return statcollect | [
"def",
"allstats",
"(",
"self",
",",
"approximate",
"=",
"False",
")",
":",
"statcollect",
"=",
"[",
"]",
"for",
"x",
"in",
"self",
".",
"layers",
"(",
")",
":",
"try",
":",
"stats",
"=",
"x",
".",
"ComputeStatistics",
"(",
"approximate",
")",
"excep... | Compute some basic raster statistics
Parameters
----------
approximate: bool
approximate statistics from overviews or a subset of all tiles?
Returns
-------
list of dicts
a list with a dictionary of statistics for each band. Keys: `min`, `max`, `mean`, `sdev`.
See :osgeo:meth:`gdal.Band.ComputeStatistics`. | [
"Compute",
"some",
"basic",
"raster",
"statistics"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L256-L279 | train | 46,231 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.array | def array(self):
"""
read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data
"""
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().transpose(1, 2, 0)
if isinstance(self.nodata, list):
for i in range(0, self.bands):
arr[:, :, i][arr[:, :, i] == self.nodata[i]] = np.nan
else:
arr[arr == self.nodata] = np.nan
return arr | python | def array(self):
"""
read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data
"""
if self.bands == 1:
return self.matrix()
else:
arr = self.raster.ReadAsArray().transpose(1, 2, 0)
if isinstance(self.nodata, list):
for i in range(0, self.bands):
arr[:, :, i][arr[:, :, i] == self.nodata[i]] = np.nan
else:
arr[arr == self.nodata] = np.nan
return arr | [
"def",
"array",
"(",
"self",
")",
":",
"if",
"self",
".",
"bands",
"==",
"1",
":",
"return",
"self",
".",
"matrix",
"(",
")",
"else",
":",
"arr",
"=",
"self",
".",
"raster",
".",
"ReadAsArray",
"(",
")",
".",
"transpose",
"(",
"1",
",",
"2",
",... | read all raster bands into a numpy ndarray
Returns
-------
numpy.ndarray
the array containing all raster data | [
"read",
"all",
"raster",
"bands",
"into",
"a",
"numpy",
"ndarray"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L281-L299 | train | 46,232 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.bandnames | def bandnames(self, names):
"""
set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
-------
"""
if not isinstance(names, list):
raise TypeError('the names to be set must be of type list')
if len(names) != self.bands:
raise ValueError(
'length mismatch of names to be set ({}) and number of bands ({})'.format(len(names), self.bands))
self.__bandnames = names | python | def bandnames(self, names):
"""
set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
-------
"""
if not isinstance(names, list):
raise TypeError('the names to be set must be of type list')
if len(names) != self.bands:
raise ValueError(
'length mismatch of names to be set ({}) and number of bands ({})'.format(len(names), self.bands))
self.__bandnames = names | [
"def",
"bandnames",
"(",
"self",
",",
"names",
")",
":",
"if",
"not",
"isinstance",
"(",
"names",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'the names to be set must be of type list'",
")",
"if",
"len",
"(",
"names",
")",
"!=",
"self",
".",
"bands... | set the names of the raster bands
Parameters
----------
names: list of str
the names to be set; must be of same length as the number of bands
Returns
------- | [
"set",
"the",
"names",
"of",
"the",
"raster",
"bands"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L341-L359 | train | 46,233 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.extract | def extract(self, px, py, radius=1, nodata=None):
"""
extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coordinate in units of the Raster SRS
radius: int or float
the radius around the point to extract pixel values from; defined as multiples of the pixel resolution
nodata: int
a value to ignore from the computations; If `None`, the nodata value of the Raster object is used
Returns
-------
int or float
the the weighted average of all pixels within the defined radius
"""
if not self.geo['xmin'] <= px <= self.geo['xmax']:
raise RuntimeError('px is out of bounds')
if not self.geo['ymin'] <= py <= self.geo['ymax']:
raise RuntimeError('py is out of bounds')
if nodata is None:
nodata = self.nodata
xres, yres = self.res
hx = xres / 2.0
hy = yres / 2.0
xlim = float(xres * radius)
ylim = float(yres * radius)
# compute minimum x and y pixel coordinates
xmin = int(floor((px - self.geo['xmin'] - xlim) / xres))
ymin = int(floor((self.geo['ymax'] - py - ylim) / yres))
xmin = xmin if xmin >= 0 else 0
ymin = ymin if ymin >= 0 else 0
# compute maximum x and y pixel coordinates
xmax = int(ceil((px - self.geo['xmin'] + xlim) / xres))
ymax = int(ceil((self.geo['ymax'] - py + ylim) / yres))
xmax = xmax if xmax <= self.cols else self.cols
ymax = ymax if ymax <= self.rows else self.rows
# load array subset
if self.__data[0] is not None:
array = self.__data[0][ymin:ymax, xmin:xmax]
# print('using loaded array of size {}, '
# 'indices [{}:{}, {}:{}] (row/y, col/x)'.format(array.shape, ymin, ymax, xmin, xmax))
else:
array = self.raster.GetRasterBand(1).ReadAsArray(xmin, ymin, xmax - xmin, ymax - ymin)
# print('loading array of size {}, '
# 'indices [{}:{}, {}:{}] (row/y, col/x)'.format(array.shape, ymin, ymax, xmin, xmax))
sum = 0
counter = 0
weightsum = 0
for x in range(xmin, xmax):
for y in range(ymin, ymax):
# check whether point is a valid image index
val = array[y - ymin, x - xmin]
if val != nodata:
# compute distances of pixel center coordinate to requested point
xc = x * xres + hx + self.geo['xmin']
yc = self.geo['ymax'] - y * yres + hy
dx = abs(xc - px)
dy = abs(yc - py)
# check whether point lies within ellipse: if ((dx ** 2) / xlim ** 2) + ((dy ** 2) / ylim ** 2) <= 1
weight = sqrt(dx ** 2 + dy ** 2)
sum += val * weight
weightsum += weight
counter += 1
array = None
if counter > 0:
return sum / weightsum
else:
return nodata | python | def extract(self, px, py, radius=1, nodata=None):
"""
extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coordinate in units of the Raster SRS
radius: int or float
the radius around the point to extract pixel values from; defined as multiples of the pixel resolution
nodata: int
a value to ignore from the computations; If `None`, the nodata value of the Raster object is used
Returns
-------
int or float
the the weighted average of all pixels within the defined radius
"""
if not self.geo['xmin'] <= px <= self.geo['xmax']:
raise RuntimeError('px is out of bounds')
if not self.geo['ymin'] <= py <= self.geo['ymax']:
raise RuntimeError('py is out of bounds')
if nodata is None:
nodata = self.nodata
xres, yres = self.res
hx = xres / 2.0
hy = yres / 2.0
xlim = float(xres * radius)
ylim = float(yres * radius)
# compute minimum x and y pixel coordinates
xmin = int(floor((px - self.geo['xmin'] - xlim) / xres))
ymin = int(floor((self.geo['ymax'] - py - ylim) / yres))
xmin = xmin if xmin >= 0 else 0
ymin = ymin if ymin >= 0 else 0
# compute maximum x and y pixel coordinates
xmax = int(ceil((px - self.geo['xmin'] + xlim) / xres))
ymax = int(ceil((self.geo['ymax'] - py + ylim) / yres))
xmax = xmax if xmax <= self.cols else self.cols
ymax = ymax if ymax <= self.rows else self.rows
# load array subset
if self.__data[0] is not None:
array = self.__data[0][ymin:ymax, xmin:xmax]
# print('using loaded array of size {}, '
# 'indices [{}:{}, {}:{}] (row/y, col/x)'.format(array.shape, ymin, ymax, xmin, xmax))
else:
array = self.raster.GetRasterBand(1).ReadAsArray(xmin, ymin, xmax - xmin, ymax - ymin)
# print('loading array of size {}, '
# 'indices [{}:{}, {}:{}] (row/y, col/x)'.format(array.shape, ymin, ymax, xmin, xmax))
sum = 0
counter = 0
weightsum = 0
for x in range(xmin, xmax):
for y in range(ymin, ymax):
# check whether point is a valid image index
val = array[y - ymin, x - xmin]
if val != nodata:
# compute distances of pixel center coordinate to requested point
xc = x * xres + hx + self.geo['xmin']
yc = self.geo['ymax'] - y * yres + hy
dx = abs(xc - px)
dy = abs(yc - py)
# check whether point lies within ellipse: if ((dx ** 2) / xlim ** 2) + ((dy ** 2) / ylim ** 2) <= 1
weight = sqrt(dx ** 2 + dy ** 2)
sum += val * weight
weightsum += weight
counter += 1
array = None
if counter > 0:
return sum / weightsum
else:
return nodata | [
"def",
"extract",
"(",
"self",
",",
"px",
",",
"py",
",",
"radius",
"=",
"1",
",",
"nodata",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"geo",
"[",
"'xmin'",
"]",
"<=",
"px",
"<=",
"self",
".",
"geo",
"[",
"'xmax'",
"]",
":",
"raise",
"... | extract weighted average of pixels intersecting with a defined radius to a point.
Parameters
----------
px: int or float
the x coordinate in units of the Raster SRS
py: int or float
the y coordinate in units of the Raster SRS
radius: int or float
the radius around the point to extract pixel values from; defined as multiples of the pixel resolution
nodata: int
a value to ignore from the computations; If `None`, the nodata value of the Raster object is used
Returns
-------
int or float
the the weighted average of all pixels within the defined radius | [
"extract",
"weighted",
"average",
"of",
"pixels",
"intersecting",
"with",
"a",
"defined",
"radius",
"to",
"a",
"point",
"."
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L446-L535 | train | 46,234 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.geo | def geo(self):
"""
General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`
"""
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
self.raster.GetGeoTransform()))
# note: yres is negative!
out['xmax'] = out['xmin'] + out['xres'] * self.cols
out['ymin'] = out['ymax'] + out['yres'] * self.rows
return out | python | def geo(self):
"""
General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y`
"""
out = dict(zip(['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres'],
self.raster.GetGeoTransform()))
# note: yres is negative!
out['xmax'] = out['xmin'] + out['xres'] * self.cols
out['ymin'] = out['ymax'] + out['yres'] * self.rows
return out | [
"def",
"geo",
"(",
"self",
")",
":",
"out",
"=",
"dict",
"(",
"zip",
"(",
"[",
"'xmin'",
",",
"'xres'",
",",
"'rotation_x'",
",",
"'ymax'",
",",
"'rotation_y'",
",",
"'yres'",
"]",
",",
"self",
".",
"raster",
".",
"GetGeoTransform",
"(",
")",
")",
... | General image geo information.
Returns
-------
dict
a dictionary with keys `xmin`, `xmax`, `xres`, `rotation_x`, `ymin`, `ymax`, `yres`, `rotation_y` | [
"General",
"image",
"geo",
"information",
"."
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L562-L577 | train | 46,235 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.res | def res(self):
"""
the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres)
"""
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | python | def res(self):
"""
the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres)
"""
return (abs(float(self.geo['xres'])), abs(float(self.geo['yres']))) | [
"def",
"res",
"(",
"self",
")",
":",
"return",
"(",
"abs",
"(",
"float",
"(",
"self",
".",
"geo",
"[",
"'xres'",
"]",
")",
")",
",",
"abs",
"(",
"float",
"(",
"self",
".",
"geo",
"[",
"'yres'",
"]",
")",
")",
")"
] | the raster resolution in x and y direction
Returns
-------
tuple
(xres, yres) | [
"the",
"raster",
"resolution",
"in",
"x",
"and",
"y",
"direction"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L721-L730 | train | 46,236 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.rescale | def rescale(self, fun):
"""
perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Raster('filename') as ras:
>>> ras.rescale(lambda x: 10 * x)
"""
if self.bands != 1:
raise ValueError('only single band images are currently supported')
# load array
mat = self.matrix()
# scale values
scaled = fun(mat)
# assign newly computed array to raster object
self.assign(scaled, band=0) | python | def rescale(self, fun):
"""
perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Raster('filename') as ras:
>>> ras.rescale(lambda x: 10 * x)
"""
if self.bands != 1:
raise ValueError('only single band images are currently supported')
# load array
mat = self.matrix()
# scale values
scaled = fun(mat)
# assign newly computed array to raster object
self.assign(scaled, band=0) | [
"def",
"rescale",
"(",
"self",
",",
"fun",
")",
":",
"if",
"self",
".",
"bands",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'only single band images are currently supported'",
")",
"# load array",
"mat",
"=",
"self",
".",
"matrix",
"(",
")",
"# scale values"... | perform raster computations with custom functions and assign them to the existing raster object in memory
Parameters
----------
fun: function
the custom function to compute on the data
Examples
--------
>>> with Raster('filename') as ras:
>>> ras.rescale(lambda x: 10 * x) | [
"perform",
"raster",
"computations",
"with",
"custom",
"functions",
"and",
"assign",
"them",
"to",
"the",
"existing",
"raster",
"object",
"in",
"memory"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L732-L757 | train | 46,237 |
johntruckenbrodt/spatialist | spatialist/raster.py | Raster.write | def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
"""
write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the written file;
data type notations of GDAL (e.g. `Float32`) and numpy (e.g. `int8`) are supported.
format: str
the file format; e.g. 'GTiff'
nodata: int or float
the nodata value to write to the file
compress_tif: bool
if the format is GeoTiff, compress the written file?
overwrite: bool
overwrite an already existing file?
Returns
-------
"""
if os.path.isfile(outname) and not overwrite:
raise RuntimeError('target file already exists')
if format == 'GTiff' and not re.search(r'\.tif[f]*$', outname):
outname += '.tif'
dtype = Dtype(self.dtype if dtype == 'default' else dtype).gdalint
nodata = self.nodata if nodata == 'default' else nodata
options = []
if format == 'GTiff' and compress_tif:
options += ['COMPRESS=DEFLATE', 'PREDICTOR=2']
driver = gdal.GetDriverByName(format)
outDataset = driver.Create(outname, self.cols, self.rows, self.bands, dtype, options)
driver = None
outDataset.SetMetadata(self.raster.GetMetadata())
outDataset.SetGeoTransform([self.geo[x] for x in ['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres']])
if self.projection is not None:
outDataset.SetProjection(self.projection)
for i in range(1, self.bands + 1):
outband = outDataset.GetRasterBand(i)
if nodata is not None:
outband.SetNoDataValue(nodata)
mat = self.matrix(band=i)
dtype_mat = str(mat.dtype)
dtype_ras = Dtype(dtype).numpystr
if not np.can_cast(dtype_mat, dtype_ras):
warnings.warn("writing band {}: unsafe casting from type {} to {}".format(i, dtype_mat, dtype_ras))
outband.WriteArray(mat)
del mat
outband.FlushCache()
outband = None
if format == 'GTiff':
outDataset.SetMetadataItem('TIFFTAG_DATETIME', strftime('%Y:%m:%d %H:%M:%S', gmtime()))
outDataset = None
if format == 'ENVI':
hdrfile = os.path.splitext(outname)[0] + '.hdr'
with HDRobject(hdrfile) as hdr:
hdr.band_names = self.bandnames
hdr.write() | python | def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
"""
write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the written file;
data type notations of GDAL (e.g. `Float32`) and numpy (e.g. `int8`) are supported.
format: str
the file format; e.g. 'GTiff'
nodata: int or float
the nodata value to write to the file
compress_tif: bool
if the format is GeoTiff, compress the written file?
overwrite: bool
overwrite an already existing file?
Returns
-------
"""
if os.path.isfile(outname) and not overwrite:
raise RuntimeError('target file already exists')
if format == 'GTiff' and not re.search(r'\.tif[f]*$', outname):
outname += '.tif'
dtype = Dtype(self.dtype if dtype == 'default' else dtype).gdalint
nodata = self.nodata if nodata == 'default' else nodata
options = []
if format == 'GTiff' and compress_tif:
options += ['COMPRESS=DEFLATE', 'PREDICTOR=2']
driver = gdal.GetDriverByName(format)
outDataset = driver.Create(outname, self.cols, self.rows, self.bands, dtype, options)
driver = None
outDataset.SetMetadata(self.raster.GetMetadata())
outDataset.SetGeoTransform([self.geo[x] for x in ['xmin', 'xres', 'rotation_x', 'ymax', 'rotation_y', 'yres']])
if self.projection is not None:
outDataset.SetProjection(self.projection)
for i in range(1, self.bands + 1):
outband = outDataset.GetRasterBand(i)
if nodata is not None:
outband.SetNoDataValue(nodata)
mat = self.matrix(band=i)
dtype_mat = str(mat.dtype)
dtype_ras = Dtype(dtype).numpystr
if not np.can_cast(dtype_mat, dtype_ras):
warnings.warn("writing band {}: unsafe casting from type {} to {}".format(i, dtype_mat, dtype_ras))
outband.WriteArray(mat)
del mat
outband.FlushCache()
outband = None
if format == 'GTiff':
outDataset.SetMetadataItem('TIFFTAG_DATETIME', strftime('%Y:%m:%d %H:%M:%S', gmtime()))
outDataset = None
if format == 'ENVI':
hdrfile = os.path.splitext(outname)[0] + '.hdr'
with HDRobject(hdrfile) as hdr:
hdr.band_names = self.bandnames
hdr.write() | [
"def",
"write",
"(",
"self",
",",
"outname",
",",
"dtype",
"=",
"'default'",
",",
"format",
"=",
"'ENVI'",
",",
"nodata",
"=",
"'default'",
",",
"compress_tif",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"is... | write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the written file;
data type notations of GDAL (e.g. `Float32`) and numpy (e.g. `int8`) are supported.
format: str
the file format; e.g. 'GTiff'
nodata: int or float
the nodata value to write to the file
compress_tif: bool
if the format is GeoTiff, compress the written file?
overwrite: bool
overwrite an already existing file?
Returns
------- | [
"write",
"the",
"raster",
"object",
"to",
"a",
"file",
"."
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L781-L846 | train | 46,238 |
johntruckenbrodt/spatialist | spatialist/raster.py | Dtype.numpy2gdalint | def numpy2gdalint(self):
"""
create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map
"""
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'uint', 'float', 'complex']:
for dtype in np.sctypes[group]:
code = gdal_array.NumericTypeCodeToGDALTypeCode(dtype)
if code is not None:
tmap[dtype().dtype.name] = code
self.__numpy2gdalint = tmap
return self.__numpy2gdalint | python | def numpy2gdalint(self):
"""
create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map
"""
if not hasattr(self, '__numpy2gdalint'):
tmap = {}
for group in ['int', 'uint', 'float', 'complex']:
for dtype in np.sctypes[group]:
code = gdal_array.NumericTypeCodeToGDALTypeCode(dtype)
if code is not None:
tmap[dtype().dtype.name] = code
self.__numpy2gdalint = tmap
return self.__numpy2gdalint | [
"def",
"numpy2gdalint",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'__numpy2gdalint'",
")",
":",
"tmap",
"=",
"{",
"}",
"for",
"group",
"in",
"[",
"'int'",
",",
"'uint'",
",",
"'float'",
",",
"'complex'",
"]",
":",
"for",
"dtyp... | create a dictionary for mapping numpy data types to GDAL data type codes
Returns
-------
dict
the type map | [
"create",
"a",
"dictionary",
"for",
"mapping",
"numpy",
"data",
"types",
"to",
"GDAL",
"data",
"type",
"codes"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/raster.py#L1281-L1299 | train | 46,239 |
svenkreiss/databench | databench/app.py | App.static_parser | def static_parser(static):
"""Parse object describing static routes.
Might be a list, a dict or a list of dicts.
"""
if static is None:
return
if isinstance(static, dict):
static = static.items()
for group in static:
if not isinstance(group, dict):
yield group
continue
for item in group.items():
yield item | python | def static_parser(static):
"""Parse object describing static routes.
Might be a list, a dict or a list of dicts.
"""
if static is None:
return
if isinstance(static, dict):
static = static.items()
for group in static:
if not isinstance(group, dict):
yield group
continue
for item in group.items():
yield item | [
"def",
"static_parser",
"(",
"static",
")",
":",
"if",
"static",
"is",
"None",
":",
"return",
"if",
"isinstance",
"(",
"static",
",",
"dict",
")",
":",
"static",
"=",
"static",
".",
"items",
"(",
")",
"for",
"group",
"in",
"static",
":",
"if",
"not",... | Parse object describing static routes.
Might be a list, a dict or a list of dicts. | [
"Parse",
"object",
"describing",
"static",
"routes",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L102-L119 | train | 46,240 |
svenkreiss/databench | databench/app.py | App.analyses_info | def analyses_info(self):
"""Add analyses from the analyses folder."""
f_config = os.path.join(self.analyses_path, 'index.yaml')
tornado.autoreload.watch(f_config)
with io.open(f_config, 'r', encoding='utf8') as f:
config = yaml.safe_load(f)
self.info.update(config)
if self.debug:
self.info['version'] += '.debug-{:04X}'.format(
int(random.random() * 0xffff))
readme = Readme(self.analyses_path)
if self.info['description'] is None:
self.info['description'] = readme.text.strip()
self.info['description_html'] = readme.html | python | def analyses_info(self):
"""Add analyses from the analyses folder."""
f_config = os.path.join(self.analyses_path, 'index.yaml')
tornado.autoreload.watch(f_config)
with io.open(f_config, 'r', encoding='utf8') as f:
config = yaml.safe_load(f)
self.info.update(config)
if self.debug:
self.info['version'] += '.debug-{:04X}'.format(
int(random.random() * 0xffff))
readme = Readme(self.analyses_path)
if self.info['description'] is None:
self.info['description'] = readme.text.strip()
self.info['description_html'] = readme.html | [
"def",
"analyses_info",
"(",
"self",
")",
":",
"f_config",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"analyses_path",
",",
"'index.yaml'",
")",
"tornado",
".",
"autoreload",
".",
"watch",
"(",
"f_config",
")",
"with",
"io",
".",
"open",
"(... | Add analyses from the analyses folder. | [
"Add",
"analyses",
"from",
"the",
"analyses",
"folder",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L187-L201 | train | 46,241 |
svenkreiss/databench | databench/app.py | App.build | def build(self):
"""Run the build command specified in index.yaml."""
for cmd in self.build_cmds:
log.info('building command: {}'.format(cmd))
full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)
log.debug('full command: {}'.format(full_cmd))
subprocess.call(full_cmd, shell=True)
log.info('build done') | python | def build(self):
"""Run the build command specified in index.yaml."""
for cmd in self.build_cmds:
log.info('building command: {}'.format(cmd))
full_cmd = 'cd {}; {}'.format(self.analyses_path, cmd)
log.debug('full command: {}'.format(full_cmd))
subprocess.call(full_cmd, shell=True)
log.info('build done') | [
"def",
"build",
"(",
"self",
")",
":",
"for",
"cmd",
"in",
"self",
".",
"build_cmds",
":",
"log",
".",
"info",
"(",
"'building command: {}'",
".",
"format",
"(",
"cmd",
")",
")",
"full_cmd",
"=",
"'cd {}; {}'",
".",
"format",
"(",
"self",
".",
"analyse... | Run the build command specified in index.yaml. | [
"Run",
"the",
"build",
"command",
"specified",
"in",
"index",
".",
"yaml",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L345-L352 | train | 46,242 |
svenkreiss/databench | databench/app.py | IndexHandler.get | def get(self):
"""Render the List-of-Analyses overview page."""
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | python | def get(self):
"""Render the List-of-Analyses overview page."""
return self.render(
'index.html',
databench_version=DATABENCH_VERSION,
meta_infos=self.meta_infos(),
**self.info
) | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"self",
".",
"render",
"(",
"'index.html'",
",",
"databench_version",
"=",
"DATABENCH_VERSION",
",",
"meta_infos",
"=",
"self",
".",
"meta_infos",
"(",
")",
",",
"*",
"*",
"self",
".",
"info",
")"
] | Render the List-of-Analyses overview page. | [
"Render",
"the",
"List",
"-",
"of",
"-",
"Analyses",
"overview",
"page",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/app.py#L386-L393 | train | 46,243 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bpp.py | _init_worker | def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | python | def _init_worker(X, X_shape, X_dtype):
"""Initializer for pool for _mprotate"""
# Using a dictionary is not strictly necessary. You can also
# use global variables.
mprotate_dict["X"] = X
mprotate_dict["X_shape"] = X_shape
mprotate_dict["X_dtype"] = X_dtype | [
"def",
"_init_worker",
"(",
"X",
",",
"X_shape",
",",
"X_dtype",
")",
":",
"# Using a dictionary is not strictly necessary. You can also",
"# use global variables.",
"mprotate_dict",
"[",
"\"X\"",
"]",
"=",
"X",
"mprotate_dict",
"[",
"\"X_shape\"",
"]",
"=",
"X_shape",
... | Initializer for pool for _mprotate | [
"Initializer",
"for",
"pool",
"for",
"_mprotate"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bpp.py#L26-L32 | train | 46,244 |
RI-imaging/ODTbrain | odtbrain/_alg3d_bpp.py | _mprotate | def _mprotate(ang, lny, pool, order):
"""Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle in degrees
lny: int
total number of rotations to perform
pool: instance of multiprocessing.pool.Pool
the pool object used for the computation
order: int
interpolation order
"""
targ_args = list()
slsize = np.int(np.floor(lny / ncores))
for t in range(ncores):
ymin = t * slsize
ymax = (t + 1) * slsize
if t == ncores - 1:
ymax = lny
targ_args.append((ymin, ymax, ang, order))
pool.map(_rotate, targ_args) | python | def _mprotate(ang, lny, pool, order):
"""Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle in degrees
lny: int
total number of rotations to perform
pool: instance of multiprocessing.pool.Pool
the pool object used for the computation
order: int
interpolation order
"""
targ_args = list()
slsize = np.int(np.floor(lny / ncores))
for t in range(ncores):
ymin = t * slsize
ymax = (t + 1) * slsize
if t == ncores - 1:
ymax = lny
targ_args.append((ymin, ymax, ang, order))
pool.map(_rotate, targ_args) | [
"def",
"_mprotate",
"(",
"ang",
",",
"lny",
",",
"pool",
",",
"order",
")",
":",
"targ_args",
"=",
"list",
"(",
")",
"slsize",
"=",
"np",
".",
"int",
"(",
"np",
".",
"floor",
"(",
"lny",
"/",
"ncores",
")",
")",
"for",
"t",
"in",
"range",
"(",
... | Uses multiprocessing to wrap around _rotate
4x speedup on an intel i7-3820 CPU @ 3.60GHz with 8 cores.
The function calls _rotate which accesses the `mprotate_dict`.
Data is rotated in-place.
Parameters
----------
ang: float
rotation angle in degrees
lny: int
total number of rotations to perform
pool: instance of multiprocessing.pool.Pool
the pool object used for the computation
order: int
interpolation order | [
"Uses",
"multiprocessing",
"to",
"wrap",
"around",
"_rotate"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_alg3d_bpp.py#L35-L65 | train | 46,245 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.write_byte | def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | python | def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | [
"def",
"write_byte",
"(",
"self",
",",
"address",
",",
"value",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Writing byte %s to device %s!\"",
",",
"bin",
"(",
"value",
")",
",",
"hex",
"(",
"address",
")",
")",
"return",
"self",
".",
"driver",
".",
"write_... | Writes the byte to unaddressed register in a device. | [
"Writes",
"the",
"byte",
"to",
"unaddressed",
"register",
"in",
"a",
"device",
"."
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L209-L212 | train | 46,246 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.read_byte | def read_byte(self, address):
"""Reads unadressed byte from a device. """
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | python | def read_byte(self, address):
"""Reads unadressed byte from a device. """
LOGGER.debug("Reading byte from device %s!", hex(address))
return self.driver.read_byte(address) | [
"def",
"read_byte",
"(",
"self",
",",
"address",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Reading byte from device %s!\"",
",",
"hex",
"(",
"address",
")",
")",
"return",
"self",
".",
"driver",
".",
"read_byte",
"(",
"address",
")"
] | Reads unadressed byte from a device. | [
"Reads",
"unadressed",
"byte",
"from",
"a",
"device",
"."
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L214-L217 | train | 46,247 |
MLAB-project/pymlab | src/pymlab/sensors/__init__.py | Bus.write_byte_data | def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | python | def write_byte_data(self, address, register, value):
"""Write a byte value to a device's register. """
LOGGER.debug("Writing byte data %s to register %s on device %s",
bin(value), hex(register), hex(address))
return self.driver.write_byte_data(address, register, value) | [
"def",
"write_byte_data",
"(",
"self",
",",
"address",
",",
"register",
",",
"value",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Writing byte data %s to register %s on device %s\"",
",",
"bin",
"(",
"value",
")",
",",
"hex",
"(",
"register",
")",
",",
"hex",
... | Write a byte value to a device's register. | [
"Write",
"a",
"byte",
"value",
"to",
"a",
"device",
"s",
"register",
"."
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/__init__.py#L219-L223 | train | 46,248 |
python-astrodynamics/spacetrack | spacetrack/aio.py | _raise_for_status | async def _raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This function was taken from the aslack project and modified. The original
copyright notice:
Copyright (c) 2015, Jonathan Sharpe
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
try:
response.raise_for_status()
except aiohttp.ClientResponseError as exc:
reason = response.reason
spacetrack_error_msg = None
try:
json = await response.json()
if isinstance(json, Mapping):
spacetrack_error_msg = json['error']
except (ValueError, KeyError, aiohttp.ClientResponseError):
pass
if not spacetrack_error_msg:
spacetrack_error_msg = await response.text()
if spacetrack_error_msg:
reason += '\nSpace-Track response:\n' + spacetrack_error_msg
payload = dict(
code=response.status,
message=reason,
headers=response.headers,
)
# history attribute is only aiohttp >= 2.1
try:
payload['history'] = exc.history
except AttributeError:
pass
raise aiohttp.ClientResponseError(**payload) | python | async def _raise_for_status(response):
"""Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This function was taken from the aslack project and modified. The original
copyright notice:
Copyright (c) 2015, Jonathan Sharpe
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
try:
response.raise_for_status()
except aiohttp.ClientResponseError as exc:
reason = response.reason
spacetrack_error_msg = None
try:
json = await response.json()
if isinstance(json, Mapping):
spacetrack_error_msg = json['error']
except (ValueError, KeyError, aiohttp.ClientResponseError):
pass
if not spacetrack_error_msg:
spacetrack_error_msg = await response.text()
if spacetrack_error_msg:
reason += '\nSpace-Track response:\n' + spacetrack_error_msg
payload = dict(
code=response.status,
message=reason,
headers=response.headers,
)
# history attribute is only aiohttp >= 2.1
try:
payload['history'] = exc.history
except AttributeError:
pass
raise aiohttp.ClientResponseError(**payload) | [
"async",
"def",
"_raise_for_status",
"(",
"response",
")",
":",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"except",
"aiohttp",
".",
"ClientResponseError",
"as",
"exc",
":",
"reason",
"=",
"response",
".",
"reason",
"spacetrack_error_msg",
"=",
... | Raise an appropriate error for a given response.
Arguments:
response (:py:class:`aiohttp.ClientResponse`): The API response.
Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate
error for the response's status.
This function was taken from the aslack project and modified. The original
copyright notice:
Copyright (c) 2015, Jonathan Sharpe
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | [
"Raise",
"an",
"appropriate",
"error",
"for",
"a",
"given",
"response",
"."
] | 18f63b7de989a31b983d140a11418e01bd6fd398 | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L349-L409 | train | 46,249 |
python-astrodynamics/spacetrack | spacetrack/aio.py | AsyncSpaceTrackClient.generic_request | async def generic_request(self, class_, iter_lines=False, iter_content=False,
controller=None, parse_types=False, **kwargs):
"""Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code-block:: python
st.tle_publish(*args, **st)
st.basicspacedata.tle_publish(*args, **st)
st.file(*args, **st)
st.fileshare.file(*args, **st)
st.spephemeris.file(*args, **st)
They resolve to the following calls respectively:
.. code-block:: python
st.generic_request('tle_publish', *args, **st)
st.generic_request('tle_publish', *args, controller='basicspacedata', **st)
st.generic_request('file', *args, **st)
st.generic_request('file', *args, controller='fileshare', **st)
st.generic_request('file', *args, controller='spephemeris', **st)
Parameters:
class_: Space-Track request class name
iter_lines: Yield result line by line
iter_content: Yield result in 100 KiB chunks.
controller: Optionally specify request controller to use.
parse_types: Parse string values in response according to type given
in predicate information, e.g. ``'2017-01-01'`` ->
``datetime.date(2017, 1, 1)``.
**kwargs: These keywords must match the predicate fields on
Space-Track. You may check valid keywords with the following
snippet:
.. code-block:: python
spacetrack = AsyncSpaceTrackClient(...)
await spacetrack.tle.get_predicates()
# or
await spacetrack.get_predicates('tle')
See :func:`~spacetrack.operators._stringify_predicate_value` for
which Python objects are converted appropriately.
Yields:
Lines—stripped of newline characters—if ``iter_lines=True``
Yields:
100 KiB chunks if ``iter_content=True``
Returns:
Parsed JSON object, unless ``format`` keyword argument is passed.
.. warning::
Passing ``format='json'`` will return the JSON **unparsed**. Do
not set ``format`` if you want the parsed JSON object returned!
"""
if iter_lines and iter_content:
raise ValueError('iter_lines and iter_content cannot both be True')
if 'format' in kwargs and parse_types:
raise ValueError('parse_types can only be used if format is unset.')
if controller is None:
controller = self._find_controller(class_)
else:
classes = self.request_controllers.get(controller, None)
if classes is None:
raise ValueError(
'Unknown request controller {!r}'.format(controller))
if class_ not in classes:
raise ValueError(
'Unknown request class {!r} for controller {!r}'
.format(class_, controller))
# Decode unicode unless class == download, including conversion of
# CRLF newlines to LF.
decode = (class_ != 'download')
if not decode and iter_lines:
error = (
'iter_lines disabled for binary data, since CRLF newlines '
'split over chunk boundaries would yield extra blank lines. '
'Use iter_content=True instead.')
raise ValueError(error)
await self.authenticate()
url = ('{0}{1}/query/class/{2}'
.format(self.base_url, controller, class_))
offline_check = (class_, controller) in self.offline_predicates
valid_fields = {p.name for p in self.rest_predicates}
predicates = None
if not offline_check:
predicates = await self.get_predicates(class_)
predicate_fields = {p.name for p in predicates}
valid_fields = predicate_fields | {p.name for p in self.rest_predicates}
else:
valid_fields |= self.offline_predicates[(class_, controller)]
for key, value in kwargs.items():
if key not in valid_fields:
raise TypeError(
"'{class_}' got an unexpected argument '{key}'"
.format(class_=class_, key=key))
value = _stringify_predicate_value(value)
url += '/{key}/{value}'.format(key=key, value=value)
logger.debug(url)
resp = await self._ratelimited_get(url)
await _raise_for_status(resp)
if iter_lines:
return _AsyncLineIterator(resp, decode_unicode=decode)
elif iter_content:
return _AsyncChunkIterator(resp, decode_unicode=decode)
else:
# If format is specified, return that format unparsed. Otherwise,
# parse the default JSON response.
if 'format' in kwargs:
if decode:
# Replace CRLF newlines with LF, Python will handle platform
# specific newlines if written to file.
data = await resp.text()
data = data.replace('\r', '')
else:
data = await resp.read()
return data
else:
data = await resp.json()
if predicates is None or not parse_types:
return data
else:
return self._parse_types(data, predicates) | python | async def generic_request(self, class_, iter_lines=False, iter_content=False,
controller=None, parse_types=False, **kwargs):
"""Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code-block:: python
st.tle_publish(*args, **st)
st.basicspacedata.tle_publish(*args, **st)
st.file(*args, **st)
st.fileshare.file(*args, **st)
st.spephemeris.file(*args, **st)
They resolve to the following calls respectively:
.. code-block:: python
st.generic_request('tle_publish', *args, **st)
st.generic_request('tle_publish', *args, controller='basicspacedata', **st)
st.generic_request('file', *args, **st)
st.generic_request('file', *args, controller='fileshare', **st)
st.generic_request('file', *args, controller='spephemeris', **st)
Parameters:
class_: Space-Track request class name
iter_lines: Yield result line by line
iter_content: Yield result in 100 KiB chunks.
controller: Optionally specify request controller to use.
parse_types: Parse string values in response according to type given
in predicate information, e.g. ``'2017-01-01'`` ->
``datetime.date(2017, 1, 1)``.
**kwargs: These keywords must match the predicate fields on
Space-Track. You may check valid keywords with the following
snippet:
.. code-block:: python
spacetrack = AsyncSpaceTrackClient(...)
await spacetrack.tle.get_predicates()
# or
await spacetrack.get_predicates('tle')
See :func:`~spacetrack.operators._stringify_predicate_value` for
which Python objects are converted appropriately.
Yields:
Lines—stripped of newline characters—if ``iter_lines=True``
Yields:
100 KiB chunks if ``iter_content=True``
Returns:
Parsed JSON object, unless ``format`` keyword argument is passed.
.. warning::
Passing ``format='json'`` will return the JSON **unparsed**. Do
not set ``format`` if you want the parsed JSON object returned!
"""
if iter_lines and iter_content:
raise ValueError('iter_lines and iter_content cannot both be True')
if 'format' in kwargs and parse_types:
raise ValueError('parse_types can only be used if format is unset.')
if controller is None:
controller = self._find_controller(class_)
else:
classes = self.request_controllers.get(controller, None)
if classes is None:
raise ValueError(
'Unknown request controller {!r}'.format(controller))
if class_ not in classes:
raise ValueError(
'Unknown request class {!r} for controller {!r}'
.format(class_, controller))
# Decode unicode unless class == download, including conversion of
# CRLF newlines to LF.
decode = (class_ != 'download')
if not decode and iter_lines:
error = (
'iter_lines disabled for binary data, since CRLF newlines '
'split over chunk boundaries would yield extra blank lines. '
'Use iter_content=True instead.')
raise ValueError(error)
await self.authenticate()
url = ('{0}{1}/query/class/{2}'
.format(self.base_url, controller, class_))
offline_check = (class_, controller) in self.offline_predicates
valid_fields = {p.name for p in self.rest_predicates}
predicates = None
if not offline_check:
predicates = await self.get_predicates(class_)
predicate_fields = {p.name for p in predicates}
valid_fields = predicate_fields | {p.name for p in self.rest_predicates}
else:
valid_fields |= self.offline_predicates[(class_, controller)]
for key, value in kwargs.items():
if key not in valid_fields:
raise TypeError(
"'{class_}' got an unexpected argument '{key}'"
.format(class_=class_, key=key))
value = _stringify_predicate_value(value)
url += '/{key}/{value}'.format(key=key, value=value)
logger.debug(url)
resp = await self._ratelimited_get(url)
await _raise_for_status(resp)
if iter_lines:
return _AsyncLineIterator(resp, decode_unicode=decode)
elif iter_content:
return _AsyncChunkIterator(resp, decode_unicode=decode)
else:
# If format is specified, return that format unparsed. Otherwise,
# parse the default JSON response.
if 'format' in kwargs:
if decode:
# Replace CRLF newlines with LF, Python will handle platform
# specific newlines if written to file.
data = await resp.text()
data = data.replace('\r', '')
else:
data = await resp.read()
return data
else:
data = await resp.json()
if predicates is None or not parse_types:
return data
else:
return self._parse_types(data, predicates) | [
"async",
"def",
"generic_request",
"(",
"self",
",",
"class_",
",",
"iter_lines",
"=",
"False",
",",
"iter_content",
"=",
"False",
",",
"controller",
"=",
"None",
",",
"parse_types",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"iter_lines",
"a... | Generic Space-Track query coroutine.
The request class methods use this method internally; the public
API is as follows:
.. code-block:: python
st.tle_publish(*args, **st)
st.basicspacedata.tle_publish(*args, **st)
st.file(*args, **st)
st.fileshare.file(*args, **st)
st.spephemeris.file(*args, **st)
They resolve to the following calls respectively:
.. code-block:: python
st.generic_request('tle_publish', *args, **st)
st.generic_request('tle_publish', *args, controller='basicspacedata', **st)
st.generic_request('file', *args, **st)
st.generic_request('file', *args, controller='fileshare', **st)
st.generic_request('file', *args, controller='spephemeris', **st)
Parameters:
class_: Space-Track request class name
iter_lines: Yield result line by line
iter_content: Yield result in 100 KiB chunks.
controller: Optionally specify request controller to use.
parse_types: Parse string values in response according to type given
in predicate information, e.g. ``'2017-01-01'`` ->
``datetime.date(2017, 1, 1)``.
**kwargs: These keywords must match the predicate fields on
Space-Track. You may check valid keywords with the following
snippet:
.. code-block:: python
spacetrack = AsyncSpaceTrackClient(...)
await spacetrack.tle.get_predicates()
# or
await spacetrack.get_predicates('tle')
See :func:`~spacetrack.operators._stringify_predicate_value` for
which Python objects are converted appropriately.
Yields:
Lines—stripped of newline characters—if ``iter_lines=True``
Yields:
100 KiB chunks if ``iter_content=True``
Returns:
Parsed JSON object, unless ``format`` keyword argument is passed.
.. warning::
Passing ``format='json'`` will return the JSON **unparsed**. Do
not set ``format`` if you want the parsed JSON object returned! | [
"Generic",
"Space",
"-",
"Track",
"query",
"coroutine",
"."
] | 18f63b7de989a31b983d140a11418e01bd6fd398 | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L70-L213 | train | 46,250 |
vladsaveliev/TargQC | targqc/utilz/utils.py | get_numeric_value | def get_numeric_value(string_value):
""" parses string_value and returns only number-like part
"""
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | python | def get_numeric_value(string_value):
""" parses string_value and returns only number-like part
"""
num_chars = ['.', '+', '-']
number = ''
for c in string_value:
if c.isdigit() or c in num_chars:
number += c
return number | [
"def",
"get_numeric_value",
"(",
"string_value",
")",
":",
"num_chars",
"=",
"[",
"'.'",
",",
"'+'",
",",
"'-'",
"]",
"number",
"=",
"''",
"for",
"c",
"in",
"string_value",
":",
"if",
"c",
".",
"isdigit",
"(",
")",
"or",
"c",
"in",
"num_chars",
":",
... | parses string_value and returns only number-like part | [
"parses",
"string_value",
"and",
"returns",
"only",
"number",
"-",
"like",
"part"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/utils.py#L83-L91 | train | 46,251 |
svenkreiss/databench | databench/cli.py | run | def run(analysis, path=None, name=None, info=None, **kwargs):
"""Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
``readme``, ...
:param dict static: Map[url regex, root-folder] to serve static content.
"""
kwargs.update({
'analysis': analysis,
'path': path,
'name': name,
'info': info,
})
main(**kwargs) | python | def run(analysis, path=None, name=None, info=None, **kwargs):
"""Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
``readme``, ...
:param dict static: Map[url regex, root-folder] to serve static content.
"""
kwargs.update({
'analysis': analysis,
'path': path,
'name': name,
'info': info,
})
main(**kwargs) | [
"def",
"run",
"(",
"analysis",
",",
"path",
"=",
"None",
",",
"name",
"=",
"None",
",",
"info",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'analysis'",
":",
"analysis",
",",
"'path'",
":",
"path",
",",
"'n... | Run a single analysis.
:param Analysis analysis: Analysis class to run.
:param str path: Path of analysis. Can be `__file__`.
:param str name: Name of the analysis.
:param dict info: Optional entries are ``version``, ``title``,
``readme``, ...
:param dict static: Map[url regex, root-folder] to serve static content. | [
"Run",
"a",
"single",
"analysis",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/cli.py#L126-L142 | train | 46,252 |
python-astrodynamics/spacetrack | spacetrack/operators.py | _stringify_predicate_value | def _stringify_predicate_value(value):
"""Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'``
"""
if isinstance(value, bool):
return str(value).lower()
elif isinstance(value, Sequence) and not isinstance(value, six.string_types):
return ','.join(_stringify_predicate_value(x) for x in value)
elif isinstance(value, datetime.datetime):
return value.isoformat(sep=' ')
elif isinstance(value, datetime.date):
return value.isoformat()
elif value is None:
return 'null-val'
else:
return str(value) | python | def _stringify_predicate_value(value):
"""Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'``
"""
if isinstance(value, bool):
return str(value).lower()
elif isinstance(value, Sequence) and not isinstance(value, six.string_types):
return ','.join(_stringify_predicate_value(x) for x in value)
elif isinstance(value, datetime.datetime):
return value.isoformat(sep=' ')
elif isinstance(value, datetime.date):
return value.isoformat()
elif value is None:
return 'null-val'
else:
return str(value) | [
"def",
"_stringify_predicate_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"str",
"(",
"value",
")",
".",
"lower",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"Sequence",
")",
"and",
"not",
"i... | Convert Python objects to Space-Track compatible strings
- Booleans (``True`` -> ``'true'``)
- Sequences (``[25544, 34602]`` -> ``'25544,34602'``)
- dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)
- ``None`` -> ``'null-val'`` | [
"Convert",
"Python",
"objects",
"to",
"Space",
"-",
"Track",
"compatible",
"strings"
] | 18f63b7de989a31b983d140a11418e01bd6fd398 | https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/operators.py#L45-L64 | train | 46,253 |
MLAB-project/pymlab | src/pymlab/utils.py | args_repr | def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("abc"))
"'a', (1, 2), some_keyword = ['a', 'b', 'c']"
"""
items = [repr(a) for a in args]
items += ["%s = %r" % (k, v) for k, v in iter(kwargs.items())]
return ", ".join(items) | python | def args_repr(*args, **kwargs):
"""
Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("abc"))
"'a', (1, 2), some_keyword = ['a', 'b', 'c']"
"""
items = [repr(a) for a in args]
items += ["%s = %r" % (k, v) for k, v in iter(kwargs.items())]
return ", ".join(items) | [
"def",
"args_repr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
"=",
"[",
"repr",
"(",
"a",
")",
"for",
"a",
"in",
"args",
"]",
"items",
"+=",
"[",
"\"%s = %r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"... | Returns human-readable string representation of both positional and
keyword arguments passed to the function.
This function uses the built-in :func:`repr()` function to convert
individual arguments to string.
>>> args_repr("a", (1, 2), some_keyword = list("abc"))
"'a', (1, 2), some_keyword = ['a', 'b', 'c']" | [
"Returns",
"human",
"-",
"readable",
"string",
"representation",
"of",
"both",
"positional",
"and",
"keyword",
"arguments",
"passed",
"to",
"the",
"function",
"."
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/utils.py#L12-L25 | train | 46,254 |
MLAB-project/pymlab | src/pymlab/utils.py | obj_repr | def obj_repr(obj, *args, **kwargs):
"""
Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:
>>> class Animal(object):
... def __init__(self, hit_points, color, **kwargs):
... self.hit_points = hit_points
... self.color = color
... self.hostile = kwargs.get("hostile", False)
... def __repr__(self):
... return obj_repr(self, self.hit_points, self.color, hostile = self.hostile)
>>> dog = Animal(2.3, "purple")
>>> repr(dog)
"Animal(2.3, 'purple', hostile = False)"
"""
cls_name = type(obj).__name__
return "%s(%s)" % (cls_name, args_repr(*args, **kwargs), ) | python | def obj_repr(obj, *args, **kwargs):
"""
Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:
>>> class Animal(object):
... def __init__(self, hit_points, color, **kwargs):
... self.hit_points = hit_points
... self.color = color
... self.hostile = kwargs.get("hostile", False)
... def __repr__(self):
... return obj_repr(self, self.hit_points, self.color, hostile = self.hostile)
>>> dog = Animal(2.3, "purple")
>>> repr(dog)
"Animal(2.3, 'purple', hostile = False)"
"""
cls_name = type(obj).__name__
return "%s(%s)" % (cls_name, args_repr(*args, **kwargs), ) | [
"def",
"obj_repr",
"(",
"obj",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls_name",
"=",
"type",
"(",
"obj",
")",
".",
"__name__",
"return",
"\"%s(%s)\"",
"%",
"(",
"cls_name",
",",
"args_repr",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs"... | Returns human-readable string representation of an object given that it has
been created by calling constructor with the specified positional and
keyword arguments.
This is a convenience function to help implement custom `__repr__()`
methods. For example:
>>> class Animal(object):
... def __init__(self, hit_points, color, **kwargs):
... self.hit_points = hit_points
... self.color = color
... self.hostile = kwargs.get("hostile", False)
... def __repr__(self):
... return obj_repr(self, self.hit_points, self.color, hostile = self.hostile)
>>> dog = Animal(2.3, "purple")
>>> repr(dog)
"Animal(2.3, 'purple', hostile = False)" | [
"Returns",
"human",
"-",
"readable",
"string",
"representation",
"of",
"an",
"object",
"given",
"that",
"it",
"has",
"been",
"created",
"by",
"calling",
"constructor",
"with",
"the",
"specified",
"positional",
"and",
"keyword",
"arguments",
"."
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/utils.py#L28-L49 | train | 46,255 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | dictmerge | def dictmerge(x, y):
"""
merge two dictionaries
"""
z = x.copy()
z.update(y)
return z | python | def dictmerge(x, y):
"""
merge two dictionaries
"""
z = x.copy()
z.update(y)
return z | [
"def",
"dictmerge",
"(",
"x",
",",
"y",
")",
":",
"z",
"=",
"x",
".",
"copy",
"(",
")",
"z",
".",
"update",
"(",
"y",
")",
"return",
"z"
] | merge two dictionaries | [
"merge",
"two",
"dictionaries"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L85-L91 | train | 46,256 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | parse_literal | def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_literal('1.5'), float)
True
>>> isinstance(parse_literal('1'), int)
True
>>> isinstance(parse_literal('foobar'), str)
True
"""
if isinstance(x, list):
return [parse_literal(y) for y in x]
elif isinstance(x, (bytes, str)):
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return x
else:
raise TypeError('input must be a string or a list of strings') | python | def parse_literal(x):
"""
return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_literal('1.5'), float)
True
>>> isinstance(parse_literal('1'), int)
True
>>> isinstance(parse_literal('foobar'), str)
True
"""
if isinstance(x, list):
return [parse_literal(y) for y in x]
elif isinstance(x, (bytes, str)):
try:
return int(x)
except ValueError:
try:
return float(x)
except ValueError:
return x
else:
raise TypeError('input must be a string or a list of strings') | [
"def",
"parse_literal",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"[",
"parse_literal",
"(",
"y",
")",
"for",
"y",
"in",
"x",
"]",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"bytes",
",",
"str",
")",
")",
... | return the smallest possible data type for a string or list of strings
Parameters
----------
x: str or list
a string to be parsed
Returns
-------
int, float or str
the parsing result
Examples
--------
>>> isinstance(parse_literal('1.5'), float)
True
>>> isinstance(parse_literal('1'), int)
True
>>> isinstance(parse_literal('foobar'), str)
True | [
"return",
"the",
"smallest",
"possible",
"data",
"type",
"for",
"a",
"string",
"or",
"list",
"of",
"strings"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L399-L435 | train | 46,257 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | urlQueryParser | def urlQueryParser(url, querydict):
"""
parse a url query
"""
address_parse = urlparse(url)
return urlunparse(address_parse._replace(query=urlencode(querydict))) | python | def urlQueryParser(url, querydict):
"""
parse a url query
"""
address_parse = urlparse(url)
return urlunparse(address_parse._replace(query=urlencode(querydict))) | [
"def",
"urlQueryParser",
"(",
"url",
",",
"querydict",
")",
":",
"address_parse",
"=",
"urlparse",
"(",
"url",
")",
"return",
"urlunparse",
"(",
"address_parse",
".",
"_replace",
"(",
"query",
"=",
"urlencode",
"(",
"querydict",
")",
")",
")"
] | parse a url query | [
"parse",
"a",
"url",
"query"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L585-L590 | train | 46,258 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | Stack.push | def push(self, x):
"""
append items to the stack; input can be a single value or a list
"""
if isinstance(x, list):
for item in x:
self.stack.append(item)
else:
self.stack.append(x) | python | def push(self, x):
"""
append items to the stack; input can be a single value or a list
"""
if isinstance(x, list):
for item in x:
self.stack.append(item)
else:
self.stack.append(x) | [
"def",
"push",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"for",
"item",
"in",
"x",
":",
"self",
".",
"stack",
".",
"append",
"(",
"item",
")",
"else",
":",
"self",
".",
"stack",
".",
"append",
"(",
... | append items to the stack; input can be a single value or a list | [
"append",
"items",
"to",
"the",
"stack",
";",
"input",
"can",
"be",
"a",
"single",
"value",
"or",
"a",
"list"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L558-L566 | train | 46,259 |
johntruckenbrodt/spatialist | spatialist/ancillary.py | Stack.pop | def pop(self):
"""
return the last stack element and delete it from the list
"""
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val | python | def pop(self):
"""
return the last stack element and delete it from the list
"""
if not self.empty():
val = self.stack[-1]
del self.stack[-1]
return val | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"empty",
"(",
")",
":",
"val",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"del",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"return",
"val"
] | return the last stack element and delete it from the list | [
"return",
"the",
"last",
"stack",
"element",
"and",
"delete",
"it",
"from",
"the",
"list"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/ancillary.py#L568-L575 | train | 46,260 |
MLAB-project/pymlab | src/pymlab/sensors/mag.py | MAG01.axes | def axes(self, offset = False):
"""returns measured value in miligauss"""
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
if y == -4096: y = OVERFLOW
z = self.bus.read_int16_data(self.address, self.HMC5883L_DZRA)
if z == -4096: z = OVERFLOW
x*=self._scale
y*=self._scale
z*=self._scale
if offset: (x, y, z) = self.__offset((x,y,z))
return (x, y, z) | python | def axes(self, offset = False):
"""returns measured value in miligauss"""
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
if y == -4096: y = OVERFLOW
z = self.bus.read_int16_data(self.address, self.HMC5883L_DZRA)
if z == -4096: z = OVERFLOW
x*=self._scale
y*=self._scale
z*=self._scale
if offset: (x, y, z) = self.__offset((x,y,z))
return (x, y, z) | [
"def",
"axes",
"(",
"self",
",",
"offset",
"=",
"False",
")",
":",
"reg",
",",
"self",
".",
"_scale",
"=",
"self",
".",
"SCALES",
"[",
"self",
".",
"_gauss",
"]",
"x",
"=",
"self",
".",
"bus",
".",
"read_int16_data",
"(",
"self",
".",
"address",
... | returns measured value in miligauss | [
"returns",
"measured",
"value",
"in",
"miligauss"
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/src/pymlab/sensors/mag.py#L77-L93 | train | 46,261 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ToString | def _ToString(x):
"""The default default formatter!."""
# Some cross-language values for primitives. This is tested in
# jsontemplate_test.py.
if x is None:
return 'null'
if isinstance(x, six.string_types):
return x
return pprint.pformat(x) | python | def _ToString(x):
"""The default default formatter!."""
# Some cross-language values for primitives. This is tested in
# jsontemplate_test.py.
if x is None:
return 'null'
if isinstance(x, six.string_types):
return x
return pprint.pformat(x) | [
"def",
"_ToString",
"(",
"x",
")",
":",
"# Some cross-language values for primitives. This is tested in",
"# jsontemplate_test.py.",
"if",
"x",
"is",
"None",
":",
"return",
"'null'",
"if",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_types",
")",
":",
"return",... | The default default formatter!. | [
"The",
"default",
"default",
"formatter!",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L705-L713 | train | 46,262 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Pairs | def _Pairs(data):
"""dictionary -> list of pairs"""
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | python | def _Pairs(data):
"""dictionary -> list of pairs"""
keys = sorted(data)
return [{'@key': k, '@value': data[k]} for k in keys] | [
"def",
"_Pairs",
"(",
"data",
")",
":",
"keys",
"=",
"sorted",
"(",
"data",
")",
"return",
"[",
"{",
"'@key'",
":",
"k",
",",
"'@value'",
":",
"data",
"[",
"k",
"]",
"}",
"for",
"k",
"in",
"keys",
"]"
] | dictionary -> list of pairs | [
"dictionary",
"-",
">",
"list",
"of",
"pairs"
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L741-L744 | train | 46,263 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Pluralize | def _Pluralize(value, unused_context, args):
"""Formatter to pluralize words."""
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionError
if value > 1:
return p
else:
return s | python | def _Pluralize(value, unused_context, args):
"""Formatter to pluralize words."""
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionError
if value > 1:
return p
else:
return s | [
"def",
"_Pluralize",
"(",
"value",
",",
"unused_context",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"s",
",",
"p",
"=",
"''",
",",
"'s'",
"elif",
"len",
"(",
"args",
")",
"==",
"1",
":",
"s",
",",
"p",
"=",
"''",
... | Formatter to pluralize words. | [
"Formatter",
"to",
"pluralize",
"words",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L808-L824 | train | 46,264 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _TemplateExists | def _TemplateExists(unused_value, context, args):
"""Returns whether the given name is in the current Template's template group."""
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | python | def _TemplateExists(unused_value, context, args):
"""Returns whether the given name is in the current Template's template group."""
try:
name = args[0]
except IndexError:
raise EvaluationError('The "template" predicate requires an argument.')
return context.HasTemplate(name) | [
"def",
"_TemplateExists",
"(",
"unused_value",
",",
"context",
",",
"args",
")",
":",
"try",
":",
"name",
"=",
"args",
"[",
"0",
"]",
"except",
"IndexError",
":",
"raise",
"EvaluationError",
"(",
"'The \"template\" predicate requires an argument.'",
")",
"return",... | Returns whether the given name is in the current Template's template group. | [
"Returns",
"whether",
"the",
"given",
"name",
"is",
"in",
"the",
"current",
"Template",
"s",
"template",
"group",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L877-L883 | train | 46,265 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | SplitMeta | def SplitMeta(meta):
"""Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it.
"""
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
'%r has an odd number of metacharacters' % meta)
return meta[:n // 2], meta[n // 2:] | python | def SplitMeta(meta):
"""Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it.
"""
n = len(meta)
if n % 2 == 1:
raise ConfigurationError(
'%r has an odd number of metacharacters' % meta)
return meta[:n // 2], meta[n // 2:] | [
"def",
"SplitMeta",
"(",
"meta",
")",
":",
"n",
"=",
"len",
"(",
"meta",
")",
"if",
"n",
"%",
"2",
"==",
"1",
":",
"raise",
"ConfigurationError",
"(",
"'%r has an odd number of metacharacters'",
"%",
"meta",
")",
"return",
"meta",
"[",
":",
"n",
"//",
... | Split and validate metacharacters.
Example: '{}' -> ('{', '}')
This is public so the syntax highlighter and other tools can use it. | [
"Split",
"and",
"validate",
"metacharacters",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L900-L911 | train | 46,266 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _MatchDirective | def _MatchDirective(token):
"""Helper function for matching certain directives."""
# Tokens below must start with '.'
if token.startswith('.'):
token = token[1:]
else:
return None, None
if token == 'end':
return END_TOKEN, None
if token == 'alternates with':
return ALTERNATES_TOKEN, token
if token.startswith('or'):
if token.strip() == 'or':
return OR_TOKEN, None
else:
pred_str = token[2:].strip()
return OR_TOKEN, pred_str
match = _SECTION_RE.match(token)
if match:
repeated, section_name = match.groups()
if repeated:
return REPEATED_SECTION_TOKEN, section_name
else:
return SECTION_TOKEN, section_name
if token.startswith('template '):
return SUBST_TEMPLATE_TOKEN, token[9:].strip()
if token.startswith('define '):
return DEF_TOKEN, token[7:].strip()
if token.startswith('if '):
return IF_TOKEN, token[3:].strip()
if token.endswith('?'):
return PREDICATE_TOKEN, token
return None, None | python | def _MatchDirective(token):
"""Helper function for matching certain directives."""
# Tokens below must start with '.'
if token.startswith('.'):
token = token[1:]
else:
return None, None
if token == 'end':
return END_TOKEN, None
if token == 'alternates with':
return ALTERNATES_TOKEN, token
if token.startswith('or'):
if token.strip() == 'or':
return OR_TOKEN, None
else:
pred_str = token[2:].strip()
return OR_TOKEN, pred_str
match = _SECTION_RE.match(token)
if match:
repeated, section_name = match.groups()
if repeated:
return REPEATED_SECTION_TOKEN, section_name
else:
return SECTION_TOKEN, section_name
if token.startswith('template '):
return SUBST_TEMPLATE_TOKEN, token[9:].strip()
if token.startswith('define '):
return DEF_TOKEN, token[7:].strip()
if token.startswith('if '):
return IF_TOKEN, token[3:].strip()
if token.endswith('?'):
return PREDICATE_TOKEN, token
return None, None | [
"def",
"_MatchDirective",
"(",
"token",
")",
":",
"# Tokens below must start with '.'",
"if",
"token",
".",
"startswith",
"(",
"'.'",
")",
":",
"token",
"=",
"token",
"[",
"1",
":",
"]",
"else",
":",
"return",
"None",
",",
"None",
"if",
"token",
"==",
"'... | Helper function for matching certain directives. | [
"Helper",
"function",
"for",
"matching",
"certain",
"directives",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L969-L1008 | train | 46,267 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _CompileTemplate | def _CompileTemplate(
template_str, builder, meta='{}', format_char='|', default_formatter='str',
whitespace='smart'):
"""Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the header -- those are parsed by FromString/FromFile
builder: The interface of _ProgramBuilder isn't fixed. Use at your own
risk.
meta: The metacharacters to use, e.g. '{}', '[]'.
default_formatter: The formatter to use for substitutions that are missing a
formatter. The 'str' formatter the "default default" -- it just tries
to convert the context value to a string in some unspecified manner.
whitespace: 'smart' or 'strip-line'. In smart mode, if a directive is alone
on a line, with only whitespace on either side, then the whitespace is
removed. In 'strip-line' mode, every line is stripped of its
leading and trailing whitespace.
Returns:
The compiled program (obtained from the builder)
Raises:
The various subclasses of CompilationError. For example, if
default_formatter=None, and a variable is missing a formatter, then
MissingFormatter is raised.
This function is public so it can be used by other tools, e.g. a syntax
checking tool run before submitting a template to source control.
"""
meta_left, meta_right = SplitMeta(meta)
# : is meant to look like Python 3000 formatting {foo:.3f}. According to
# PEP 3101, that's also what .NET uses.
# | is more readable, but, more importantly, reminiscent of pipes, which is
# useful for multiple formatters, e.g. {name|js-string|html}
if format_char not in (':', '|'):
raise ConfigurationError(
'Only format characters : and | are accepted (got %r)' % format_char)
if whitespace not in ('smart', 'strip-line'):
raise ConfigurationError('Invalid whitespace mode %r' % whitespace)
# If we go to -1, then we got too many {end}. If end at 1, then we're missing
# an {end}.
balance_counter = 0
comment_counter = 0 # ditto for ##BEGIN/##END
has_defines = False
for token_type, token in _Tokenize(template_str, meta_left, meta_right,
whitespace):
if token_type == COMMENT_BEGIN_TOKEN:
comment_counter += 1
continue
if token_type == COMMENT_END_TOKEN:
comment_counter -= 1
if comment_counter < 0:
raise CompilationError('Got too many ##END markers')
continue
# Don't process any tokens
if comment_counter > 0:
continue
if token_type in (LITERAL_TOKEN, META_LITERAL_TOKEN):
if token:
builder.Append(token)
continue
if token_type in (SECTION_TOKEN, REPEATED_SECTION_TOKEN, DEF_TOKEN):
parts = [p.strip() for p in token.split(format_char)]
if len(parts) == 1:
name = parts[0]
formatters = []
else:
name = parts[0]
formatters = parts[1:]
builder.NewSection(token_type, name, formatters)
balance_counter += 1
if token_type == DEF_TOKEN:
has_defines = True
continue
if token_type == PREDICATE_TOKEN:
# {.attr?} lookups
builder.NewPredicateSection(token, test_attr=True)
balance_counter += 1
continue
if token_type == IF_TOKEN:
builder.NewPredicateSection(token, test_attr=False)
balance_counter += 1
continue
if token_type == OR_TOKEN:
builder.NewOrClause(token)
continue
if token_type == ALTERNATES_TOKEN:
builder.AlternatesWith()
continue
if token_type == END_TOKEN:
balance_counter -= 1
if balance_counter < 0:
# TODO: Show some context for errors
raise TemplateSyntaxError(
'Got too many %send%s statements. You may have mistyped an '
"earlier 'section' or 'repeated section' directive."
% (meta_left, meta_right))
builder.EndSection()
continue
if token_type == SUBST_TOKEN:
parts = [p.strip() for p in token.split(format_char)]
if len(parts) == 1:
if default_formatter is None:
raise MissingFormatter('This template requires explicit formatters.')
# If no formatter is specified, the default is the 'str' formatter,
# which the user can define however they desire.
name = token
formatters = [default_formatter]
else:
name = parts[0]
formatters = parts[1:]
builder.AppendSubstitution(name, formatters)
continue
if token_type == SUBST_TEMPLATE_TOKEN:
# no formatters
builder.AppendTemplateSubstitution(token)
continue
if balance_counter != 0:
raise TemplateSyntaxError('Got too few %send%s statements' %
(meta_left, meta_right))
if comment_counter != 0:
raise CompilationError('Got %d more {##BEGIN}s than {##END}s' % comment_counter)
return builder.Root(), has_defines | python | def _CompileTemplate(
template_str, builder, meta='{}', format_char='|', default_formatter='str',
whitespace='smart'):
"""Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the header -- those are parsed by FromString/FromFile
builder: The interface of _ProgramBuilder isn't fixed. Use at your own
risk.
meta: The metacharacters to use, e.g. '{}', '[]'.
default_formatter: The formatter to use for substitutions that are missing a
formatter. The 'str' formatter the "default default" -- it just tries
to convert the context value to a string in some unspecified manner.
whitespace: 'smart' or 'strip-line'. In smart mode, if a directive is alone
on a line, with only whitespace on either side, then the whitespace is
removed. In 'strip-line' mode, every line is stripped of its
leading and trailing whitespace.
Returns:
The compiled program (obtained from the builder)
Raises:
The various subclasses of CompilationError. For example, if
default_formatter=None, and a variable is missing a formatter, then
MissingFormatter is raised.
This function is public so it can be used by other tools, e.g. a syntax
checking tool run before submitting a template to source control.
"""
meta_left, meta_right = SplitMeta(meta)
# : is meant to look like Python 3000 formatting {foo:.3f}. According to
# PEP 3101, that's also what .NET uses.
# | is more readable, but, more importantly, reminiscent of pipes, which is
# useful for multiple formatters, e.g. {name|js-string|html}
if format_char not in (':', '|'):
raise ConfigurationError(
'Only format characters : and | are accepted (got %r)' % format_char)
if whitespace not in ('smart', 'strip-line'):
raise ConfigurationError('Invalid whitespace mode %r' % whitespace)
# If we go to -1, then we got too many {end}. If end at 1, then we're missing
# an {end}.
balance_counter = 0
comment_counter = 0 # ditto for ##BEGIN/##END
has_defines = False
for token_type, token in _Tokenize(template_str, meta_left, meta_right,
whitespace):
if token_type == COMMENT_BEGIN_TOKEN:
comment_counter += 1
continue
if token_type == COMMENT_END_TOKEN:
comment_counter -= 1
if comment_counter < 0:
raise CompilationError('Got too many ##END markers')
continue
# Don't process any tokens
if comment_counter > 0:
continue
if token_type in (LITERAL_TOKEN, META_LITERAL_TOKEN):
if token:
builder.Append(token)
continue
if token_type in (SECTION_TOKEN, REPEATED_SECTION_TOKEN, DEF_TOKEN):
parts = [p.strip() for p in token.split(format_char)]
if len(parts) == 1:
name = parts[0]
formatters = []
else:
name = parts[0]
formatters = parts[1:]
builder.NewSection(token_type, name, formatters)
balance_counter += 1
if token_type == DEF_TOKEN:
has_defines = True
continue
if token_type == PREDICATE_TOKEN:
# {.attr?} lookups
builder.NewPredicateSection(token, test_attr=True)
balance_counter += 1
continue
if token_type == IF_TOKEN:
builder.NewPredicateSection(token, test_attr=False)
balance_counter += 1
continue
if token_type == OR_TOKEN:
builder.NewOrClause(token)
continue
if token_type == ALTERNATES_TOKEN:
builder.AlternatesWith()
continue
if token_type == END_TOKEN:
balance_counter -= 1
if balance_counter < 0:
# TODO: Show some context for errors
raise TemplateSyntaxError(
'Got too many %send%s statements. You may have mistyped an '
"earlier 'section' or 'repeated section' directive."
% (meta_left, meta_right))
builder.EndSection()
continue
if token_type == SUBST_TOKEN:
parts = [p.strip() for p in token.split(format_char)]
if len(parts) == 1:
if default_formatter is None:
raise MissingFormatter('This template requires explicit formatters.')
# If no formatter is specified, the default is the 'str' formatter,
# which the user can define however they desire.
name = token
formatters = [default_formatter]
else:
name = parts[0]
formatters = parts[1:]
builder.AppendSubstitution(name, formatters)
continue
if token_type == SUBST_TEMPLATE_TOKEN:
# no formatters
builder.AppendTemplateSubstitution(token)
continue
if balance_counter != 0:
raise TemplateSyntaxError('Got too few %send%s statements' %
(meta_left, meta_right))
if comment_counter != 0:
raise CompilationError('Got %d more {##BEGIN}s than {##END}s' % comment_counter)
return builder.Root(), has_defines | [
"def",
"_CompileTemplate",
"(",
"template_str",
",",
"builder",
",",
"meta",
"=",
"'{}'",
",",
"format_char",
"=",
"'|'",
",",
"default_formatter",
"=",
"'str'",
",",
"whitespace",
"=",
"'smart'",
")",
":",
"meta_left",
",",
"meta_right",
"=",
"SplitMeta",
"... | Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the header -- those are parsed by FromString/FromFile
builder: The interface of _ProgramBuilder isn't fixed. Use at your own
risk.
meta: The metacharacters to use, e.g. '{}', '[]'.
default_formatter: The formatter to use for substitutions that are missing a
formatter. The 'str' formatter the "default default" -- it just tries
to convert the context value to a string in some unspecified manner.
whitespace: 'smart' or 'strip-line'. In smart mode, if a directive is alone
on a line, with only whitespace on either side, then the whitespace is
removed. In 'strip-line' mode, every line is stripped of its
leading and trailing whitespace.
Returns:
The compiled program (obtained from the builder)
Raises:
The various subclasses of CompilationError. For example, if
default_formatter=None, and a variable is missing a formatter, then
MissingFormatter is raised.
This function is public so it can be used by other tools, e.g. a syntax
checking tool run before submitting a template to source control. | [
"Compile",
"the",
"template",
"string",
"calling",
"methods",
"on",
"the",
"program",
"builder",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1106-L1250 | train | 46,268 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | FromString | def FromString(s, **kwargs):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, **kwargs) | python | def FromString(s, **kwargs):
"""Like FromFile, but takes a string."""
f = StringIO.StringIO(s)
return FromFile(f, **kwargs) | [
"def",
"FromString",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
"=",
"StringIO",
".",
"StringIO",
"(",
"s",
")",
"return",
"FromFile",
"(",
"f",
",",
"*",
"*",
"kwargs",
")"
] | Like FromFile, but takes a string. | [
"Like",
"FromFile",
"but",
"takes",
"a",
"string",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1258-L1262 | train | 46,269 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | FromFile | def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None,
_constructor=None):
"""Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP or E-mail headers. The first lines of the file
can specify template options, such as the metacharacters to use. One blank
line must separate the options from the template body.
Example:
default-formatter: none
meta: {{}}
format-char: :
<blank line required>
Template goes here: {{variable:html}}
Args:
f: A file handle to read from. Caller is responsible for opening and
closing it.
"""
_constructor = _constructor or Template
options = {}
# Parse lines until the first one that doesn't look like an option
while 1:
line = f.readline()
match = _OPTION_RE.match(line)
if match:
name, value = match.group(1), match.group(2)
# Accept something like 'Default-Formatter: raw'. This syntax is like
# HTTP/E-mail headers.
name = name.lower()
# In Python 2.4, kwargs must be plain strings
name = name.encode('utf-8')
if name in _OPTION_NAMES:
name = name.replace('-', '_')
value = value.strip()
if name == 'default_formatter' and value.lower() == 'none':
value = None
options[name] = value
else:
break
else:
break
if options:
if line.strip():
raise CompilationError(
'Must be one blank line between template options and body (got %r)'
% line)
body = f.read()
else:
# There were no options, so no blank line is necessary.
body = line + f.read()
return _constructor(body,
more_formatters=more_formatters,
more_predicates=more_predicates,
**options) | python | def FromFile(f, more_formatters=lambda x: None, more_predicates=lambda x: None,
_constructor=None):
"""Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP or E-mail headers. The first lines of the file
can specify template options, such as the metacharacters to use. One blank
line must separate the options from the template body.
Example:
default-formatter: none
meta: {{}}
format-char: :
<blank line required>
Template goes here: {{variable:html}}
Args:
f: A file handle to read from. Caller is responsible for opening and
closing it.
"""
_constructor = _constructor or Template
options = {}
# Parse lines until the first one that doesn't look like an option
while 1:
line = f.readline()
match = _OPTION_RE.match(line)
if match:
name, value = match.group(1), match.group(2)
# Accept something like 'Default-Formatter: raw'. This syntax is like
# HTTP/E-mail headers.
name = name.lower()
# In Python 2.4, kwargs must be plain strings
name = name.encode('utf-8')
if name in _OPTION_NAMES:
name = name.replace('-', '_')
value = value.strip()
if name == 'default_formatter' and value.lower() == 'none':
value = None
options[name] = value
else:
break
else:
break
if options:
if line.strip():
raise CompilationError(
'Must be one blank line between template options and body (got %r)'
% line)
body = f.read()
else:
# There were no options, so no blank line is necessary.
body = line + f.read()
return _constructor(body,
more_formatters=more_formatters,
more_predicates=more_predicates,
**options) | [
"def",
"FromFile",
"(",
"f",
",",
"more_formatters",
"=",
"lambda",
"x",
":",
"None",
",",
"more_predicates",
"=",
"lambda",
"x",
":",
"None",
",",
"_constructor",
"=",
"None",
")",
":",
"_constructor",
"=",
"_constructor",
"or",
"Template",
"options",
"="... | Parse a template from a file, using a simple file format.
This is useful when you want to include template options in a data file,
rather than in the source code.
The format is similar to HTTP or E-mail headers. The first lines of the file
can specify template options, such as the metacharacters to use. One blank
line must separate the options from the template body.
Example:
default-formatter: none
meta: {{}}
format-char: :
<blank line required>
Template goes here: {{variable:html}}
Args:
f: A file handle to read from. Caller is responsible for opening and
closing it. | [
"Parse",
"a",
"template",
"from",
"a",
"file",
"using",
"a",
"simple",
"file",
"format",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1265-L1329 | train | 46,270 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _Execute | def _Execute(statements, context, callback, trace):
"""Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion.
"""
# Every time we call _Execute, increase this depth
if trace:
trace.exec_depth += 1
for i, statement in enumerate(statements):
if isinstance(statement, six.string_types):
callback(statement)
else:
# In the case of a substitution, args is a pair (name, formatters).
# In the case of a section, it's a _Section instance.
try:
func, args = statement
func(args, context, callback, trace)
except UndefinedVariable as e:
# Show context for statements
start = max(0, i - 3)
end = i + 3
e.near = statements[start:end]
e.trace = trace # Attach caller's trace (could be None)
raise | python | def _Execute(statements, context, callback, trace):
"""Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion.
"""
# Every time we call _Execute, increase this depth
if trace:
trace.exec_depth += 1
for i, statement in enumerate(statements):
if isinstance(statement, six.string_types):
callback(statement)
else:
# In the case of a substitution, args is a pair (name, formatters).
# In the case of a section, it's a _Section instance.
try:
func, args = statement
func(args, context, callback, trace)
except UndefinedVariable as e:
# Show context for statements
start = max(0, i - 3)
end = i + 3
e.near = statements[start:end]
e.trace = trace # Attach caller's trace (could be None)
raise | [
"def",
"_Execute",
"(",
"statements",
",",
"context",
",",
"callback",
",",
"trace",
")",
":",
"# Every time we call _Execute, increase this depth",
"if",
"trace",
":",
"trace",
".",
"exec_depth",
"+=",
"1",
"for",
"i",
",",
"statement",
"in",
"enumerate",
"(",
... | Execute a bunch of template statements in a ScopedContext.
Args:
callback: Strings are "written" to this callback function.
trace: Trace object, or None
This is called in a mutually recursive fashion. | [
"Execute",
"a",
"bunch",
"of",
"template",
"statements",
"in",
"a",
"ScopedContext",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1725-L1752 | train | 46,271 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | expand | def expand(template_str, dictionary, **kwargs):
"""Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))
"""
t = Template(template_str, **kwargs)
return t.expand(dictionary) | python | def expand(template_str, dictionary, **kwargs):
"""Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s))
"""
t = Template(template_str, **kwargs)
return t.expand(dictionary) | [
"def",
"expand",
"(",
"template_str",
",",
"dictionary",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"Template",
"(",
"template_str",
",",
"*",
"*",
"kwargs",
")",
"return",
"t",
".",
"expand",
"(",
"dictionary",
")"
] | Free function to expands a template string with a data dictionary.
This is useful for cases where you don't care about saving the result of
compilation (similar to re.match('.*', s) vs DOT_STAR.match(s)) | [
"Free",
"function",
"to",
"expands",
"a",
"template",
"string",
"with",
"a",
"data",
"dictionary",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1755-L1762 | train | 46,272 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _FlattenToCallback | def _FlattenToCallback(tokens, callback):
"""Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c');
"""
for t in tokens:
if isinstance(t, six.string_types):
callback(t)
else:
_FlattenToCallback(t, callback) | python | def _FlattenToCallback(tokens, callback):
"""Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c');
"""
for t in tokens:
if isinstance(t, six.string_types):
callback(t)
else:
_FlattenToCallback(t, callback) | [
"def",
"_FlattenToCallback",
"(",
"tokens",
",",
"callback",
")",
":",
"for",
"t",
"in",
"tokens",
":",
"if",
"isinstance",
"(",
"t",
",",
"six",
".",
"string_types",
")",
":",
"callback",
"(",
"t",
")",
"else",
":",
"_FlattenToCallback",
"(",
"t",
","... | Takes a nested list structure and flattens it.
['a', ['b', 'c']] -> callback('a'); callback('b'); callback('c'); | [
"Takes",
"a",
"nested",
"list",
"structure",
"and",
"flattens",
"it",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1768-L1777 | train | 46,273 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | execute_with_style_LEGACY | def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'):
"""OBSOLETE old API."""
try:
body_data = data[body_subtree]
except KeyError:
raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)
tokens_body = []
template.execute(body_data, tokens_body.append)
data[body_subtree] = tokens_body
tokens = []
style.execute(data, tokens.append)
_FlattenToCallback(tokens, callback) | python | def execute_with_style_LEGACY(template, style, data, callback, body_subtree='body'):
"""OBSOLETE old API."""
try:
body_data = data[body_subtree]
except KeyError:
raise EvaluationError('Data dictionary has no subtree %r' % body_subtree)
tokens_body = []
template.execute(body_data, tokens_body.append)
data[body_subtree] = tokens_body
tokens = []
style.execute(data, tokens.append)
_FlattenToCallback(tokens, callback) | [
"def",
"execute_with_style_LEGACY",
"(",
"template",
",",
"style",
",",
"data",
",",
"callback",
",",
"body_subtree",
"=",
"'body'",
")",
":",
"try",
":",
"body_data",
"=",
"data",
"[",
"body_subtree",
"]",
"except",
"KeyError",
":",
"raise",
"EvaluationError"... | OBSOLETE old API. | [
"OBSOLETE",
"old",
"API",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1783-L1794 | train | 46,274 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | expand_with_style | def expand_with_style(template, style, data, body_subtree='body'):
"""Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
template: Template instance for the inner "page content"
style: Template instance for the outer "page style"
data: Data dictionary, with a 'body' key (or body_subtree
"""
if template.has_defines:
return template.expand(data, style=style)
else:
tokens = []
execute_with_style_LEGACY(template, style, data, tokens.append,
body_subtree=body_subtree)
return JoinTokens(tokens) | python | def expand_with_style(template, style, data, body_subtree='body'):
"""Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
template: Template instance for the inner "page content"
style: Template instance for the outer "page style"
data: Data dictionary, with a 'body' key (or body_subtree
"""
if template.has_defines:
return template.expand(data, style=style)
else:
tokens = []
execute_with_style_LEGACY(template, style, data, tokens.append,
body_subtree=body_subtree)
return JoinTokens(tokens) | [
"def",
"expand_with_style",
"(",
"template",
",",
"style",
",",
"data",
",",
"body_subtree",
"=",
"'body'",
")",
":",
"if",
"template",
".",
"has_defines",
":",
"return",
"template",
".",
"expand",
"(",
"data",
",",
"style",
"=",
"style",
")",
"else",
":... | Expand a data dictionary with a template AND a style.
DEPRECATED -- Remove this entire function in favor of expand(d, style=style)
A style is a Template instance that factors out the common strings in several
"body" templates.
Args:
template: Template instance for the inner "page content"
style: Template instance for the outer "page style"
data: Data dictionary, with a 'body' key (or body_subtree | [
"Expand",
"a",
"data",
"dictionary",
"with",
"a",
"template",
"AND",
"a",
"style",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1797-L1816 | train | 46,275 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder._GetFormatter | def _GetFormatter(self, format_str):
"""
The user's formatters are consulted first, then the default formatters.
"""
formatter, args, func_type = self.formatters.LookupWithType(format_str)
if formatter:
return formatter, args, func_type
else:
raise BadFormatter('%r is not a valid formatter' % format_str) | python | def _GetFormatter(self, format_str):
"""
The user's formatters are consulted first, then the default formatters.
"""
formatter, args, func_type = self.formatters.LookupWithType(format_str)
if formatter:
return formatter, args, func_type
else:
raise BadFormatter('%r is not a valid formatter' % format_str) | [
"def",
"_GetFormatter",
"(",
"self",
",",
"format_str",
")",
":",
"formatter",
",",
"args",
",",
"func_type",
"=",
"self",
".",
"formatters",
".",
"LookupWithType",
"(",
"format_str",
")",
"if",
"formatter",
":",
"return",
"formatter",
",",
"args",
",",
"f... | The user's formatters are consulted first, then the default formatters. | [
"The",
"user",
"s",
"formatters",
"are",
"consulted",
"first",
"then",
"the",
"default",
"formatters",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L390-L398 | train | 46,276 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder._GetPredicate | def _GetPredicate(self, pred_str, test_attr=False):
"""
The user's predicates are consulted first, then the default predicates.
"""
predicate, args, func_type = self.predicates.LookupWithType(pred_str)
if predicate:
pred = predicate, args, func_type
else:
# Nicer syntax, {.debug?} is shorthand for {.if test debug}.
# Currently there is not if/elif chain; just use
# {.if test debug} {.or test release} {.or} {.end}
if test_attr:
assert pred_str.endswith('?')
# func, args, func_type
pred = (_TestAttribute, (pred_str[:-1],), ENHANCED_FUNC)
else:
raise BadPredicate('%r is not a valid predicate' % pred_str)
return pred | python | def _GetPredicate(self, pred_str, test_attr=False):
"""
The user's predicates are consulted first, then the default predicates.
"""
predicate, args, func_type = self.predicates.LookupWithType(pred_str)
if predicate:
pred = predicate, args, func_type
else:
# Nicer syntax, {.debug?} is shorthand for {.if test debug}.
# Currently there is not if/elif chain; just use
# {.if test debug} {.or test release} {.or} {.end}
if test_attr:
assert pred_str.endswith('?')
# func, args, func_type
pred = (_TestAttribute, (pred_str[:-1],), ENHANCED_FUNC)
else:
raise BadPredicate('%r is not a valid predicate' % pred_str)
return pred | [
"def",
"_GetPredicate",
"(",
"self",
",",
"pred_str",
",",
"test_attr",
"=",
"False",
")",
":",
"predicate",
",",
"args",
",",
"func_type",
"=",
"self",
".",
"predicates",
".",
"LookupWithType",
"(",
"pred_str",
")",
"if",
"predicate",
":",
"pred",
"=",
... | The user's predicates are consulted first, then the default predicates. | [
"The",
"user",
"s",
"predicates",
"are",
"consulted",
"first",
"then",
"the",
"default",
"predicates",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L400-L417 | train | 46,277 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder.NewSection | def NewSection(self, token_type, section_name, pre_formatters):
"""For sections or repeated sections."""
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == REPEATED_SECTION_TOKEN:
new_block = _RepeatedSection(section_name, pre_formatters)
func = _DoRepeatedSection
elif token_type == SECTION_TOKEN:
new_block = _Section(section_name, pre_formatters)
func = _DoSection
elif token_type == DEF_TOKEN:
new_block = _Section(section_name, [])
func = _DoDef
else:
raise AssertionError('Invalid token type %s' % token_type)
self._NewSection(func, new_block) | python | def NewSection(self, token_type, section_name, pre_formatters):
"""For sections or repeated sections."""
pre_formatters = [self._GetFormatter(f) for f in pre_formatters]
# TODO: Consider getting rid of this dispatching, and turn _Do* into methods
if token_type == REPEATED_SECTION_TOKEN:
new_block = _RepeatedSection(section_name, pre_formatters)
func = _DoRepeatedSection
elif token_type == SECTION_TOKEN:
new_block = _Section(section_name, pre_formatters)
func = _DoSection
elif token_type == DEF_TOKEN:
new_block = _Section(section_name, [])
func = _DoDef
else:
raise AssertionError('Invalid token type %s' % token_type)
self._NewSection(func, new_block) | [
"def",
"NewSection",
"(",
"self",
",",
"token_type",
",",
"section_name",
",",
"pre_formatters",
")",
":",
"pre_formatters",
"=",
"[",
"self",
".",
"_GetFormatter",
"(",
"f",
")",
"for",
"f",
"in",
"pre_formatters",
"]",
"# TODO: Consider getting rid of this dispa... | For sections or repeated sections. | [
"For",
"sections",
"or",
"repeated",
"sections",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L435-L452 | train | 46,278 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ProgramBuilder.NewPredicateSection | def NewPredicateSection(self, pred_str, test_attr=False):
"""For chains of predicate clauses."""
pred = self._GetPredicate(pred_str, test_attr=test_attr)
block = _PredicateSection()
block.NewOrClause(pred)
self._NewSection(_DoPredicates, block) | python | def NewPredicateSection(self, pred_str, test_attr=False):
"""For chains of predicate clauses."""
pred = self._GetPredicate(pred_str, test_attr=test_attr)
block = _PredicateSection()
block.NewOrClause(pred)
self._NewSection(_DoPredicates, block) | [
"def",
"NewPredicateSection",
"(",
"self",
",",
"pred_str",
",",
"test_attr",
"=",
"False",
")",
":",
"pred",
"=",
"self",
".",
"_GetPredicate",
"(",
"pred_str",
",",
"test_attr",
"=",
"test_attr",
")",
"block",
"=",
"_PredicateSection",
"(",
")",
"block",
... | For chains of predicate clauses. | [
"For",
"chains",
"of",
"predicate",
"clauses",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L468-L474 | train | 46,279 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext.PushSection | def PushSection(self, name, pre_formatters):
"""Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section.
"""
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get(name)
# Apply pre-formatters
for i, (f, args, formatter_type) in enumerate(pre_formatters):
if formatter_type == ENHANCED_FUNC:
value = f(value, self, args)
elif formatter_type == SIMPLE_FUNC:
value = f(value)
else:
assert False, 'Invalid formatter type %r' % formatter_type
self.stack.append(_Frame(value))
return value | python | def PushSection(self, name, pre_formatters):
"""Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section.
"""
if name == '@':
value = self.stack[-1].context
else:
value = self.stack[-1].context.get(name)
# Apply pre-formatters
for i, (f, args, formatter_type) in enumerate(pre_formatters):
if formatter_type == ENHANCED_FUNC:
value = f(value, self, args)
elif formatter_type == SIMPLE_FUNC:
value = f(value)
else:
assert False, 'Invalid formatter type %r' % formatter_type
self.stack.append(_Frame(value))
return value | [
"def",
"PushSection",
"(",
"self",
",",
"name",
",",
"pre_formatters",
")",
":",
"if",
"name",
"==",
"'@'",
":",
"value",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"context",
"else",
":",
"value",
"=",
"self",
".",
"stack",
"[",
"-",
"1... | Given a section name, push it on the top of the stack.
Returns:
The new section, or None if there is no such section. | [
"Given",
"a",
"section",
"name",
"push",
"it",
"on",
"the",
"top",
"of",
"the",
"stack",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L598-L619 | train | 46,280 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext.Next | def Next(self):
"""Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements
"""
stacktop = self.stack[-1]
# Now we're iterating -- push a new mutable object onto the stack
if stacktop.index == -1:
stacktop = _Frame(None, index=0)
self.stack.append(stacktop)
context_array = self.stack[-2].context
if stacktop.index == len(context_array):
self.stack.pop()
raise StopIteration
stacktop.context = context_array[stacktop.index]
stacktop.index += 1
return True | python | def Next(self):
"""Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements
"""
stacktop = self.stack[-1]
# Now we're iterating -- push a new mutable object onto the stack
if stacktop.index == -1:
stacktop = _Frame(None, index=0)
self.stack.append(stacktop)
context_array = self.stack[-2].context
if stacktop.index == len(context_array):
self.stack.pop()
raise StopIteration
stacktop.context = context_array[stacktop.index]
stacktop.index += 1
return True | [
"def",
"Next",
"(",
"self",
")",
":",
"stacktop",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"# Now we're iterating -- push a new mutable object onto the stack",
"if",
"stacktop",
".",
"index",
"==",
"-",
"1",
":",
"stacktop",
"=",
"_Frame",
"(",
"None",
... | Advance to the next item in a repeated section.
Raises:
StopIteration if there are no more elements | [
"Advance",
"to",
"the",
"next",
"item",
"in",
"a",
"repeated",
"section",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L624-L646 | train | 46,281 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext._LookUpStack | def _LookUpStack(self, name):
"""Look up the stack for the given name."""
i = len(self.stack) - 1
while 1:
frame = self.stack[i]
if name == '@index':
if frame.index != -1: # -1 is undefined
return frame.index # @index is 1-based
else:
context = frame.context
if hasattr(context, 'get'): # Can't look up names in a list or atom
try:
return context[name]
except KeyError:
pass
i -= 1 # Next frame
if i <= -1: # Couldn't find it anywhere
return self._Undefined(name) | python | def _LookUpStack(self, name):
"""Look up the stack for the given name."""
i = len(self.stack) - 1
while 1:
frame = self.stack[i]
if name == '@index':
if frame.index != -1: # -1 is undefined
return frame.index # @index is 1-based
else:
context = frame.context
if hasattr(context, 'get'): # Can't look up names in a list or atom
try:
return context[name]
except KeyError:
pass
i -= 1 # Next frame
if i <= -1: # Couldn't find it anywhere
return self._Undefined(name) | [
"def",
"_LookUpStack",
"(",
"self",
",",
"name",
")",
":",
"i",
"=",
"len",
"(",
"self",
".",
"stack",
")",
"-",
"1",
"while",
"1",
":",
"frame",
"=",
"self",
".",
"stack",
"[",
"i",
"]",
"if",
"name",
"==",
"'@index'",
":",
"if",
"frame",
".",... | Look up the stack for the given name. | [
"Look",
"up",
"the",
"stack",
"for",
"the",
"given",
"name",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L654-L672 | train | 46,282 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | _ScopedContext.Lookup | def Lookup(self, name):
"""Get the value associated with a name in the current context.
The current context could be an dictionary in a list, or a dictionary
outside a list.
Args:
name: name to lookup, e.g. 'foo' or 'foo.bar.baz'
Returns:
The value, or self.undefined_str
Raises:
UndefinedVariable if self.undefined_str is not set
"""
if name == '@':
return self.stack[-1].context
parts = name.split('.')
value = self._LookUpStack(parts[0])
# Now do simple lookups of the rest of the parts
for part in parts[1:]:
try:
value = value[part]
except (KeyError, TypeError): # TypeError for non-dictionaries
return self._Undefined(part)
return value | python | def Lookup(self, name):
"""Get the value associated with a name in the current context.
The current context could be an dictionary in a list, or a dictionary
outside a list.
Args:
name: name to lookup, e.g. 'foo' or 'foo.bar.baz'
Returns:
The value, or self.undefined_str
Raises:
UndefinedVariable if self.undefined_str is not set
"""
if name == '@':
return self.stack[-1].context
parts = name.split('.')
value = self._LookUpStack(parts[0])
# Now do simple lookups of the rest of the parts
for part in parts[1:]:
try:
value = value[part]
except (KeyError, TypeError): # TypeError for non-dictionaries
return self._Undefined(part)
return value | [
"def",
"Lookup",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"==",
"'@'",
":",
"return",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
".",
"context",
"parts",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"value",
"=",
"self",
".",
"_LookUpStack... | Get the value associated with a name in the current context.
The current context could be an dictionary in a list, or a dictionary
outside a list.
Args:
name: name to lookup, e.g. 'foo' or 'foo.bar.baz'
Returns:
The value, or self.undefined_str
Raises:
UndefinedVariable if self.undefined_str is not set | [
"Get",
"the",
"value",
"associated",
"with",
"a",
"name",
"in",
"the",
"current",
"context",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L674-L702 | train | 46,283 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | Template.execute | def execute(self, data_dict, callback, group=None, trace=None):
"""Low level method to expand the template piece by piece.
Args:
data_dict: The JSON data dictionary.
callback: A callback which should be called with each expanded token.
group: Dictionary of name -> Template instance (for styles)
Example: You can pass 'f.write' as the callback to write directly to a file
handle.
"""
# First try the passed in version, then the one set by _SetTemplateGroup. May
# be None. Only one of these should be set.
group = group or self.group
context = _ScopedContext(data_dict, self.undefined_str, group=group)
_Execute(self._program.Statements(), context, callback, trace) | python | def execute(self, data_dict, callback, group=None, trace=None):
"""Low level method to expand the template piece by piece.
Args:
data_dict: The JSON data dictionary.
callback: A callback which should be called with each expanded token.
group: Dictionary of name -> Template instance (for styles)
Example: You can pass 'f.write' as the callback to write directly to a file
handle.
"""
# First try the passed in version, then the one set by _SetTemplateGroup. May
# be None. Only one of these should be set.
group = group or self.group
context = _ScopedContext(data_dict, self.undefined_str, group=group)
_Execute(self._program.Statements(), context, callback, trace) | [
"def",
"execute",
"(",
"self",
",",
"data_dict",
",",
"callback",
",",
"group",
"=",
"None",
",",
"trace",
"=",
"None",
")",
":",
"# First try the passed in version, then the one set by _SetTemplateGroup. May",
"# be None. Only one of these should be set.",
"group",
"=",
... | Low level method to expand the template piece by piece.
Args:
data_dict: The JSON data dictionary.
callback: A callback which should be called with each expanded token.
group: Dictionary of name -> Template instance (for styles)
Example: You can pass 'f.write' as the callback to write directly to a file
handle. | [
"Low",
"level",
"method",
"to",
"expand",
"the",
"template",
"piece",
"by",
"piece",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1426-L1441 | train | 46,284 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | Template.expand | def expand(self, *args, **kwargs):
"""Expands the template with the given data dictionary, returning a string.
This is a small wrapper around execute(), and is the most convenient
interface.
Args:
data_dict: The JSON data dictionary. Like the builtin dict() constructor,
it can take a single dictionary as a positional argument, or arbitrary
keyword arguments.
trace: Trace object for debugging
style: Template instance to be treated as a style for this template (the
"outside")
Returns:
The return value could be a str() or unicode() instance, depending on the
the type of the template string passed in, and what the types the strings
in the dictionary are.
"""
if args:
if len(args) == 1:
data_dict = args[0]
trace = kwargs.get('trace')
style = kwargs.get('style')
else:
raise TypeError(
'expand() only takes 1 positional argument (got %s)' % args)
else:
data_dict = kwargs
trace = None # Can't use trace= with the kwargs style
style = None
tokens = []
group = _MakeGroupFromRootSection(self._program, self.undefined_str)
if style:
style.execute(data_dict, tokens.append, group=group,
trace=trace)
else:
# Needs a group to reference its OWN {.define}s
self.execute(data_dict, tokens.append, group=group,
trace=trace)
return JoinTokens(tokens) | python | def expand(self, *args, **kwargs):
"""Expands the template with the given data dictionary, returning a string.
This is a small wrapper around execute(), and is the most convenient
interface.
Args:
data_dict: The JSON data dictionary. Like the builtin dict() constructor,
it can take a single dictionary as a positional argument, or arbitrary
keyword arguments.
trace: Trace object for debugging
style: Template instance to be treated as a style for this template (the
"outside")
Returns:
The return value could be a str() or unicode() instance, depending on the
the type of the template string passed in, and what the types the strings
in the dictionary are.
"""
if args:
if len(args) == 1:
data_dict = args[0]
trace = kwargs.get('trace')
style = kwargs.get('style')
else:
raise TypeError(
'expand() only takes 1 positional argument (got %s)' % args)
else:
data_dict = kwargs
trace = None # Can't use trace= with the kwargs style
style = None
tokens = []
group = _MakeGroupFromRootSection(self._program, self.undefined_str)
if style:
style.execute(data_dict, tokens.append, group=group,
trace=trace)
else:
# Needs a group to reference its OWN {.define}s
self.execute(data_dict, tokens.append, group=group,
trace=trace)
return JoinTokens(tokens) | [
"def",
"expand",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"data_dict",
"=",
"args",
"[",
"0",
"]",
"trace",
"=",
"kwargs",
".",
"get",
"(",
"'trace'",
... | Expands the template with the given data dictionary, returning a string.
This is a small wrapper around execute(), and is the most convenient
interface.
Args:
data_dict: The JSON data dictionary. Like the builtin dict() constructor,
it can take a single dictionary as a positional argument, or arbitrary
keyword arguments.
trace: Trace object for debugging
style: Template instance to be treated as a style for this template (the
"outside")
Returns:
The return value could be a str() or unicode() instance, depending on the
the type of the template string passed in, and what the types the strings
in the dictionary are. | [
"Expands",
"the",
"template",
"with",
"the",
"given",
"data",
"dictionary",
"returning",
"a",
"string",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1445-L1487 | train | 46,285 |
vladsaveliev/TargQC | targqc/utilz/jsontemplate/_jsontemplate.py | Template.tokenstream | def tokenstream(self, data_dict):
"""Yields a list of tokens resulting from expansion.
This may be useful for WSGI apps. NOTE: In the current implementation, the
entire expanded template must be stored memory.
NOTE: This is a generator, but JavaScript doesn't have generators.
"""
tokens = []
self.execute(data_dict, tokens.append)
for token in tokens:
yield token | python | def tokenstream(self, data_dict):
"""Yields a list of tokens resulting from expansion.
This may be useful for WSGI apps. NOTE: In the current implementation, the
entire expanded template must be stored memory.
NOTE: This is a generator, but JavaScript doesn't have generators.
"""
tokens = []
self.execute(data_dict, tokens.append)
for token in tokens:
yield token | [
"def",
"tokenstream",
"(",
"self",
",",
"data_dict",
")",
":",
"tokens",
"=",
"[",
"]",
"self",
".",
"execute",
"(",
"data_dict",
",",
"tokens",
".",
"append",
")",
"for",
"token",
"in",
"tokens",
":",
"yield",
"token"
] | Yields a list of tokens resulting from expansion.
This may be useful for WSGI apps. NOTE: In the current implementation, the
entire expanded template must be stored memory.
NOTE: This is a generator, but JavaScript doesn't have generators. | [
"Yields",
"a",
"list",
"of",
"tokens",
"resulting",
"from",
"expansion",
"."
] | e887c36b2194dbd73c6ea32989b6cb84c6c0e58d | https://github.com/vladsaveliev/TargQC/blob/e887c36b2194dbd73c6ea32989b6cb84c6c0e58d/targqc/utilz/jsontemplate/_jsontemplate.py#L1489-L1500 | train | 46,286 |
RI-imaging/ODTbrain | odtbrain/_preproc.py | align_unwrapped | def align_unwrapped(sino):
"""Align an unwrapped phase array to zero-phase
All operations are performed in-place.
"""
samples = []
if len(sino.shape) == 2:
# 2D
# take 1D samples at beginning and end of array
samples.append(sino[:, 0])
samples.append(sino[:, 1])
samples.append(sino[:, 2])
samples.append(sino[:, -1])
samples.append(sino[:, -2])
elif len(sino.shape) == 3:
# 3D
# take 1D samples at beginning and end of array
samples.append(sino[:, 0, 0])
samples.append(sino[:, 0, -1])
samples.append(sino[:, -1, 0])
samples.append(sino[:, -1, -1])
samples.append(sino[:, 0, 1])
# find discontinuities in the samples
steps = np.zeros((len(samples), samples[0].shape[0]))
for i in range(len(samples)):
t = np.unwrap(samples[i])
steps[i] = samples[i] - t
# if the majority believes so, add a step of PI
remove = mode(steps, axis=0)[0][0]
# obtain divmod min
twopi = 2*np.pi
minimum = divmod_neg(np.min(sino), twopi)[0]
remove += minimum*twopi
for i in range(len(sino)):
sino[i] -= remove[i] | python | def align_unwrapped(sino):
"""Align an unwrapped phase array to zero-phase
All operations are performed in-place.
"""
samples = []
if len(sino.shape) == 2:
# 2D
# take 1D samples at beginning and end of array
samples.append(sino[:, 0])
samples.append(sino[:, 1])
samples.append(sino[:, 2])
samples.append(sino[:, -1])
samples.append(sino[:, -2])
elif len(sino.shape) == 3:
# 3D
# take 1D samples at beginning and end of array
samples.append(sino[:, 0, 0])
samples.append(sino[:, 0, -1])
samples.append(sino[:, -1, 0])
samples.append(sino[:, -1, -1])
samples.append(sino[:, 0, 1])
# find discontinuities in the samples
steps = np.zeros((len(samples), samples[0].shape[0]))
for i in range(len(samples)):
t = np.unwrap(samples[i])
steps[i] = samples[i] - t
# if the majority believes so, add a step of PI
remove = mode(steps, axis=0)[0][0]
# obtain divmod min
twopi = 2*np.pi
minimum = divmod_neg(np.min(sino), twopi)[0]
remove += minimum*twopi
for i in range(len(sino)):
sino[i] -= remove[i] | [
"def",
"align_unwrapped",
"(",
"sino",
")",
":",
"samples",
"=",
"[",
"]",
"if",
"len",
"(",
"sino",
".",
"shape",
")",
"==",
"2",
":",
"# 2D",
"# take 1D samples at beginning and end of array",
"samples",
".",
"append",
"(",
"sino",
"[",
":",
",",
"0",
... | Align an unwrapped phase array to zero-phase
All operations are performed in-place. | [
"Align",
"an",
"unwrapped",
"phase",
"array",
"to",
"zero",
"-",
"phase"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_preproc.py#L7-L46 | train | 46,287 |
RI-imaging/ODTbrain | odtbrain/_preproc.py | divmod_neg | def divmod_neg(a, b):
"""Return divmod with closest result to zero"""
q, r = divmod(a, b)
# make sure r is close to zero
sr = np.sign(r)
if np.abs(r) > b/2:
q += sr
r -= b * sr
return q, r | python | def divmod_neg(a, b):
"""Return divmod with closest result to zero"""
q, r = divmod(a, b)
# make sure r is close to zero
sr = np.sign(r)
if np.abs(r) > b/2:
q += sr
r -= b * sr
return q, r | [
"def",
"divmod_neg",
"(",
"a",
",",
"b",
")",
":",
"q",
",",
"r",
"=",
"divmod",
"(",
"a",
",",
"b",
")",
"# make sure r is close to zero",
"sr",
"=",
"np",
".",
"sign",
"(",
"r",
")",
"if",
"np",
".",
"abs",
"(",
"r",
")",
">",
"b",
"/",
"2"... | Return divmod with closest result to zero | [
"Return",
"divmod",
"with",
"closest",
"result",
"to",
"zero"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_preproc.py#L49-L57 | train | 46,288 |
RI-imaging/ODTbrain | odtbrain/_preproc.py | sinogram_as_radon | def sinogram_as_radon(uSin, align=True):
r"""Compute the phase from a complex wave field sinogram
This step is essential when using the ray approximation before
computation of the refractive index with the inverse Radon
transform.
Parameters
----------
uSin: 2d or 3d complex ndarray
The background-corrected sinogram of the complex scattered wave
:math:`u(\mathbf{r})/u_0(\mathbf{r})`. The first axis iterates
through the angles :math:`\phi_0`.
align: bool
Tries to correct for a phase offset in the phase sinogram.
Returns
-------
phase: 2d or 3d real ndarray
The unwrapped phase array corresponding to `uSin`.
See Also
--------
skimage.restoration.unwrap_phase: phase unwrapping
radontea.backproject_3d: e.g. reconstruction via backprojection
"""
ndims = len(uSin.shape)
if ndims == 2:
# unwrapping is very important
phiR = np.unwrap(np.angle(uSin), axis=-1)
else:
# Unwrap gets the dimension of the problem from the input
# data. Since we have a sinogram, we need to pass it the
# slices one by one.
phiR = np.angle(uSin)
for ii in range(len(phiR)):
phiR[ii] = unwrap_phase(phiR[ii], seed=47)
if align:
align_unwrapped(phiR)
return phiR | python | def sinogram_as_radon(uSin, align=True):
r"""Compute the phase from a complex wave field sinogram
This step is essential when using the ray approximation before
computation of the refractive index with the inverse Radon
transform.
Parameters
----------
uSin: 2d or 3d complex ndarray
The background-corrected sinogram of the complex scattered wave
:math:`u(\mathbf{r})/u_0(\mathbf{r})`. The first axis iterates
through the angles :math:`\phi_0`.
align: bool
Tries to correct for a phase offset in the phase sinogram.
Returns
-------
phase: 2d or 3d real ndarray
The unwrapped phase array corresponding to `uSin`.
See Also
--------
skimage.restoration.unwrap_phase: phase unwrapping
radontea.backproject_3d: e.g. reconstruction via backprojection
"""
ndims = len(uSin.shape)
if ndims == 2:
# unwrapping is very important
phiR = np.unwrap(np.angle(uSin), axis=-1)
else:
# Unwrap gets the dimension of the problem from the input
# data. Since we have a sinogram, we need to pass it the
# slices one by one.
phiR = np.angle(uSin)
for ii in range(len(phiR)):
phiR[ii] = unwrap_phase(phiR[ii], seed=47)
if align:
align_unwrapped(phiR)
return phiR | [
"def",
"sinogram_as_radon",
"(",
"uSin",
",",
"align",
"=",
"True",
")",
":",
"ndims",
"=",
"len",
"(",
"uSin",
".",
"shape",
")",
"if",
"ndims",
"==",
"2",
":",
"# unwrapping is very important",
"phiR",
"=",
"np",
".",
"unwrap",
"(",
"np",
".",
"angle... | r"""Compute the phase from a complex wave field sinogram
This step is essential when using the ray approximation before
computation of the refractive index with the inverse Radon
transform.
Parameters
----------
uSin: 2d or 3d complex ndarray
The background-corrected sinogram of the complex scattered wave
:math:`u(\mathbf{r})/u_0(\mathbf{r})`. The first axis iterates
through the angles :math:`\phi_0`.
align: bool
Tries to correct for a phase offset in the phase sinogram.
Returns
-------
phase: 2d or 3d real ndarray
The unwrapped phase array corresponding to `uSin`.
See Also
--------
skimage.restoration.unwrap_phase: phase unwrapping
radontea.backproject_3d: e.g. reconstruction via backprojection | [
"r",
"Compute",
"the",
"phase",
"from",
"a",
"complex",
"wave",
"field",
"sinogram"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_preproc.py#L60-L102 | train | 46,289 |
RI-imaging/ODTbrain | odtbrain/_preproc.py | sinogram_as_rytov | def sinogram_as_rytov(uSin, u0=1, align=True):
r"""Convert the complex wave field sinogram to the Rytov phase
This method applies the Rytov approximation to the
recorded complex wave sinogram. To achieve this, the following
filter is applied:
.. math::
u_\mathrm{B}(\mathbf{r}) = u_\mathrm{0}(\mathbf{r})
\ln\!\left(
\frac{u_\mathrm{R}(\mathbf{r})}{u_\mathrm{0}(\mathbf{r})}
+1 \right)
This filter step effectively replaces the Born approximation
:math:`u_\mathrm{B}(\mathbf{r})` with the Rytov approximation
:math:`u_\mathrm{R}(\mathbf{r})`, assuming that the scattered
field is equal to
:math:`u(\mathbf{r})\approx u_\mathrm{R}(\mathbf{r})+
u_\mathrm{0}(\mathbf{r})`.
Parameters
----------
uSin: 2d or 3d complex ndarray
The sinogram of the complex wave
:math:`u_\mathrm{R}(\mathbf{r}) + u_\mathrm{0}(\mathbf{r})`.
The first axis iterates through the angles :math:`\phi_0`.
u0: ndarray of dimension as `uSin` or less, or int.
The incident plane wave
:math:`u_\mathrm{0}(\mathbf{r})` at the detector.
If `u0` is "1", it is assumed that the data is already
background-corrected (
`uSin` :math:`= \frac{u_\mathrm{R}(\mathbf{r})}{
u_\mathrm{0}(\mathbf{r})} + 1`
). Note that if the reconstruction distance :math:`l_\mathrm{D}`
of the original experiment is non-zero and `u0` is set to 1,
then the reconstruction will be wrong; the field is not focused
to the center of the reconstruction volume.
align: bool
Tries to correct for a phase offset in the phase sinogram.
Returns
-------
uB: 2d or 3d real ndarray
The Rytov-filtered complex sinogram
:math:`u_\mathrm{B}(\mathbf{r})`.
See Also
--------
skimage.restoration.unwrap_phase: phase unwrapping
"""
ndims = len(uSin.shape)
# imaginary part of the complex Rytov phase
phiR = np.angle(uSin / u0)
# real part of the complex Rytov phase
lna = np.log(np.absolute(uSin / u0))
if ndims == 2:
# unwrapping is very important
phiR[:] = np.unwrap(phiR, axis=-1)
else:
# Unwrap gets the dimension of the problem from the input
# data. Since we have a sinogram, we need to pass it the
# slices one by one.
for ii in range(len(phiR)):
phiR[ii] = unwrap_phase(phiR[ii], seed=47)
if align:
align_unwrapped(phiR)
# rytovSin = u0*(np.log(a/a0) + 1j*phiR)
# u0 is one - we already did background correction
# complex rytov phase:
rytovSin = 1j * phiR + lna
return u0 * rytovSin | python | def sinogram_as_rytov(uSin, u0=1, align=True):
r"""Convert the complex wave field sinogram to the Rytov phase
This method applies the Rytov approximation to the
recorded complex wave sinogram. To achieve this, the following
filter is applied:
.. math::
u_\mathrm{B}(\mathbf{r}) = u_\mathrm{0}(\mathbf{r})
\ln\!\left(
\frac{u_\mathrm{R}(\mathbf{r})}{u_\mathrm{0}(\mathbf{r})}
+1 \right)
This filter step effectively replaces the Born approximation
:math:`u_\mathrm{B}(\mathbf{r})` with the Rytov approximation
:math:`u_\mathrm{R}(\mathbf{r})`, assuming that the scattered
field is equal to
:math:`u(\mathbf{r})\approx u_\mathrm{R}(\mathbf{r})+
u_\mathrm{0}(\mathbf{r})`.
Parameters
----------
uSin: 2d or 3d complex ndarray
The sinogram of the complex wave
:math:`u_\mathrm{R}(\mathbf{r}) + u_\mathrm{0}(\mathbf{r})`.
The first axis iterates through the angles :math:`\phi_0`.
u0: ndarray of dimension as `uSin` or less, or int.
The incident plane wave
:math:`u_\mathrm{0}(\mathbf{r})` at the detector.
If `u0` is "1", it is assumed that the data is already
background-corrected (
`uSin` :math:`= \frac{u_\mathrm{R}(\mathbf{r})}{
u_\mathrm{0}(\mathbf{r})} + 1`
). Note that if the reconstruction distance :math:`l_\mathrm{D}`
of the original experiment is non-zero and `u0` is set to 1,
then the reconstruction will be wrong; the field is not focused
to the center of the reconstruction volume.
align: bool
Tries to correct for a phase offset in the phase sinogram.
Returns
-------
uB: 2d or 3d real ndarray
The Rytov-filtered complex sinogram
:math:`u_\mathrm{B}(\mathbf{r})`.
See Also
--------
skimage.restoration.unwrap_phase: phase unwrapping
"""
ndims = len(uSin.shape)
# imaginary part of the complex Rytov phase
phiR = np.angle(uSin / u0)
# real part of the complex Rytov phase
lna = np.log(np.absolute(uSin / u0))
if ndims == 2:
# unwrapping is very important
phiR[:] = np.unwrap(phiR, axis=-1)
else:
# Unwrap gets the dimension of the problem from the input
# data. Since we have a sinogram, we need to pass it the
# slices one by one.
for ii in range(len(phiR)):
phiR[ii] = unwrap_phase(phiR[ii], seed=47)
if align:
align_unwrapped(phiR)
# rytovSin = u0*(np.log(a/a0) + 1j*phiR)
# u0 is one - we already did background correction
# complex rytov phase:
rytovSin = 1j * phiR + lna
return u0 * rytovSin | [
"def",
"sinogram_as_rytov",
"(",
"uSin",
",",
"u0",
"=",
"1",
",",
"align",
"=",
"True",
")",
":",
"ndims",
"=",
"len",
"(",
"uSin",
".",
"shape",
")",
"# imaginary part of the complex Rytov phase",
"phiR",
"=",
"np",
".",
"angle",
"(",
"uSin",
"/",
"u0"... | r"""Convert the complex wave field sinogram to the Rytov phase
This method applies the Rytov approximation to the
recorded complex wave sinogram. To achieve this, the following
filter is applied:
.. math::
u_\mathrm{B}(\mathbf{r}) = u_\mathrm{0}(\mathbf{r})
\ln\!\left(
\frac{u_\mathrm{R}(\mathbf{r})}{u_\mathrm{0}(\mathbf{r})}
+1 \right)
This filter step effectively replaces the Born approximation
:math:`u_\mathrm{B}(\mathbf{r})` with the Rytov approximation
:math:`u_\mathrm{R}(\mathbf{r})`, assuming that the scattered
field is equal to
:math:`u(\mathbf{r})\approx u_\mathrm{R}(\mathbf{r})+
u_\mathrm{0}(\mathbf{r})`.
Parameters
----------
uSin: 2d or 3d complex ndarray
The sinogram of the complex wave
:math:`u_\mathrm{R}(\mathbf{r}) + u_\mathrm{0}(\mathbf{r})`.
The first axis iterates through the angles :math:`\phi_0`.
u0: ndarray of dimension as `uSin` or less, or int.
The incident plane wave
:math:`u_\mathrm{0}(\mathbf{r})` at the detector.
If `u0` is "1", it is assumed that the data is already
background-corrected (
`uSin` :math:`= \frac{u_\mathrm{R}(\mathbf{r})}{
u_\mathrm{0}(\mathbf{r})} + 1`
). Note that if the reconstruction distance :math:`l_\mathrm{D}`
of the original experiment is non-zero and `u0` is set to 1,
then the reconstruction will be wrong; the field is not focused
to the center of the reconstruction volume.
align: bool
Tries to correct for a phase offset in the phase sinogram.
Returns
-------
uB: 2d or 3d real ndarray
The Rytov-filtered complex sinogram
:math:`u_\mathrm{B}(\mathbf{r})`.
See Also
--------
skimage.restoration.unwrap_phase: phase unwrapping | [
"r",
"Convert",
"the",
"complex",
"wave",
"field",
"sinogram",
"to",
"the",
"Rytov",
"phase"
] | abbab8b790f10c0c7aea8d858d7d60f2fdd7161e | https://github.com/RI-imaging/ODTbrain/blob/abbab8b790f10c0c7aea8d858d7d60f2fdd7161e/odtbrain/_preproc.py#L105-L182 | train | 46,290 |
svenkreiss/databench | databench/utils.py | json_encoder_default | def json_encoder_default(obj):
"""Handle more data types than the default JSON encoder.
Specifically, it treats a `set` and a `numpy.array` like a `list`.
Example usage: ``json.dumps(obj, default=json_encoder_default)``
"""
if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
if obj.size == 1:
if np.issubdtype(obj.dtype, np.integer):
return int(obj)
elif np.issubdtype(obj.dtype, np.floating):
return float(obj)
if isinstance(obj, set):
return list(obj)
elif hasattr(obj, 'to_native'):
# DatastoreList, DatastoreDict
return obj.to_native()
elif hasattr(obj, 'tolist') and hasattr(obj, '__iter__'):
# for np.array
return obj.tolist()
return obj | python | def json_encoder_default(obj):
"""Handle more data types than the default JSON encoder.
Specifically, it treats a `set` and a `numpy.array` like a `list`.
Example usage: ``json.dumps(obj, default=json_encoder_default)``
"""
if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
if obj.size == 1:
if np.issubdtype(obj.dtype, np.integer):
return int(obj)
elif np.issubdtype(obj.dtype, np.floating):
return float(obj)
if isinstance(obj, set):
return list(obj)
elif hasattr(obj, 'to_native'):
# DatastoreList, DatastoreDict
return obj.to_native()
elif hasattr(obj, 'tolist') and hasattr(obj, '__iter__'):
# for np.array
return obj.tolist()
return obj | [
"def",
"json_encoder_default",
"(",
"obj",
")",
":",
"if",
"np",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"obj",
",",
"'size'",
")",
"and",
"hasattr",
"(",
"obj",
",",
"'dtype'",
")",
":",
"if",
"obj",
".",
"size",
"==",
"1",
":",
"if",
"np",
... | Handle more data types than the default JSON encoder.
Specifically, it treats a `set` and a `numpy.array` like a `list`.
Example usage: ``json.dumps(obj, default=json_encoder_default)`` | [
"Handle",
"more",
"data",
"types",
"than",
"the",
"default",
"JSON",
"encoder",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/utils.py#L13-L36 | train | 46,291 |
svenkreiss/databench | databench/utils.py | fig_to_src | def fig_to_src(figure, image_format='png', dpi=80):
"""Convert a matplotlib figure to an inline HTML image.
:param matplotlib.figure.Figure figure: Figure to display.
:param str image_format: png (default) or svg
:param int dpi: dots-per-inch for raster graphics.
:rtype: str
"""
if image_format == 'png':
f = io.BytesIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return png_to_src(f.read())
elif image_format == 'svg':
f = io.StringIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return svg_to_src(f.read()) | python | def fig_to_src(figure, image_format='png', dpi=80):
"""Convert a matplotlib figure to an inline HTML image.
:param matplotlib.figure.Figure figure: Figure to display.
:param str image_format: png (default) or svg
:param int dpi: dots-per-inch for raster graphics.
:rtype: str
"""
if image_format == 'png':
f = io.BytesIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return png_to_src(f.read())
elif image_format == 'svg':
f = io.StringIO()
figure.savefig(f, format=image_format, dpi=dpi)
f.seek(0)
return svg_to_src(f.read()) | [
"def",
"fig_to_src",
"(",
"figure",
",",
"image_format",
"=",
"'png'",
",",
"dpi",
"=",
"80",
")",
":",
"if",
"image_format",
"==",
"'png'",
":",
"f",
"=",
"io",
".",
"BytesIO",
"(",
")",
"figure",
".",
"savefig",
"(",
"f",
",",
"format",
"=",
"ima... | Convert a matplotlib figure to an inline HTML image.
:param matplotlib.figure.Figure figure: Figure to display.
:param str image_format: png (default) or svg
:param int dpi: dots-per-inch for raster graphics.
:rtype: str | [
"Convert",
"a",
"matplotlib",
"figure",
"to",
"an",
"inline",
"HTML",
"image",
"."
] | 99d4adad494b60a42af6b8bfba94dd0c41ba0786 | https://github.com/svenkreiss/databench/blob/99d4adad494b60a42af6b8bfba94dd0c41ba0786/databench/utils.py#L39-L57 | train | 46,292 |
MLAB-project/pymlab | examples/I2CSPI_HBSTEP_chain.py | axis.ReleaseSW | def ReleaseSW(self):
' Go away from Limit Switch '
while self.ReadStatusBit(2) == 1: # is Limit Switch ON ?
spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW
while self.IsBusy():
pass
self.MoveWait(10) | python | def ReleaseSW(self):
' Go away from Limit Switch '
while self.ReadStatusBit(2) == 1: # is Limit Switch ON ?
spi.SPI_write(self.CS, [0x92, 0x92] | (~self.Dir & 1)) # release SW
while self.IsBusy():
pass
self.MoveWait(10) | [
"def",
"ReleaseSW",
"(",
"self",
")",
":",
"while",
"self",
".",
"ReadStatusBit",
"(",
"2",
")",
"==",
"1",
":",
"# is Limit Switch ON ?",
"spi",
".",
"SPI_write",
"(",
"self",
".",
"CS",
",",
"[",
"0x92",
",",
"0x92",
"]",
"|",
"(",
"~",
"self",
"... | Go away from Limit Switch | [
"Go",
"away",
"from",
"Limit",
"Switch"
] | d18d858ae83b203defcf2aead0dbd11b3c444658 | https://github.com/MLAB-project/pymlab/blob/d18d858ae83b203defcf2aead0dbd11b3c444658/examples/I2CSPI_HBSTEP_chain.py#L55-L61 | train | 46,293 |
johntruckenbrodt/spatialist | spatialist/vector.py | feature2vector | def feature2vector(feature, ref, layername=None):
"""
create a Vector object from ogr features
Parameters
----------
feature: list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature`
a single feature or a list of features
ref: Vector
a reference Vector object to retrieve geo information from
layername: str or None
the name of the output layer; retrieved from `ref` if `None`
Returns
-------
Vector
the new Vector object
"""
features = feature if isinstance(feature, list) else [feature]
layername = layername if layername is not None else ref.layername
vec = Vector(driver='Memory')
vec.addlayer(layername, ref.srs, ref.geomType)
feat_def = features[0].GetDefnRef()
fields = [feat_def.GetFieldDefn(x) for x in range(0, feat_def.GetFieldCount())]
vec.layer.CreateFields(fields)
for feat in features:
vec.layer.CreateFeature(feat)
vec.init_features()
return vec | python | def feature2vector(feature, ref, layername=None):
"""
create a Vector object from ogr features
Parameters
----------
feature: list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature`
a single feature or a list of features
ref: Vector
a reference Vector object to retrieve geo information from
layername: str or None
the name of the output layer; retrieved from `ref` if `None`
Returns
-------
Vector
the new Vector object
"""
features = feature if isinstance(feature, list) else [feature]
layername = layername if layername is not None else ref.layername
vec = Vector(driver='Memory')
vec.addlayer(layername, ref.srs, ref.geomType)
feat_def = features[0].GetDefnRef()
fields = [feat_def.GetFieldDefn(x) for x in range(0, feat_def.GetFieldCount())]
vec.layer.CreateFields(fields)
for feat in features:
vec.layer.CreateFeature(feat)
vec.init_features()
return vec | [
"def",
"feature2vector",
"(",
"feature",
",",
"ref",
",",
"layername",
"=",
"None",
")",
":",
"features",
"=",
"feature",
"if",
"isinstance",
"(",
"feature",
",",
"list",
")",
"else",
"[",
"feature",
"]",
"layername",
"=",
"layername",
"if",
"layername",
... | create a Vector object from ogr features
Parameters
----------
feature: list of :osgeo:class:`ogr.Feature` or :osgeo:class:`ogr.Feature`
a single feature or a list of features
ref: Vector
a reference Vector object to retrieve geo information from
layername: str or None
the name of the output layer; retrieved from `ref` if `None`
Returns
-------
Vector
the new Vector object | [
"create",
"a",
"Vector",
"object",
"from",
"ogr",
"features"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L782-L810 | train | 46,294 |
johntruckenbrodt/spatialist | spatialist/vector.py | intersect | def intersect(obj1, obj2):
"""
intersect two Vector objects
Parameters
----------
obj1: Vector
the first vector object; this object is reprojected to the CRS of obj2 if necessary
obj2: Vector
the second vector object
Returns
-------
Vector
the intersect of obj1 and obj2
"""
if not isinstance(obj1, Vector) or not isinstance(obj2, Vector):
raise RuntimeError('both objects must be of type Vector')
obj1 = obj1.clone()
obj2 = obj2.clone()
obj1.reproject(obj2.srs)
#######################################################
# create basic overlap
union1 = ogr.Geometry(ogr.wkbMultiPolygon)
# union all the geometrical features of layer 1
for feat in obj1.layer:
union1.AddGeometry(feat.GetGeometryRef())
obj1.layer.ResetReading()
union1.Simplify(0)
# same for layer2
union2 = ogr.Geometry(ogr.wkbMultiPolygon)
for feat in obj2.layer:
union2.AddGeometry(feat.GetGeometryRef())
obj2.layer.ResetReading()
union2.Simplify(0)
# intersection
intersect_base = union1.Intersection(union2)
union1 = None
union2 = None
#######################################################
# compute detailed per-geometry overlaps
if intersect_base.GetArea() > 0:
intersection = Vector(driver='Memory')
intersection.addlayer('intersect', obj1.srs, ogr.wkbPolygon)
fieldmap = []
for index, fielddef in enumerate([obj1.fieldDefs, obj2.fieldDefs]):
for field in fielddef:
name = field.GetName()
i = 2
while name in intersection.fieldnames:
name = '{}_{}'.format(field.GetName(), i)
i += 1
fieldmap.append((index, field.GetName(), name))
intersection.addfield(name, type=field.GetType(), width=field.GetWidth())
for feature1 in obj1.layer:
geom1 = feature1.GetGeometryRef()
if geom1.Intersects(intersect_base):
for feature2 in obj2.layer:
geom2 = feature2.GetGeometryRef()
# select only the intersections
if geom2.Intersects(intersect_base):
intersect = geom2.Intersection(geom1)
fields = {}
for item in fieldmap:
if item[0] == 0:
fields[item[2]] = feature1.GetField(item[1])
else:
fields[item[2]] = feature2.GetField(item[1])
intersection.addfeature(intersect, fields)
intersect_base = None
return intersection | python | def intersect(obj1, obj2):
"""
intersect two Vector objects
Parameters
----------
obj1: Vector
the first vector object; this object is reprojected to the CRS of obj2 if necessary
obj2: Vector
the second vector object
Returns
-------
Vector
the intersect of obj1 and obj2
"""
if not isinstance(obj1, Vector) or not isinstance(obj2, Vector):
raise RuntimeError('both objects must be of type Vector')
obj1 = obj1.clone()
obj2 = obj2.clone()
obj1.reproject(obj2.srs)
#######################################################
# create basic overlap
union1 = ogr.Geometry(ogr.wkbMultiPolygon)
# union all the geometrical features of layer 1
for feat in obj1.layer:
union1.AddGeometry(feat.GetGeometryRef())
obj1.layer.ResetReading()
union1.Simplify(0)
# same for layer2
union2 = ogr.Geometry(ogr.wkbMultiPolygon)
for feat in obj2.layer:
union2.AddGeometry(feat.GetGeometryRef())
obj2.layer.ResetReading()
union2.Simplify(0)
# intersection
intersect_base = union1.Intersection(union2)
union1 = None
union2 = None
#######################################################
# compute detailed per-geometry overlaps
if intersect_base.GetArea() > 0:
intersection = Vector(driver='Memory')
intersection.addlayer('intersect', obj1.srs, ogr.wkbPolygon)
fieldmap = []
for index, fielddef in enumerate([obj1.fieldDefs, obj2.fieldDefs]):
for field in fielddef:
name = field.GetName()
i = 2
while name in intersection.fieldnames:
name = '{}_{}'.format(field.GetName(), i)
i += 1
fieldmap.append((index, field.GetName(), name))
intersection.addfield(name, type=field.GetType(), width=field.GetWidth())
for feature1 in obj1.layer:
geom1 = feature1.GetGeometryRef()
if geom1.Intersects(intersect_base):
for feature2 in obj2.layer:
geom2 = feature2.GetGeometryRef()
# select only the intersections
if geom2.Intersects(intersect_base):
intersect = geom2.Intersection(geom1)
fields = {}
for item in fieldmap:
if item[0] == 0:
fields[item[2]] = feature1.GetField(item[1])
else:
fields[item[2]] = feature2.GetField(item[1])
intersection.addfeature(intersect, fields)
intersect_base = None
return intersection | [
"def",
"intersect",
"(",
"obj1",
",",
"obj2",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj1",
",",
"Vector",
")",
"or",
"not",
"isinstance",
"(",
"obj2",
",",
"Vector",
")",
":",
"raise",
"RuntimeError",
"(",
"'both objects must be of type Vector'",
")",
... | intersect two Vector objects
Parameters
----------
obj1: Vector
the first vector object; this object is reprojected to the CRS of obj2 if necessary
obj2: Vector
the second vector object
Returns
-------
Vector
the intersect of obj1 and obj2 | [
"intersect",
"two",
"Vector",
"objects"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L813-L887 | train | 46,295 |
johntruckenbrodt/spatialist | spatialist/vector.py | Vector.addfield | def addfield(self, name, type, width=10):
"""
add a field to the vector layer
Parameters
----------
name: str
the field name
type: int
the OGR Field Type (OFT), e.g. ogr.OFTString.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
width: int
the width of the new field (only for ogr.OFTString fields)
Returns
-------
"""
fieldDefn = ogr.FieldDefn(name, type)
if type == ogr.OFTString:
fieldDefn.SetWidth(width)
self.layer.CreateField(fieldDefn) | python | def addfield(self, name, type, width=10):
"""
add a field to the vector layer
Parameters
----------
name: str
the field name
type: int
the OGR Field Type (OFT), e.g. ogr.OFTString.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
width: int
the width of the new field (only for ogr.OFTString fields)
Returns
-------
"""
fieldDefn = ogr.FieldDefn(name, type)
if type == ogr.OFTString:
fieldDefn.SetWidth(width)
self.layer.CreateField(fieldDefn) | [
"def",
"addfield",
"(",
"self",
",",
"name",
",",
"type",
",",
"width",
"=",
"10",
")",
":",
"fieldDefn",
"=",
"ogr",
".",
"FieldDefn",
"(",
"name",
",",
"type",
")",
"if",
"type",
"==",
"ogr",
".",
"OFTString",
":",
"fieldDefn",
".",
"SetWidth",
"... | add a field to the vector layer
Parameters
----------
name: str
the field name
type: int
the OGR Field Type (OFT), e.g. ogr.OFTString.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
width: int
the width of the new field (only for ogr.OFTString fields)
Returns
------- | [
"add",
"a",
"field",
"to",
"the",
"vector",
"layer"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L140-L161 | train | 46,296 |
johntruckenbrodt/spatialist | spatialist/vector.py | Vector.addlayer | def addlayer(self, name, srs, geomType):
"""
add a layer to the vector layer
Parameters
----------
name: str
the layer name
srs: int, str or :osgeo:class:`osr.SpatialReference`
the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options.
geomType: int
an OGR well-known binary data type.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
Returns
-------
"""
self.vector.CreateLayer(name, srs, geomType)
self.init_layer() | python | def addlayer(self, name, srs, geomType):
"""
add a layer to the vector layer
Parameters
----------
name: str
the layer name
srs: int, str or :osgeo:class:`osr.SpatialReference`
the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options.
geomType: int
an OGR well-known binary data type.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
Returns
-------
"""
self.vector.CreateLayer(name, srs, geomType)
self.init_layer() | [
"def",
"addlayer",
"(",
"self",
",",
"name",
",",
"srs",
",",
"geomType",
")",
":",
"self",
".",
"vector",
".",
"CreateLayer",
"(",
"name",
",",
"srs",
",",
"geomType",
")",
"self",
".",
"init_layer",
"(",
")"
] | add a layer to the vector layer
Parameters
----------
name: str
the layer name
srs: int, str or :osgeo:class:`osr.SpatialReference`
the spatial reference system. See :func:`spatialist.auxil.crsConvert` for options.
geomType: int
an OGR well-known binary data type.
See `Module ogr <https://gdal.org/python/osgeo.ogr-module.html>`_.
Returns
------- | [
"add",
"a",
"layer",
"to",
"the",
"vector",
"layer"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L163-L182 | train | 46,297 |
johntruckenbrodt/spatialist | spatialist/vector.py | Vector.addvector | def addvector(self, vec):
"""
add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
-------
"""
vec.layer.ResetReading()
for feature in vec.layer:
self.layer.CreateFeature(feature)
self.init_features()
vec.layer.ResetReading() | python | def addvector(self, vec):
"""
add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
-------
"""
vec.layer.ResetReading()
for feature in vec.layer:
self.layer.CreateFeature(feature)
self.init_features()
vec.layer.ResetReading() | [
"def",
"addvector",
"(",
"self",
",",
"vec",
")",
":",
"vec",
".",
"layer",
".",
"ResetReading",
"(",
")",
"for",
"feature",
"in",
"vec",
".",
"layer",
":",
"self",
".",
"layer",
".",
"CreateFeature",
"(",
"feature",
")",
"self",
".",
"init_features",
... | add a vector object to the layer of the current Vector object
Parameters
----------
vec: Vector
the vector object to add
merge: bool
merge overlapping polygons?
Returns
------- | [
"add",
"a",
"vector",
"object",
"to",
"the",
"layer",
"of",
"the",
"current",
"Vector",
"object"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L184-L203 | train | 46,298 |
johntruckenbrodt/spatialist | spatialist/vector.py | Vector.bbox | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
create a bounding box from the extent of the Vector object
Parameters
----------
outname: str or None
the name of the vector file to be written; if None, a Vector object is returned
format: str
the name of the file format to write
overwrite: bool
overwrite an already existing file?
Returns
-------
Vector or None
if outname is None, the bounding box Vector object
"""
if outname is None:
return bbox(self.extent, self.srs)
else:
bbox(self.extent, self.srs, outname=outname, format=format, overwrite=overwrite) | python | def bbox(self, outname=None, format='ESRI Shapefile', overwrite=True):
"""
create a bounding box from the extent of the Vector object
Parameters
----------
outname: str or None
the name of the vector file to be written; if None, a Vector object is returned
format: str
the name of the file format to write
overwrite: bool
overwrite an already existing file?
Returns
-------
Vector or None
if outname is None, the bounding box Vector object
"""
if outname is None:
return bbox(self.extent, self.srs)
else:
bbox(self.extent, self.srs, outname=outname, format=format, overwrite=overwrite) | [
"def",
"bbox",
"(",
"self",
",",
"outname",
"=",
"None",
",",
"format",
"=",
"'ESRI Shapefile'",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"outname",
"is",
"None",
":",
"return",
"bbox",
"(",
"self",
".",
"extent",
",",
"self",
".",
"srs",
")",
... | create a bounding box from the extent of the Vector object
Parameters
----------
outname: str or None
the name of the vector file to be written; if None, a Vector object is returned
format: str
the name of the file format to write
overwrite: bool
overwrite an already existing file?
Returns
-------
Vector or None
if outname is None, the bounding box Vector object | [
"create",
"a",
"bounding",
"box",
"from",
"the",
"extent",
"of",
"the",
"Vector",
"object"
] | 007f49296a156de8d7168ad235b5a5b8e8d3633d | https://github.com/johntruckenbrodt/spatialist/blob/007f49296a156de8d7168ad235b5a5b8e8d3633d/spatialist/vector.py#L205-L226 | train | 46,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.