INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Tab completion hook for the %%opts cell magic. | def option_completer(cls, k,v):
"Tab completion hook for the %%opts cell magic."
line = v.text_until_cursor
completions = cls.setup_completer()
compositor_defs = {el.group:el.output_type.__name__
for el in Compositor.definitions if el.group}
return cls.... |
Registers the Link | def link(self):
"""
Registers the Link
"""
if self.source in self.registry:
links = self.registry[self.source]
params = {
k: v for k, v in self.get_param_values() if k != 'name'}
for link in links:
link_params = {
... |
Unregisters the Link | def unlink(self):
"""
Unregisters the Link
"""
links = self.registry.get(self.source)
if self in links:
links.pop(links.index(self)) |
Get factors for categorical axes. | def _get_factors(self, element):
"""
Get factors for categorical axes.
"""
if not element.kdims:
xfactors, yfactors = [element.label], []
else:
factors = [key for key in element.groupby(element.kdims).data.keys()]
if element.ndims > 1:
... |
Map elements from given order array to bins of start and end values for radius or angle dimension. | def _get_bins(self, kind, order, reverse=False):
"""
Map elements from given `order` array to bins of start and end values
for radius or angle dimension.
"""
if kind == "radius":
start = self.max_radius * self.radius_inner
end = self.max_radius
e... |
Extract first and second value from tuples of mapped bins. | def _get_bounds(mapper, values):
"""
Extract first and second value from tuples of mapped bins.
"""
array = np.array([mapper.get(x) for x in values])
return array[:, 0], array[:, 1] |
Limit hover tool to annular wedges only. | def _postprocess_hover(self, renderer, source):
"""
Limit hover tool to annular wedges only.
"""
if isinstance(renderer.glyph, AnnularWedge):
super(RadialHeatMapPlot, self)._postprocess_hover(renderer, source) |
Supply custom static extents because radial heatmaps always have the same boundaries. | def get_extents(self, view, ranges, range_type='combined'):
"""Supply custom, static extents because radial heatmaps always have
the same boundaries.
"""
if range_type not in ('data', 'combined'):
return (None,)*4
lower = -self.radius_outer
upper = 2 * self.ma... |
Create dictionary containing default ColumnDataSource glyph to data mappings. | def get_default_mapping(self, z, cmapper):
"""Create dictionary containing default ColumnDataSource glyph to data
mappings.
"""
map_annular = dict(x=self.max_radius, y=self.max_radius,
inner_radius="inner_radius",
outer_radius="oute... |
Helper function to convert values to corresponding dimension type. | def _pprint(self, element, dim_label, vals):
"""Helper function to convert values to corresponding dimension type.
"""
if vals.dtype.kind not in 'SU':
dim = element.gridded.get_dimension(dim_label)
return [dim.pprint_value(v) for v in vals]
return vals |
Helper function to compute tick mappings based on ticks and default orders and bins. | def _compute_tick_mapping(self, kind, order, bins):
"""Helper function to compute tick mappings based on `ticks` and
default orders and bins.
"""
if kind == "angle":
ticks = self.xticks
reverse = True
elif kind == "radius":
ticks = self.ytick... |
Generate ColumnDataSource dictionary for segment labels. | def _get_seg_labels_data(self, order_seg, bins_seg):
"""Generate ColumnDataSource dictionary for segment labels.
"""
if self.xticks is None:
return dict(x=[], y=[], text=[], angle=[])
mapping = self._compute_tick_mapping("angle", order_seg, bins_seg)
values = [(te... |
Generate ColumnDataSource dictionary for annular labels. | def _get_ann_labels_data(self, order_ann, bins_ann):
"""Generate ColumnDataSource dictionary for annular labels.
"""
if self.yticks is None:
return dict(x=[], y=[], text=[], angle=[])
mapping = self._compute_tick_mapping("radius", order_ann, bins_ann)
values = [(la... |
Helper function to get marker positions depending on mark type. | def _get_markers(marks, order, bins):
"""Helper function to get marker positions depending on mark type.
"""
if callable(marks):
markers = [x for x in order if marks(x)]
elif isinstance(marks, list):
markers = [order[x] for x in marks]
elif isinstance(ma... |
Generate ColumnDataSource dictionary for segment separation lines. | def _get_xmarks_data(self, order_seg, bins_seg):
"""Generate ColumnDataSource dictionary for segment separation lines.
"""
if not self.xmarks:
return dict(xs=[], ys=[])
angles = self._get_markers(self.xmarks, order_seg, bins_seg)
inner = self.max_radius * self.rad... |
Generate ColumnDataSource dictionary for segment separation lines. | def _get_ymarks_data(self, order_ann, bins_ann):
"""Generate ColumnDataSource dictionary for segment separation lines.
"""
if not self.ymarks:
return dict(radius=[])
radius = self._get_markers(self.ymarks, order_ann, bins_ann)
return dict(radius=radius) |
Merge a collection of AttrTree objects. | def merge(cls, trees):
"""
Merge a collection of AttrTree objects.
"""
first = trees[0]
for tree in trees:
first.update(tree)
return first |
Returns the path up to the root for the current node. | def path(self):
"Returns the path up to the root for the current node."
if self.parent:
return '.'.join([self.parent.path, str(self.identifier)])
else:
return self.identifier if self.identifier else self.__class__.__name__ |
Updated the contents of the current AttrTree with the contents of a second AttrTree. | def update(self, other):
"""
Updated the contents of the current AttrTree with the
contents of a second AttrTree.
"""
if not isinstance(other, AttrTree):
raise Exception('Can only update with another AttrTree type.')
fixed_status = (self.fixed, other.fixed)
... |
Set the given value at the supplied path where path is either a tuple of strings or a string in A. B. C format. | def set_path(self, path, val):
"""
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format.
"""
path = tuple(path.split('.')) if isinstance(path , str) else tuple(path)
disallowed = [p for p in path if not type(self)._... |
Filters the loaded AttrTree using the supplied path_filters. | def filter(self, path_filters):
"""
Filters the loaded AttrTree using the supplied path_filters.
"""
if not path_filters: return self
# Convert string path filters
path_filters = [tuple(pf.split('.')) if not isinstance(pf, tuple)
else pf for pf in... |
Propagate the value up to the root node. | def _propagate(self, path, val):
"""
Propagate the value up to the root node.
"""
if val == '_DELETE':
if path in self.data:
del self.data[path]
else:
items = [(key, v) for key, v in self.data.items()
if not... |
Get a node of the AttrTree using its path string. | def get(self, identifier, default=None):
"""Get a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The indexed node of the AttrTree
"""
split... |
Pop a node of the AttrTree using its path string. | def pop(self, identifier, default=None):
"""Pop a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The node that was removed from the AttrTree
"""
... |
Filter event values that do not originate from the plotting handles associated with a particular stream using their ids to match them. | def _filter_msg(self, msg, ids):
"""
Filter event values that do not originate from the plotting
handles associated with a particular stream using their
ids to match them.
"""
filtered_msg = {}
for k, v in msg.items():
if isinstance(v, dict) and 'id' i... |
Find all requested plotting handles and cache them along with the IDs of the models the callbacks will be attached to. | def _init_plot_handles(self):
"""
Find all requested plotting handles and cache them along
with the IDs of the models the callbacks will be attached to.
"""
plots = [self.plot]
if self.plot.subplots:
plots += list(self.plot.subplots.values())
handles ... |
Gather the ids of the plotting handles attached to this callback This allows checking that a stream is not given the state of a plotting handle it wasn t attached to | def _get_stream_handle_ids(self, handles):
"""
Gather the ids of the plotting handles attached to this callback
This allows checking that a stream is not given the state
of a plotting handle it wasn't attached to
"""
stream_handle_ids = defaultdict(dict)
for strea... |
Generates JS code to look up attributes on JS objects from an attributes specification dictionary. If the specification references a plotting particular plotting handle it will also generate JS code to get the ID of the object. | def attributes_js(cls, attributes):
"""
Generates JS code to look up attributes on JS objects from
an attributes specification dictionary. If the specification
references a plotting particular plotting handle it will also
generate JS code to get the ID of the object.
Sim... |
Creates a CustomJS callback that will send the requested attributes back to python. | def get_customjs(self, references, plot_id=None):
"""
Creates a CustomJS callback that will send the requested
attributes back to python.
"""
# Generate callback JS code to get all the requested data
if plot_id is None:
plot_id = self.plot.id or 'PLACEHOLDER_P... |
Generates a CustomJS callback by generating the required JS code and gathering all plotting handles and installs it on the requested callback handle. | def set_customjs_callback(self, js_callback, handle):
"""
Generates a CustomJS callback by generating the required JS
code and gathering all plotting handles and installs it on
the requested callback handle.
"""
if self.on_events:
for event in self.on_events:
... |
Resolves a Callback attribute specification looking the corresponding attribute up on the cb_obj which should be a bokeh model. If not model is supplied cb_obj is assumed to be the same as the model. | def resolve_attr_spec(cls, spec, cb_obj, model=None):
"""
Resolves a Callback attribute specification looking the
corresponding attribute up on the cb_obj, which should be a
bokeh model. If not model is supplied cb_obj is assumed to
be the same as the model.
"""
i... |
Process change events adding timeout to process multiple concerted value change at once rather than firing off multiple plot updates. | def on_change(self, attr, old, new):
"""
Process change events adding timeout to process multiple concerted
value change at once rather than firing off multiple plot updates.
"""
self._queue.append((attr, old, new))
if not self._active and self.plot.document:
... |
Process bokeh UIEvents adding timeout to process multiple concerted value change at once rather than firing off multiple plot updates. | def on_event(self, event):
"""
Process bokeh UIEvents adding timeout to process multiple concerted
value change at once rather than firing off multiple plot updates.
"""
self._queue.append((event))
if not self._active and self.plot.document:
self.plot.document... |
Trigger callback change event and triggering corresponding streams. | def process_on_event(self):
"""
Trigger callback change event and triggering corresponding streams.
"""
if not self._queue:
self._active = False
return
# Get unique event types in the queue
events = list(OrderedDict([(event.event_name, event)
... |
Set up on_change events for bokeh server interactions. | def set_server_callback(self, handle):
"""
Set up on_change events for bokeh server interactions.
"""
if self.on_events:
for event in self.on_events:
handle.on_event(event, self.on_event)
if self.on_changes:
for change in self.on_changes:
... |
Clips out of bounds values | def _process_out_of_bounds(self, value, start, end):
"Clips out of bounds values"
if isinstance(value, np.datetime64):
v = dt64_to_dt(value)
if isinstance(start, (int, float)):
start = convert_timestamp(start)
if isinstance(end, (int, float)):
... |
Traverses the supplied plot and searches for any Links on the plotted objects. | def find_links(cls, root_plot):
"""
Traverses the supplied plot and searches for any Links on
the plotted objects.
"""
plot_fn = lambda x: isinstance(x, GenericElementPlot) and not isinstance(x, GenericOverlayPlot)
plots = root_plot.traverse(lambda x: x, [plot_fn])
... |
Searches a GenericElementPlot for a Link. | def find_link(cls, plot, link=None):
"""
Searches a GenericElementPlot for a Link.
"""
registry = Link.registry.items()
for source in plot.link_sources:
if link is None:
links = [
l for src, links in registry for l in links
... |
Return the values along the requested dimension. | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... |
Clones the object overriding data and parameters. | def clone(self, data=None, shared_data=True, new_type=None, *args, **overrides):
"""Clones the object, overriding data and parameters.
Args:
data: New data replacing the existing data
shared_data (bool, optional): Whether to use existing data
new_type (optional): Typ... |
Return the values along the requested dimension. | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... |
Return the values along the requested dimension. | def dimension_values(self, dimension, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
flat (bool, optional): Whether to flatten arra... |
Get the formatted cell value for the given row and column indices. | def pprint_cell(self, row, col):
"""
Get the formatted cell value for the given row and column indices.
"""
if col > 2:
raise Exception("Only two columns available in a ItemTable.")
elif row >= self.rows:
raise Exception("Maximum row index is %d" % self.ro... |
Deprecated method to access the ItemTable value dimension values. | def values(self):
"""
Deprecated method to access the ItemTable value dimension values.
"""
self.param.warning('ItemTable values method is deprecated.')
return tuple(self.data.get(d.name, np.NaN)
for d in self.vdims) |
Hook to process the object currently being displayed. | def process_object(obj):
"Hook to process the object currently being displayed."
invalid_options = OptsMagic.process_element(obj)
if invalid_options: return invalid_options
OutputMagic.info(obj) |
Returns plot renderer and format for single frame export. | def single_frame_plot(obj):
"""
Returns plot, renderer and format for single frame export.
"""
obj = Layout.from_values(obj) if isinstance(obj, AdjointLayout) else obj
backend = Store.current_backend
renderer = Store.renderers[backend]
plot_cls = renderer.plotting_class(obj)
plot = plo... |
Only display the first frame of an animated plot | def first_frame(obj):
"Only display the first frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
plot.update(0)
return {'text/html': renderer.html(plot, fmt)} |
Only display the ( approximately ) middle frame of an animated plot | def middle_frame(obj):
"Only display the (approximately) middle frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
middle_frame = int(len(plot) / 2)
plot.update(middle_frame)
return {'text/html': renderer.html(plot, fmt)} |
Only display the last frame of an animated plot | def last_frame(obj):
"Only display the last frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
plot.update(len(plot))
return {'text/html': renderer.html(plot, fmt)} |
A decorator to wrap display hooks that return a MIME bundle or None. Additionally it handles adding output to the notebook archive saves files specified with the output magic and handles tracebacks. | def display_hook(fn):
"""
A decorator to wrap display hooks that return a MIME bundle or None.
Additionally it handles adding output to the notebook archive, saves
files specified with the output magic and handles tracebacks.
"""
@wraps(fn)
def wrapped(element):
global FULL_TRACEBACK... |
Renders any HoloViews object to HTML and displays it using the IPython display function. If raw is enabled the raw HTML is returned instead of displaying it directly. | def display(obj, raw_output=False, **kwargs):
"""
Renders any HoloViews object to HTML and displays it
using the IPython display function. If raw is enabled
the raw HTML is returned instead of displaying it directly.
"""
if not Store.loaded_backends() and isinstance(obj, Dimensioned):
ra... |
Used to render elements to an image format ( svg or png ) if requested in the display formats. | def image_display(element, max_frames, fmt):
"""
Used to render elements to an image format (svg or png) if requested
in the display formats.
"""
if fmt not in Store.display_formats:
return None
info = process_object(element)
if info:
display(HTML(info))
return
b... |
Map elements from given order array to bins ranging from start to end. | def _map_order_to_ticks(start, end, order, reverse=False):
"""Map elements from given `order` array to bins ranging from `start`
to `end`.
"""
size = len(order)
bounds = np.linspace(start, end, size + 1)
if reverse:
bounds = bounds[::-1]
mapping = list... |
Compute x and y positions for separation lines for given angles. | def _compute_separations(inner, outer, angles):
"""Compute x and y positions for separation lines for given angles.
"""
return [np.array([[a, inner], [a, outer]]) for a in angles] |
Return the lower and upper bounds of values along dimension. | def range(self, dim, data_range=True, dimension_range=True):
"""Return the lower and upper bounds of values along dimension.
Args:
dimension: The dimension to compute the range on.
data_range (bool): Compute range from data values
dimension_range (bool): Include Dime... |
Return the values along the requested dimension. | def dimension_values(self, dim, expanded=True, flat=True):
"""Return the values along the requested dimension.
Args:
dimension: The dimension to return values for
expanded (bool, optional): Whether to expand values
Whether to return the expanded values, behavior ... |
Get the type of the requested dimension. | def get_dimension_type(self, dim):
"""Get the type of the requested dimension.
Type is determined by Dimension.type attribute or common
type of the dimension values, otherwise None.
Args:
dimension: Dimension to look up by name or by index
Returns:
Decl... |
Convert dimension values to DataFrame. | def dframe(self, dimensions=None, multi_index=False):
"""Convert dimension values to DataFrame.
Returns a pandas dataframe of columns along each dimension,
either completely flat or indexed by key dimensions.
Args:
dimensions: Dimensions to return as columns
mul... |
Convert dimension values to a dictionary. | def columns(self, dimensions=None):
"""Convert dimension values to a dictionary.
Returns a dictionary of column arrays along each dimension
of the element.
Args:
dimensions: Dimensions to return as columns
Returns:
Dictionary of arrays for each dimensio... |
message receive routine for UDP link | def recv_msg(self):
'''message receive routine for UDP link'''
self.pre_message()
s = self.recv()
if len(s) > 0:
if self.first_byte:
self.auto_mavlink_version(s)
m = self.mav.parse_char(s)
if m is not None:
self.post_message(m)
... |
Send MAV_CMD_CONDITION_YAW message to point vehicle at a specified heading ( in degrees ). | def condition_yaw(heading, relative=False):
"""
Send MAV_CMD_CONDITION_YAW message to point vehicle at a specified heading (in degrees).
This method sets an absolute heading by default, but you can set the `relative` parameter
to `True` to set yaw relative to the current yaw heading.
By default th... |
Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a specified region of interest ( LocationGlobal ). The vehicle may also turn to face the ROI. | def set_roi(location):
"""
Send MAV_CMD_DO_SET_ROI message to point camera gimbal at a
specified region of interest (LocationGlobal).
The vehicle may also turn to face the ROI.
For more information see:
http://copter.ardupilot.com/common-mavlink-mission-command-messages-mav_cmd/#mav_cmd_do_se... |
Returns a LocationGlobal object containing the latitude/ longitude dNorth and dEast metres from the specified original_location. The returned LocationGlobal has the same alt value as original_location. | def get_location_metres(original_location, dNorth, dEast):
"""
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned LocationGlobal has the same `alt` value
as `original_location`.
The function is useful w... |
Returns the ground distance in metres between two LocationGlobal objects. | def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/d... |
Returns the bearing between the two LocationGlobal objects passed as parameters. | def get_bearing(aLocation1, aLocation2):
"""
Returns the bearing between the two LocationGlobal objects passed as parameters.
This method is an approximation, and may not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diy... |
Send SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal. | def goto_position_target_global_int(aLocation):
"""
Send SET_POSITION_TARGET_GLOBAL_INT command to request the vehicle fly to a specified LocationGlobal.
For more information see: https://pixhawk.ethz.ch/mavlink/#SET_POSITION_TARGET_GLOBAL_INT
See the above link for information on the type_mask (0=ena... |
Send SET_POSITION_TARGET_LOCAL_NED command to request the vehicle fly to a specified location in the North East Down frame. | def goto_position_target_local_ned(north, east, down):
"""
Send SET_POSITION_TARGET_LOCAL_NED command to request the vehicle fly to a specified
location in the North, East, Down frame.
It is important to remember that in this frame, positive altitudes are entered as negative
"Down" values. So if... |
Moves the vehicle to a position dNorth metres North and dEast metres East of the current position. | def goto(dNorth, dEast, gotoFunction=vehicle.simple_goto):
"""
Moves the vehicle to a position dNorth metres North and dEast metres East of the current position.
The method takes a function pointer argument with a single `dronekit.lib.LocationGlobal` parameter for
the target position. This allows it t... |
Move vehicle in direction based on specified velocity vectors and for the specified duration. | def send_ned_velocity(velocity_x, velocity_y, velocity_z, duration):
"""
Move vehicle in direction based on specified velocity vectors and
for the specified duration.
This uses the SET_POSITION_TARGET_LOCAL_NED command with a type mask enabling only
velocity components
(http://dev.ardupilot.c... |
Move vehicle in direction based on specified velocity vectors. | def send_global_velocity(velocity_x, velocity_y, velocity_z, duration):
"""
Move vehicle in direction based on specified velocity vectors.
This uses the SET_POSITION_TARGET_GLOBAL_INT command with type mask enabling only
velocity components
(http://dev.ardupilot.com/wiki/copter-commands-in-guided... |
Load a mission from a file into a list. The mission definition is in the Waypoint file format ( http:// qgroundcontrol. org/ mavlink/ waypoint_protocol#waypoint_file_format ). | def readmission(aFileName):
"""
Load a mission from a file into a list. The mission definition is in the Waypoint file
format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
This function is used by upload_mission().
"""
print("\nReading mission from file: %s" % aFil... |
Upload a mission from a file. | def upload_mission(aFileName):
"""
Upload a mission from a file.
"""
#Read mission from file
missionlist = readmission(aFileName)
print("\nUpload mission from a file: %s" % aFileName)
#Clear existing mission from vehicle
print(' Clear mission')
cmds = vehicle.commands
cmds.... |
Downloads the current mission and returns it in a list. It is used in save_mission () to get the file information to save. | def download_mission():
"""
Downloads the current mission and returns it in a list.
It is used in save_mission() to get the file information to save.
"""
print(" Download mission from vehicle")
missionlist=[]
cmds = vehicle.commands
cmds.download()
cmds.wait_ready()
for cmd in cm... |
Save a mission in the Waypoint file format ( http:// qgroundcontrol. org/ mavlink/ waypoint_protocol#waypoint_file_format ). | def save_mission(aFileName):
"""
Save a mission in the Waypoint file format
(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
"""
print("\nSave mission from Vehicle to file: %s" % aFileName)
#Download mission from vehicle
missionlist = download_mission()
#A... |
Print a mission file to demonstrate round trip | def printfile(aFileName):
"""
Print a mission file to demonstrate "round trip"
"""
print("\nMission file: %s" % aFileName)
with open(aFileName) as f:
for line in f:
print(' %s' % line.strip()) |
Gets distance in metres to the current waypoint. It returns None for the first waypoint ( Home location ). | def distance_to_current_waypoint():
"""
Gets distance in metres to the current waypoint.
It returns None for the first waypoint (Home location).
"""
nextwaypoint = vehicle.commands.next
if nextwaypoint==0:
return None
missionitem=vehicle.commands[nextwaypoint-1] #commands are zero i... |
Given telemetry log get a series of wpts approximating the previous flight | def position_messages_from_tlog(filename):
"""
Given telemetry log, get a series of wpts approximating the previous flight
"""
# Pull out just the global position msgs
messages = []
mlog = mavutil.mavlink_connection(filename)
while True:
try:
m = mlog.recv_match(type=['GL... |
Arms vehicle and fly to aTargetAltitude. | def arm_and_takeoff(aTargetAltitude):
"""
Arms vehicle and fly to aTargetAltitude.
"""
# Don't try to arm until autopilot is ready
while not vehicle.is_armable:
print(" Waiting for vehicle to initialise...")
time.sleep(1)
# Set mode to GUIDED for arming and takeoff:
... |
Returns a LocationGlobal object containing the latitude/ longitude dNorth and dEast metres from the specified original_location. The returned Location has the same alt value as original_location. | def get_location_metres(original_location, dNorth, dEast):
"""
Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the
specified `original_location`. The returned Location has the same `alt` value
as `original_location`.
The function is useful when yo... |
Adds a takeoff command and four waypoint commands to the current mission. The waypoints are positioned to form a square of side length 2 * aSize around the specified LocationGlobal ( aLocation ). | def adds_square_mission(aLocation, aSize):
"""
Adds a takeoff command and four waypoint commands to the current mission.
The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation).
The function assumes vehicle.commands matches the vehicle missi... |
Returns a: py: class: Vehicle object connected to the address specified by string parameter ip. Connection string parameters ( ip ) for different targets are listed in the: ref: getting started guide <get_started_connecting >. | def connect(ip,
_initialize=True,
wait_ready=None,
timeout=30,
still_waiting_callback=default_still_waiting_callback,
still_waiting_interval=1,
status_printer=None,
vehicle_class=None,
rate=4,
baud=115200,
... |
Distance away from home in meters. Returns 3D distance if down is known otherwise 2D distance. | def distance_home(self):
"""
Distance away from home, in meters. Returns 3D distance if `down` is known, otherwise 2D distance.
"""
if self.north is not None and self.east is not None:
if self.down is not None:
return math.sqrt(self.north**2 + self.east**2 + ... |
Add an attribute listener callback. | def add_attribute_listener(self, attr_name, observer):
"""
Add an attribute listener callback.
The callback function (``observer``) is invoked differently depending on the *type of attribute*.
Attributes that represent sensor values or which are used to monitor connection status are upd... |
Remove an attribute listener ( observer ) that was previously added using: py: func: add_attribute_listener. | def remove_attribute_listener(self, attr_name, observer):
"""
Remove an attribute listener (observer) that was previously added using :py:func:`add_attribute_listener`.
For example, the following line would remove a previously added vehicle 'global_frame'
observer called ``location_call... |
This method is used to update attribute observers when the named attribute is updated. | def notify_attribute_listeners(self, attr_name, value, cache=False):
"""
This method is used to update attribute observers when the named attribute is updated.
You should call it in your message listeners after updating an attribute with
information from a vehicle message.
By d... |
Decorator for attribute listeners. | def on_attribute(self, name):
"""
Decorator for attribute listeners.
The decorated function (``observer``) is invoked differently depending on the *type of attribute*.
Attributes that represent sensor values or which are used to monitor connection status are updated
whenever a m... |
Decorator for message listener callback functions. | def on_message(self, name):
"""
Decorator for message listener callback functions.
.. tip::
This is the most elegant way to define message listener callback functions.
Use :py:func:`add_message_listener` only if you need to be able to
:py:func:`remove the li... |
Adds a message listener function that will be called every time the specified message is received. | def add_message_listener(self, name, fn):
"""
Adds a message listener function that will be called every time the specified message is received.
.. tip::
We recommend you use :py:func:`on_message` instead of this method as it has a more elegant syntax.
This method is on... |
Removes a message listener ( that was previously added using: py: func: add_message_listener ). | def remove_message_listener(self, name, fn):
"""
Removes a message listener (that was previously added using :py:func:`add_message_listener`).
See :ref:`mavlink_messages` for more information.
:param String name: The name of the message for which the listener is to be removed (or '*' t... |
Current system batter status (: py: class: Battery ). | def battery(self):
"""
Current system batter status (:py:class:`Battery`).
"""
if self._voltage is None or self._current is None or self._level is None:
return None
return Battery(self._voltage, self._current, self._level) |
GPS position information (: py: class: GPSInfo ). | def gps_0(self):
"""
GPS position information (:py:class:`GPSInfo`).
"""
return GPSInfo(self._eph, self._epv, self._fix_type, self._satellites_visible) |
Returns True if the vehicle is ready to arm false otherwise ( Boolean ). | def is_armable(self):
"""
Returns ``True`` if the vehicle is ready to arm, false otherwise (``Boolean``).
This attribute wraps a number of pre-arm checks, ensuring that the vehicle has booted,
has a good GPS fix, and that the EKF pre-arm is complete.
"""
# check that mod... |
System status (: py: class: SystemStatus ). | def system_status(self):
"""
System status (:py:class:`SystemStatus`).
The status has a ``state`` property with one of the following values:
* ``UNINIT``: Uninitialized system, state is unknown.
* ``BOOT``: System is booting up.
* ``CALIBRATING``: System is calibrating ... |
True if the EKF status is considered acceptable False otherwise ( boolean ). | def ekf_ok(self):
"""
``True`` if the EKF status is considered acceptable, ``False`` otherwise (``boolean``).
"""
# legacy check for dronekit-python for solo
# use same check that ArduCopter::system.pde::position_ok() is using
if self.armed:
return self._ekf_p... |
Sets the home location ( LocationGlobal ). | def home_location(self, pos):
"""
Sets the home location (``LocationGlobal``).
The value cannot be set until it has successfully been read from the vehicle. After being
set the value is cached in the home_location attribute and does not have to be re-read.
.. note::
... |
Wait for a condition to be True. | def wait_for(self, condition, timeout=None, interval=0.1, errmsg=None):
'''Wait for a condition to be True.
Wait for condition, a callable, to return True. If timeout is
nonzero, raise a TimeoutError(errmsg) if the condition is not
True after timeout seconds. Check the condition evera... |
Wait for the vehicle to become armable. | def wait_for_armable(self, timeout=None):
'''Wait for the vehicle to become armable.
If timeout is nonzero, raise a TimeoutError if the vehicle
is not armable after timeout seconds.
'''
def check_armable():
return self.is_armable
self.wait_for(check_armable... |
Arm the vehicle. | def arm(self, wait=True, timeout=None):
'''Arm the vehicle.
If wait is True, wait for arm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not armed after timeout seconds.
'''
self.armed = True
if wait:
... |
Disarm the vehicle. | def disarm(self, wait=True, timeout=None):
'''Disarm the vehicle.
If wait is True, wait for disarm operation to complete before
returning. If timeout is nonzero, raise a TimeouTerror if the
vehicle has not disarmed after timeout seconds.
'''
self.armed = False
... |
Set the flight mode. | def wait_for_mode(self, mode, timeout=None):
'''Set the flight mode.
If wait is True, wait for the mode to change before returning.
If timeout is nonzero, raise a TimeoutError if the flight mode
hasn't changed after timeout seconds.
'''
if not isinstance(mode, VehicleMo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.