output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Returns the version of the libiperf library | Here you have a function in Python 3, explain what it does
def iperf_version(self):
# TODO: Is there a better way to get the const char than allocating 30?
VersionType = c_char * 30
return VersionType.in_dll(self.lib, "version").value.decode('utf-8') | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _error_to_string(self, error_id):
"""Returns an error string from libiperf
:param error_id: The error_id produced by libiperf
:rtype: string
"""
strerror = self.lib.iperf_strerror
strerror.restype = c_char_p
return strerror(error_id).decode('utf-8') | Write a Python 3 function for
returning an error string from libiperf | As a Python code analyst, you investigate and solve complex coding mysteries |
def server_hostname(self):
"""The server hostname to connect to.
Accepts DNS entries or IP addresses.
:rtype: string
"""
result = c_char_p(
self.lib.iperf_get_test_server_hostname(self._test)
).value
if result:
self._server_hostname = res... | Write a Python 3 function that can
return the server hostname to connect to. | As a Python code analyst, you investigate and solve complex coding mysteries |
The iperf3 instance protocol | Make a summary of the following Python 3 code
def protocol(self):
proto_id = self.lib.iperf_get_test_protocol_id(self._test)
if proto_id == SOCK_STREAM:
self._protocol = 'tcp'
elif proto_id == SOCK_DGRAM:
self._protocol = 'udp'
return self._protocol | As a python code expert, you are capable of creating scripts from specifications. |
The test startup duration to omit in seconds. | Explain what the following Python 3 code does
def omit(self):
self._omit = self.lib.iperf_get_test_omit(self._test)
return self._omit | You are a Python code generator, capable of creating scripts from specifications. |
def bandwidth(self):
"""Target bandwidth in bits/sec"""
self._bandwidth = self.lib.iperf_get_test_rate(self._test)
return self._bandwidth | How would you implement a function in Python 3 that
targets bandwidth in bits / sec | You are a Python code generator, capable of creating scripts from specifications. |
Toggles direction of test in the order of the test | How would you explain what the following Python 3 function does
def reverse(self):
enabled = self.lib.iperf_get_test_reverse(self._test)
if enabled:
self._reverse = True
else:
self._reverse = False
return self._reverse | You are a Python code analyst, evaluating scripts for potential improvements. |
def run(self):
"""Run the current test client.
:rtype: instance of :class:`TestResult`
"""
if self.json_output:
output_to_pipe(self._pipe_in) # Disable stdout
error = self.lib.iperf_run_client(self._test)
if not self.iperf_version.startswith('iperf ... | How would you implement a function in Python 3 that
runs the current test client. | As a Python code analyst, you investigate and solve complex coding mysteries |
def run(self):
"""Run the iperf3 server instance.
:rtype: instance of :class:`TestResult`
"""
def _run_in_thread(self, data_queue):
"""Runs the iperf_run_server
:param data_queue: thread-safe queue
"""
output_to_pipe(self._pipe_in) # di... | How would you code a function in Python 3 to
run the iperf3 server instance. | As a Python code composer, you craft elegant and concise scripts. |
Create a set of subplots for the specified number of rows and columns. | Can you generate the documentation for the following Python 3 function
def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, hemisphere='lower', projection='equal_area',
**fig_kw):
"""
Identical to matplotlib.pyplot.subplots, except that this will defa... | You are a Python code generator, capable of creating scripts from specifications. |
Makes a fault - and - striae plot for normal faults
with the given strikes dips and rakes. | Here you have a function in Python 3, explain what it does
def fault_and_striae_plot(ax, strikes, dips, rakes):
# Plot the planes
lines = ax.plane(strikes, dips, 'k-', lw=0.5)
# Calculate the position of the rake of the lineations, but don't plot yet
x, y = mplstereonet.rake(strikes, dips, rakes)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Makes a tangent lineation plot for normal faults with the given strikes dips and rakes. | Can you generate the documentation for the following Python 3 function
def tangent_lineation_plot(ax, strikes, dips, rakes):
# Calculate the position of the rake of the lineations, but don't plot yet
rake_x, rake_y = mplstereonet.rake(strikes, dips, rakes)
# Calculate the direction the arrows should point
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read data from a text file on disk. | Can you generate a brief explanation for the following Python 3 code
def load():
# Get the data file relative to this file's location...
datadir = os.path.dirname(__file__)
filename = os.path.join(datadir, 'angelier_data.txt')
data = []
with open(filename, 'r') as infile:
for line in infile... | As a Python code composer, you craft elegant and concise scripts. |
def density_grid(*args, **kwargs):
"""
Estimates point density of the given linear orientation measurements
(Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes
based on the `measurement` keyword argument.). Returns a regular (in
lat-long space) grid of density estimates over a hem... | Write a Python 3 function that can
return a regular grid of point density estimates for the given linear orientation measurements. | You are a Python code analyst, evaluating scripts for potential improvements. |
Kernel function from Vollmer for exponential smoothing. | Given the following Python 3 function, write the documentation
def _exponential_kamb(cos_dist, sigma=3):
n = float(cos_dist.size)
f = 2 * (1.0 + n / sigma**2)
count = np.exp(f * (cos_dist - 1))
units = np.sqrt(n * (f/2.0 - 1) / f**2)
return count, units | As a Python code analyst, you investigate and solve complex coding mysteries |
def _linear_inverse_kamb(cos_dist, sigma=3):
"""Kernel function from Vollmer for linear smoothing."""
n = float(cos_dist.size)
radius = _kamb_radius(n, sigma)
f = 2 / (1 - radius)
cos_dist = cos_dist[cos_dist >= radius]
count = (f * (cos_dist - radius))
return count, _kamb_units(n, radius) | Create a Python 3 function for
kerneling function from Vollmer for linear smoothing. | As a Python code analyst, you investigate and solve complex coding mysteries |
Original Kamb kernel function ( raw count within radius ). | How would you explain what the following Python 3 function does
def _kamb_count(cos_dist, sigma=3):
n = float(cos_dist.size)
dist = _kamb_radius(n, sigma)
count = (cos_dist >= dist).astype(float)
return count, _kamb_units(n, dist) | You are a Python code analyst, evaluating scripts for potential improvements. |
Schmidt counting kernel function. | Can you generate the documentation for the following Python 3 function
def _schmidt_count(cos_dist, sigma=None):
radius = 0.01
count = ((1 - cos_dist) <= radius).astype(float)
# To offset the count.sum() - 0.5 required for the kamb methods...
count = 0.5 / count.size + count
return count, (cos_dist.... | You are a Python code analyst, evaluating scripts for potential improvements. |
The affine portion of the base transform. This is called by _set_lim_and_transforms. | Explain what the following Python 3 code does
def _get_affine_transform(self):
# How big is the projected globe?
# In the case of a stereonet, it's actually constant.
xscale = yscale = self._scale
# Create an affine transform to stretch the projection from 0-1
return Affine2D() \... | As a python code expert, you are capable of creating scripts from specifications. |
Setup the key transforms for the axes. | Can you generate a brief explanation for the following Python 3 code
def _set_lim_and_transforms(self):
# Most of the transforms are set up correctly by LambertAxes
LambertAxes._set_lim_and_transforms(self)
# Transform for latitude ticks. These are typically unused, but just
# in case w... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the number of degrees between each longitude gridline. | Can you generate the documentation for the following Python 3 function
def set_longitude_grid(self, degrees):
number = (360.0 / degrees) + 1
locs = np.linspace(-np.pi, np.pi, number, True)[1:]
locs[-1] -= 0.01 # Workaround for "back" gridlines showing.
self.xaxis.set_major_locator(FixedL... | You are a Python code architect, reviewing and designing scalable and efficient code |
def set_rotation(self, rotation):
"""Set the rotation of the stereonet in degrees clockwise from North."""
self._rotation = np.radians(rotation)
self._polar.set_theta_offset(self._rotation + np.pi / 2.0)
self.transData.invalidate()
self.transAxes.invalidate()
self._set_li... | Write a Python 3 function that can
set the rotation of the stereonet in degrees clockwise from North. | As a python code expert, you are capable of creating scripts from specifications. |
Format displayed coordinates during mouseover of axes. | Given the following Python 3 function, write the documentation
def format_coord(self, x, y):
p, b = stereonet_math.geographic2plunge_bearing(x, y)
s, d = stereonet_math.geographic2pole(x, y)
pb = u'P/B={:0.0f}\u00b0/{:03.0f}\u00b0'.format(p[0], b[0])
sd = u'S/D={:03.0f}\u00b0/{:0.0f}\u00... | As a Python code analyst, you investigate and solve complex coding mysteries |
This is a simple grid of the components of the current object. | Explain what the following Python 3 code does
def grid(self, b=None, which='major', axis='both', kind='arbitrary',
center=None, **kwargs):
"""
Usage is identical to a normal axes grid except for the ``kind`` and
``center`` kwargs. ``kind="polar"`` will add a polar overlay.
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds an overlay to the current figure. | Can you generate the documentation for the following Python 3 function
def _add_overlay(self, center):
plunge, bearing = stereonet_math.geographic2plunge_bearing(*center)
lon0, lat0 = center
fig = self.get_figure()
self._overlay_axes = fig.add_axes(self.get_position(True),
... | As a Python code composer, you craft elegant and concise scripts. |
def set_azimuth_ticks(self, angles, labels=None, frac=None, **kwargs):
"""
Sets the azimuthal tick locations (Note: tick lines are not currently
drawn or supported.).
Parameters
----------
angles : sequence of numbers
The tick locations in degrees.
la... | Write a Python 3 script for
setting the azimuthal tick locations. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the labels for the azimuthal ticks. | Can you generate a brief explanation for the following Python 3 code
def set_azimuth_ticklabels(self, labels, fontdict=None, **kwargs):
return self._polar.set_xticklabels(labels, fontdict, **kwargs) | You are a Python code architect, reviewing and designing scalable and efficient code |
def plane(self, strike, dip, *args, **kwargs):
"""
Plot lines representing planes on the axes. Additional arguments and
keyword arguments are passed on to `ax.plot`.
Parameters
----------
strike, dip : number or sequences of numbers
The strike and dip of the ... | How would you code a function in Python 3 to
plot lines representing planes on the axes. | As a Python code composer, you craft elegant and concise scripts. |
def pole(self, strike, dip, *args, **kwargs):
"""
Plot points representing poles to planes on the axes. Additional
arguments and keyword arguments are passed on to `ax.plot`.
Parameters
----------
strike, dip : numbers or sequences of numbers
The strike and d... | Implement a Python 3 function for
plotting points representing poles to planes on the axes. | You are a Python code generator, capable of creating scripts from specifications. |
Plot points along planes on the axes. | Here you have a function in Python 3, explain what it does
def rake(self, strike, dip, rake_angle, *args, **kwargs):
lon, lat = stereonet_math.rake(strike, dip, rake_angle)
args, kwargs = self._point_plot_defaults(args, kwargs)
return self.plot(lon, lat, *args, **kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
Plot points representing linear features on the axes. | Can you generate the documentation for the following Python 3 function
def line(self, plunge, bearing, *args, **kwargs):
lon, lat = stereonet_math.line(plunge, bearing)
args, kwargs = self._point_plot_defaults(args, kwargs)
return self.plot([lon], [lat], *args, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is used to set the default values for the point plot. | Can you generate the documentation for the following Python 3 function
def _point_plot_defaults(self, args, kwargs):
if args:
return args, kwargs
if 'ls' not in kwargs and 'linestyle' not in kwargs:
kwargs['linestyle'] = 'none'
if 'marker' not in kwargs:
kwar... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _contour_helper(self, args, kwargs):
"""Unify defaults and common functionality of ``density_contour`` and
``density_contourf``."""
contour_kwargs = {}
contour_kwargs['measurement'] = kwargs.pop('measurement', 'poles')
contour_kwargs['method'] = kwargs.pop('method', 'exponent... | Implement a Python 3 function for
unifying defaults and common functionality of density_contour and . | You are a Python code architect, reviewing and designing scalable and efficient code |
def density_contour(self, *args, **kwargs):
"""
Estimates point density of the given linear orientation measurements
(Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes
based on the `measurement` keyword argument.) and plots contour lines of
the resulting densi... | Can you create a Python 3 function that
estimates point density of the given linear orientation measurements (Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes based on the `measurement` keyword argument.) and plots contour lines of the resulting density distribution. Parameters ---------- *args : A... | As a Python code analyst, you investigate and solve complex coding mysteries |
def density_contourf(self, *args, **kwargs):
"""
Estimates point density of the given linear orientation measurements
(Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes
based on the `measurement` keyword argument.) and plots filled contours
of the resulting de... | Implement a Python 3 function for
estimating point density of the given linear orientation measurements (Interpreted as poles, lines, rakes, or "raw" longitudes and latitudes based on the `measurement` keyword argument.) and plots filled contours of the resulting density distribution. Parameters ---------- *args : A va... | You are a Python code generator, capable of creating scripts from specifications. |
def basic():
"""Set up a basic stereonet and plot the same data each time."""
fig, ax = mplstereonet.subplots()
strike, dip = 315, 30
ax.plane(strike, dip, color='lightblue')
ax.pole(strike, dip, color='green', markersize=15)
ax.rake(strike, dip, 40, marker='*', markersize=20, color='green')
... | Can you create a Python 3 function that
sets up a basic stereonet and plot the same data each time. | You are a Python code analyst, evaluating scripts for potential improvements. |
Example to explain azimuth and dip on a lower - helisphere stereonet. | Make a summary of the following Python 3 code
def stereonet_projection_explanation(ax):
ax.set_title('Dip and Azimuth', y=1.1, size=18)
# Set the azimuth ticks to be just "N", "E", etc.
ax.set_azimuth_ticks(range(0, 360, 10))
# Hackishly set some of the azimuth labels to North, East, etc...
fmt = ... | As a Python code composer, you craft elegant and concise scripts. |
Example showing how the native longitude and latitude relate to the
stereonet projection. | How would you explain what the following Python 3 function does
def native_projection_explanation(ax):
ax.set_title('Longitude and Latitude', size=18, y=1.1)
# Hide the azimuth labels
ax.set_azimuth_ticklabels([])
# Make the axis tick labels visible:
ax.set_xticks(np.radians(np.arange(-80, 90, 10)... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a white halo around the xlabels. | Given the following Python 3 function, write the documentation
def xlabel_halo(ax):
import matplotlib.patheffects as effects
for tick in ax.get_xticklabels() + [ax.xaxis.label]:
tick.set_path_effects([effects.withStroke(linewidth=4, foreground='w')]) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parses the strike and dip measurement strings and returns the strike and dip measurements. | Given the following Python 3 function, write the documentation
def parse_strike_dip(strike, dip):
strike = parse_azimuth(strike)
dip, direction = split_trailing_letters(dip)
if direction is not None:
expected_direc = strike + 90
if opposite_end(expected_direc, direction):
strike... | As a python code expert, you are capable of creating scripts from specifications. |
def parse_rake(strike, dip, rake):
"""
Parses strings of strike, dip, and rake and returns a strike, dip, and rake
measurement following the right-hand-rule, with the "end" of the strike
that the rake is measured from indicated by the sign of the rake (positive
rakes correspond to the strike directi... | Write a Python 3 function for
parsing a strike and dip measurement and returns a strike dip and rake. | As a Python code composer, you craft elegant and concise scripts. |
def parse_plunge_bearing(plunge, bearing):
"""
Parses strings of plunge and bearing and returns a consistent plunge and
bearing measurement as floats. Plunge angles returned by this function will
always be between 0 and 90.
If no direction letter(s) is present, the plunge is assumed to be measured
... | Write a Python 3 script for
parsing a string of plunge and bearing and returns a consistent plunge and bearing measurement as floats. | You are a Python code architect, reviewing and designing scalable and efficient code |
def dip_direction2strike(azimuth):
"""
Converts a planar measurment of dip direction using the dip-azimuth
convention into a strike using the right-hand-rule.
Parameters
----------
azimuth : number or string
The dip direction of the plane in degrees. This can be either a
numeric... | Can you create a Python 3 function that
converts a planar measurment of dip direction using the dip - azimuth convention into a strike using the right - hand - rule. | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts a planar measurement of strike using the right - hand - rule into the dip - direction that the plane dips. | Can you generate the documentation for the following Python 3 function
def strike2dip_direction(strike):
strike = parse_azimuth(strike)
dip_direction = strike + 90
if dip_direction > 360:
dip_direction -= 360
return dip_direction | As a Python code composer, you craft elegant and concise scripts. |
Parses an azimuth measurement in azimuth or quadrant format. | Can you tell what is the following Python 3 function doing
def parse_azimuth(azimuth):
try:
azimuth = float(azimuth)
except ValueError:
if not azimuth[0].isalpha():
raise ValueError('Ambiguous azimuth: {}'.format(azimuth))
azimuth = parse_quadrant_measurement(azimuth)
ret... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_quadrant_measurement(quad_azimuth):
"""
Parses a quadrant measurement of the form "AxxB", where A and B are cardinal
directions and xx is an angle measured relative to those directions.
In other words, it converts a measurement such as E30N into an azimuth of
60 degrees, or W10S into an a... | How would you implement a function in Python 3 that
parses a measurement of the form AxxB or AxxB into an azimuth of the next 260 degrees. | As a Python code composer, you craft elegant and concise scripts. |
def inverted(self):
"""Return the inverse of the transform."""
# This is a bit of hackery so that we can put a single "inverse"
# function here. If we just made "self._inverse_type" point to the class
# in question, it wouldn't be defined yet. This way, it's done at
# at runtime ... | How would you implement a function in Python 3 that
returns the inverse of the transform. | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts a longitude and latitude given in
_radians_ to cartesian coordinates. | Can you tell what is the following Python 3 function doing
def sph2cart(lon, lat):
x = np.cos(lat)*np.cos(lon)
y = np.cos(lat)*np.sin(lon)
z = np.sin(lat)
return x, y, z | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cart2sph(x, y, z):
"""
Converts cartesian coordinates `x`, `y`, `z` into a longitude and latitude.
x=0, y=0, z=0 is assumed to correspond to the center of the globe.
Returns lon and lat in radians.
Parameters
----------
`x`, `y`, `z` : Arrays of cartesian coordinates
Returns
--... | Create a Python 3 function to
convert cartesian coordinates x y z into a longitude and latitude in radians. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _rotate(lon, lat, theta, axis='x'):
"""
Rotate "lon", "lat" coords (in _degrees_) about the X-axis by "theta"
degrees. This effectively simulates rotating a physical stereonet.
Returns rotated lon, lat coords in _radians_).
"""
# Convert input to numpy arrays in radians
lon, lat = np.at... | Can you write a function in Python 3 where it
rotates a node on a given axis by the given angle. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def antipode(lon, lat):
"""
Calculates the antipode (opposite point on the globe) of the given point or
points. Input and output is expected to be in radians.
Parameters
----------
lon : number or sequence of numbers
Longitude in radians
lat : number or sequence of numbers
L... | Implement a function in Python 3 to
calculate the antipode of the given point or sequence of numbers lon lat. | As a python code expert, you are capable of creating scripts from specifications. |
def plane(strike, dip, segments=100, center=(0, 0)):
"""
Calculates the longitude and latitude of `segments` points along the
stereonet projection of each plane with a given `strike` and `dip` in
degrees. Returns points for one hemisphere only.
Parameters
----------
strike : number or sequ... | Write a Python 3 script for
calculating the longitude and latitude of each plane in the base set of points. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Calculates the longitude and latitude of the pole to the plane. | Make a summary of the following Python 3 code
def pole(strike, dip):
strike, dip = np.atleast_1d(strike, dip)
mask = dip > 90
dip[mask] = 180 - dip[mask]
strike[mask] += 180
# Plot the approriate point for a strike of 0 and rotate it
lon, lat = -dip, 0.0
lon, lat = _rotate(lon, lat, strike)
... | You are a Python code generator, capable of creating scripts from specifications. |
Calculates the longitude and latitude of the linear feature specified by strike dip and rake_angle. | Explain what the following Python 3 code does
def rake(strike, dip, rake_angle):
strike, dip, rake_angle = np.atleast_1d(strike, dip, rake_angle)
# Plot the approriate point for a strike of 0 and rotate it
dip = 90 - dip
lon = dip
rake_angle = rake_angle.copy()
rake_angle[rake_angle < 0] += 180... | As a python code expert, you are capable of creating scripts from specifications. |
Calculates the longitude and latitude of the linear feature specified by the plunge and bearing. | Here you have a function in Python 3, explain what it does
def line(plunge, bearing):
plunge, bearing = np.atleast_1d(plunge, bearing)
# Plot the approriate point for a bearing of 0 and rotate it
lat = 90 - plunge
lon = 0
lon, lat = _rotate(lon, lat, bearing)
return lon, lat | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the longitude and latitude of a small circle. | How would you explain what the following Python 3 function does
def cone(plunge, bearing, angle, segments=100):
plunges, bearings, angles = np.atleast_1d(plunge, bearing, angle)
lons, lats = [], []
for plunge, bearing, angle in zip(plunges, bearings, angles):
lat = (90 - angle) * np.ones(segments, d... | As a python code expert, you are capable of creating scripts from specifications. |
def plunge_bearing2pole(plunge, bearing):
"""
Converts the given `plunge` and `bearing` in degrees to a strike and dip
of the plane whose pole would be parallel to the line specified. (i.e. The
pole to the plane returned would plot at the same point as the specified
plunge and bearing.)
Paramet... | Write a Python 3 script for
converting the given plunge and bearing in degrees to a strike and dip tuple. | As a Python code composer, you craft elegant and concise scripts. |
Converts the given strike and dip in dgrees of a plane to a plunge
and bearing of its pole. | Given the following Python 3 function, write the documentation
def pole2plunge_bearing(strike, dip):
strike, dip = np.atleast_1d(strike, dip)
bearing = strike - 90
plunge = 90 - dip
bearing[bearing < 0] += 360
return plunge, bearing | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the resultant vector from a series of longitudes and latitudes. | Can you generate a brief explanation for the following Python 3 code
def mean_vector(lons, lats):
xyz = sph2cart(lons, lats)
xyz = np.vstack(xyz).T
mean_vec = xyz.mean(axis=0)
r_value = np.linalg.norm(mean_vec)
mean_vec = cart2sph(*mean_vec)
return mean_vec, r_value | As a python code expert, you are capable of creating scripts from specifications. |
Function that calculates the Fisher statistics for a set of longitudes and latitudes. | Can you generate the documentation for the following Python 3 function
def fisher_stats(lons, lats, conf=95):
xyz = sph2cart(lons, lats)
xyz = np.vstack(xyz).T
mean_vec = xyz.mean(axis=0)
r_value = np.linalg.norm(mean_vec)
num = xyz.shape[0]
mean_vec = cart2sph(*mean_vec)
if num > 1:
... | As a python code expert, you are capable of creating scripts from specifications. |
Converts a longitude and latitude from a stereonet into a strike and dip tuple. | Given the following Python 3 function, write the documentation
def geographic2pole(lon, lat):
plunge, bearing = geographic2plunge_bearing(lon, lat)
strike = bearing + 90
strike[strike >= 360] -= 360
dip = 90 - plunge
return strike, dip | You are a Python code analyst, evaluating scripts for potential improvements. |
def geographic2plunge_bearing(lon, lat):
"""
Converts longitude and latitude in stereonet coordinates into a
plunge/bearing.
Parameters
----------
lon, lat : numbers or sequences of numbers
Longitudes and latitudes in radians as measured from a
lower-hemisphere stereonet
Re... | Write a Python 3 script for
converting longitude and latitude in stereonet coordinates into plunge and bearing arrays. | You are a Python code generator, capable of creating scripts from specifications. |
def plane_intersection(strike1, dip1, strike2, dip2):
"""
Finds the intersection of two planes. Returns a plunge/bearing of the linear
intersection of the two planes.
Also accepts sequences of strike1s, dip1s, strike2s, dip2s.
Parameters
----------
strike1, dip1 : numbers or sequences of n... | Write a Python 3 function for
finding the intersection of two strikes and dips. | As a python code expert, you are capable of creating scripts from specifications. |
def project_onto_plane(strike, dip, plunge, bearing):
"""
Projects a linear feature(s) onto the surface of a plane. Returns a rake
angle(s) along the plane.
This is also useful for finding the rake angle of a feature that already
intersects the plane in question.
Parameters
----------
... | Can you implement a function in Python 3 that
projects a linear feature onto the surface of a plane. | As a Python code analyst, you investigate and solve complex coding mysteries |
def azimuth2rake(strike, dip, azimuth):
"""
Projects an azimuth of a linear feature onto a plane as a rake angle.
Parameters
----------
strike, dip : numbers
The strike and dip of the plane in degrees following the
right-hand-rule.
azimuth : numbers
The azimuth of the li... | Write a Python 3 function that can
project an azimuth of a linear feature onto a plane as a rake angle. Parameters ---------- strike, dip : numbers The strike and dip of the plane in degrees following the right-hand-rule. azimuth : numbers The azimuth of the linear feature in degrees clockwise from north (i.e. a 0-360 ... | You are a Python code generator, capable of creating scripts from specifications. |
def xyz2stereonet(x, y, z):
"""
Converts x, y, z in _world_ cartesian coordinates into lower-hemisphere
stereonet coordinates.
Parameters
----------
x, y, z : array-likes
Sequences of world coordinates
Returns
-------
lon, lat : arrays
Sequences of longitudes and la... | Implement a Python 3 function for
converting x y z in _world_ cartesian coordinates into lower - helisphere stereonet coordinates. | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts a sequence of longitudes and latitudes from a lower - helisphere stereonet into _world_ x y z coordinates. | Make a summary of the following Python 3 code
def stereonet2xyz(lon, lat):
lon, lat = np.atleast_1d(lon, lat)
x, y, z = sph2cart(lon, lat)
return y, z, -x | You are a Python code generator, capable of creating scripts from specifications. |
def angular_distance(first, second, bidirectional=True):
"""
Calculate the angular distance between two linear features or elementwise
angular distance between two sets of linear features. (Note: a linear
feature in this context is a point on a stereonet represented
by a single latitude and longitud... | Create a Python 3 function for
calculating the angular distance between two sets of linear features or elementwise linear features or elementwise linear features. | You are a Python code generator, capable of creating scripts from specifications. |
Reproject data such that center is the north pole. Returns lon lat in the new rotated reference frame. | Explain what the following Python 3 code does
def _repole(lon, lat, center):
vec3 = sph2cart(*center)
vec3 = np.squeeze(vec3)
if not np.allclose(vec3, [0, 0, 1]):
vec1 = np.cross(vec3, [0, 0, 1])
else:
vec1 = np.cross(vec3, [1, 0, 0])
vec2 = np.cross(vec3, vec1)
vecs = [item / np... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _sd_of_eigenvector(data, vec, measurement='poles', bidirectional=True):
"""Unifies ``fit_pole`` and ``fit_girdle``."""
lon, lat = _convert_measurements(data, measurement)
vals, vecs = cov_eig(lon, lat, bidirectional)
x, y, z = vecs[:, vec]
s, d = stereonet_math.geographic2pole(*stereonet_math.ca... | Implement a function in Python 3 to
unify fit_pole and fit_girdle. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the 3D eigenvectors of the 3D covariance matrix of the avec of the specified set of measurements. | Can you generate the documentation for the following Python 3 function
def eigenvectors(*args, **kwargs):
lon, lat = _convert_measurements(args, kwargs.get('measurement', 'poles'))
vals, vecs = cov_eig(lon, lat, kwargs.get('bidirectional', True))
lon, lat = stereonet_math.cart2sph(*vecs)
plunges, bearin... | As a Python code composer, you craft elegant and concise scripts. |
Returns the mean vector for a set of measurments. | Explain what the following Python 3 code does
def find_mean_vector(*args, **kwargs):
lon, lat = _convert_measurements(args, kwargs.get('measurement', 'lines'))
vector, r_value = stereonet_math.mean_vector(lon, lat)
plunge, bearing = stereonet_math.geographic2plunge_bearing(*vector)
return (plunge[0], be... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_fisher_stats(*args, **kwargs):
"""
Returns the mean vector and summary statistics for a set of measurements.
By default, this expects the input to be plunges and bearings, but the type
of input can be controlled through the ``measurement`` kwarg.
Parameters
----------
*args : 2 or ... | Write a Python 3 function for
returning the mean vector and summary statistics for a set of measurements. | You are a Python code generator, capable of creating scripts from specifications. |
def kmeans(*args, **kwargs):
"""
Find centers of multi-modal clusters of data using a kmeans approach
modified for spherical measurements.
Parameters
----------
*args : 2 or 3 sequences of measurements
By default, this will be expected to be ``strike`` & ``dip``, both
array-lik... | Can you create a Python 3 function that
returns a new Nx2 array - like structure that can be used to create a multi - modal cluster for a set of measurements. | You are a Python code architect, reviewing and designing scalable and efficient code |
def is_disconnect(e, connection, cursor):
"""
Connection state check from SQLAlchemy:
https://bitbucket.org/sqlalchemy/sqlalchemy/src/tip/lib/sqlalchemy/dialects/postgresql/psycopg2.py
"""
if isinstance(e, OperationalError):
# these error messages from libpq: interfaces/libpq/fe-misc.c.
... | How would you code a function in Python 3 to
check if a connection is closed or not. | As a Python code analyst, you investigate and solve complex coding mysteries |
Dispose of the pool for this instance closing all connections and deleting the pool. | Make a summary of the following Python 3 code
def _dispose(self):
self.close()
# _DBProxy.dispose doesn't actually call dispose on the pool
conn_params = self.get_connection_params()
key = db_pool._serialize(**conn_params)
try:
pool = db_pool.pools[key]
except... | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the shape of data after encoding. | Can you generate a brief explanation for the following Python 3 code
def calc_fc_size(img_height, img_width):
'''Calculates shape of data after encoding.
Parameters
----------
img_height : int
Height of input image.
img_width : int
Width of input image.
Returns
-------
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the shape of data after decoding. | Given the following Python 3 function, write the documentation
def calc_im_size(img_height, img_width):
'''Calculates shape of data after decoding.
Parameters
----------
img_height : int
Height of encoded data.
img_width : int
Width of encoded data.
Returns
-------
enco... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_paths(directory):
'''Gets all the paths of non-hidden files in a directory
and returns a list of those paths.
Parameters
----------
directory : str
The directory whose contents you wish to grab.
Returns
-------
paths : List[str]
'''
fnames = [os.path.join(dir... | Can you write a function in Python 3 where it
gets all the paths of non - hidden files in a directory and returns a list of those paths. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Resizes all images with given paths to new dimensions. | Can you generate a brief explanation for the following Python 3 code
def image_resize(file_paths, new_dir, width, height):
'''Resizes all images with given paths to new dimensions.
Uses up/downscaling with antialiasing.
Parameters
----------
file_paths : List[str]
List of path strings f... | As a python code expert, you are capable of creating scripts from specifications. |
Transform latent vectors into images. | Here you have a function in Python 3, explain what it does
def inverse_transform(self, data, test=False):
'''Transform latent vectors into images.
Parameters
----------
data : array-like shape (n_images, latent_width)
Input numpy array of images.
test [optional] : bo... | You are a Python code generator, capable of creating scripts from specifications. |
def load_images(self, filepaths):
'''Load in image files from list of paths.
Parameters
----------
filepaths : List[str]
List of file paths of images to be loaded.
Returns
-------
images : array-like shape (n_images, n_colors, image_width, image_hei... | Create a Python 3 function to
load in image files from list of filepaths. | As a python code expert, you are capable of creating scripts from specifications. |
Fit the VAE model to the image data. | Can you generate the documentation for the following Python 3 function
def fit(
self,
img_data,
save_freq=-1,
pic_freq=-1,
n_epochs=100,
batch_size=50,
weight_decay=True,
model_path='./VAE_training_model/',
img_path='./VAE_training_images/',
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def save(self, path, name, save_meta=True):
'''Saves model as a sequence of files in the format:
{path}/{name}_{'model', 'opt', 'meta'}.h5
Parameters
----------
path : str
The directory of the file you wish to save the model to.
name : str
The... | Write a Python 3 function that can
save the current state of the class to a sequence of files in the format : . h5 . | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(cls, model, opt, meta, flag_gpu=None):
'''Loads in model as a class instance with with the specified
model and optimizer states.
Parameters
----------
model : str
Path to the model state file.
opt : str
Path to the optimizer state file... | How would you implement a function in Python 3 that
loads in model as a class instance with the specified model and optimizer states. | As a python code expert, you are capable of creating scripts from specifications. |
def fit(
self,
img_data,
save_freq=-1,
pic_freq=-1,
n_epochs=100,
batch_size=50,
weight_decay=True,
model_path='./GAN_training_model/',
img_path='./GAN_training_images/',
img_out_width=10,
mirroring=False
):
'''Fit the G... | Create a Python 3 function to
fit the GAN model to the image data. | You are a Python code architect, reviewing and designing scalable and efficient code |
Saves the current state of the class to a sequence of files in the format dec_opt meta. h5
| Can you generate the documentation for the following Python 3 function
def save(self, path, name, save_meta=True):
'''Saves model as a sequence of files in the format:
{path}/{name}_{'dec', 'disc', 'dec_opt',
'disc_opt', 'meta'}.h5
Parameters
----------
path : st... | As a python code expert, you are capable of creating scripts from specifications. |
Transform image data to latent space. | Given the following Python 3 function, write the documentation
def transform(self, data, test=False):
'''Transform image data to latent space.
Parameters
----------
data : array-like shape (n_images, image_width, image_height,
n_colors)
Inp... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fit(
self,
img_data,
gamma=1.0,
save_freq=-1,
pic_freq=-1,
n_epochs=100,
batch_size=50,
weight_decay=True,
model_path='./VAEGAN_training_model/',
img_path='./VAEGAN_training_images/',
img_out_width=10,
mirroring=False
... | How would you code a function in Python 3 to
fit the VAE model to the image data. | As a Python code composer, you craft elegant and concise scripts. |
Loads in model as a class instance with the specified
model and optimizer states. | Here you have a function in Python 3, explain what it does
def load(cls, enc, dec, disc, enc_opt, dec_opt, disc_opt, meta, flag_gpu=None):
'''Loads in model as a class instance with with the specified
model and optimizer states.
Parameters
----------
enc : str
Pat... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Compute the Jacobian determinant of a quadratic surface. | Can you tell what is the following Python 3 function doing
def quadratic_jacobian_polynomial(nodes):
# First evaluate the Jacobian at each of the 6 nodes.
jac_parts = _helpers.matrix_product(nodes, _QUADRATIC_JACOBIAN_HELPER)
jac_at_nodes = np.empty((1, 6), order="F")
jac_at_nodes[0, 0] = two_by_two_det... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Compute the Jacobian determinant of a cubic surface. | Explain what the following Python 3 code does
def cubic_jacobian_polynomial(nodes):
# First evaluate the Jacobian at each of the 15 nodes
# in the quartic triangle.
jac_parts = _helpers.matrix_product(nodes, _CUBIC_JACOBIAN_HELPER)
jac_at_nodes = np.empty((1, 15), order="F")
jac_at_nodes[0, 0] = two... | As a Python code composer, you craft elegant and concise scripts. |
r Performs one round of the de Casteljau algorithm for surfaces. | Explain what the following Python 3 code does
def _de_casteljau_one_round(nodes, degree, lambda1, lambda2, lambda3):
dimension, num_nodes = nodes.shape
num_new_nodes = num_nodes - degree - 1
new_nodes = np.empty((dimension, num_new_nodes), order="F")
index = 0
# parent_i1 = index + k
# parent_i2... | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute the matrix that computes the de Casteljau algorithm for the given degree. | Can you tell what is the following Python 3 function doing
def make_transform(degree, weights_a, weights_b, weights_c):
num_nodes = ((degree + 1) * (degree + 2)) // 2
id_mat = np.eye(num_nodes, order="F")
# Pre-compute the matrices that do the reduction so we don't
# have to **actually** perform the de ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Converts a reduced values dictionary into a matrix. | Can you generate a brief explanation for the following Python 3 code
def reduced_to_matrix(shape, degree, vals_by_weight):
result = np.empty(shape, order="F")
index = 0
for k in six.moves.xrange(degree + 1):
for j in six.moves.xrange(degree + 1 - k):
i = degree - j - k
key = ... | As a python code expert, you are capable of creating scripts from specifications. |
Specialize a surface to a specialization. | Make a summary of the following Python 3 code
def _specialize_surface(nodes, degree, weights_a, weights_b, weights_c):
# Uses A-->0, B-->1, C-->2 to represent the specialization used.
partial_vals = {
(0,): de_casteljau_one_round(nodes, degree, *weights_a),
(1,): de_casteljau_one_round(nodes, de... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subdivides a surface into four sub - surfaces. | Can you generate a brief explanation for the following Python 3 code
def _subdivide_nodes(nodes, degree):
if degree == 1:
nodes_a = _helpers.matrix_product(nodes, LINEAR_SUBDIVIDE_A)
nodes_b = _helpers.matrix_product(nodes, LINEAR_SUBDIVIDE_B)
nodes_c = _helpers.matrix_product(nodes, LINEAR_... | You are a Python code architect, reviewing and designing scalable and efficient code |
r Compute s and t partial of a Jacobian surfaces in a resource set. | Here you have a function in Python 3, explain what it does
def _jacobian_both(nodes, degree, dimension):
_, num_nodes = nodes.shape
result = np.empty((2 * dimension, num_nodes - degree - 1), order="F")
result[:dimension, :] = jacobian_s(nodes, degree, dimension)
result[dimension:, :] = jacobian_t(nodes,... | As a python code expert, you are capable of creating scripts from specifications. |
This function returns the intersection class for the tangent curves at the given tangent vectors. | Here you have a function in Python 3, explain what it does
def classify_tangent_intersection(
intersection, nodes1, tangent1, nodes2, tangent2
):
"""Helper for func:`classify_intersection` at tangencies.
.. note::
This is a helper used only by :func:`classify_intersection`.
Args:
inter... | You are a Python code analyst, evaluating scripts for potential improvements. |
Check if an edge lies inside another edge. | How would you explain what the following Python 3 function does
def ignored_edge_corner(edge_tangent, corner_tangent, corner_previous_edge):
cross_prod = _helpers.cross_product(
edge_tangent.ravel(order="F"), corner_tangent.ravel(order="F")
)
# A negative cross product indicates that ``edge_tangent`... | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.