Best Python code snippet using pytest-benchmark
taurussynopticwidget.py
Source:taurussynopticwidget.py
1"""2A Taurus based TANGO backend for the SVG synoptic.3"""4from inspect import isclass5import json6import numpy as np7from PyQt4 import QtCore8import PyTango9from synopticwidget import SynopticWidget10from taurus import Attribute, Manager, Release11from taurus.core.taurusbasetypes import (12 AttrQuality, TaurusEventType, TaurusSerializationMode)13from taurus.external.qt import Qt14TAURUS_VERSION = Release.version_info[0]15try:16 from taurus.qt.qtgui.container import TaurusWidget17except ImportError:18 from taurus.qt.qtgui.panel import TaurusWidget19from taurus.qt.qtgui.panel import TaurusDevicePanel20from taurus.qt.qtgui.application import TaurusApplication21try:22 from taurus.core.tango.enums import DevState23except ImportError:24 from PyTango import DevState, AttrQuality25from .taurusregistry import Registry26class TooltipUpdater(QtCore.QThread):27 finished = QtCore.pyqtSignal(str, str)28 def __init__(self, model):29 QtCore.QThread.__init__(self)30 self.model = model31 def run(self):32 # TODO: This needs to be redone; maybe use string.template?33 try:34 attribute = Attribute(str(self.model) + "/State")35 if attribute:36 value = attribute.read()37 html = json.dumps('Value: ' +38 '<span class="value">%s</span>'39 % value.value)40 self.finished.emit(self.model, html)41 except PyTango.DevFailed as e:42 print e43def getStateClasses(state=None):44 "Return a state CSS class configuration"45 states = dict((("state-%s" % name), s == state)46 for name, s in PyTango.DevState.names.items())47 states["state"] = True48 return states49# precalculate since this is done quite a lot50STATE_CLASSES = dict((state, json.dumps(getStateClasses(state)))51 for name, state in PyTango.DevState.names.items())52STATE_CLASSES[None] = json.dumps(getStateClasses())53# lookup table to get state name as a string54STATE_MAP = {code: name for name, code in PyTango.DevState.names.items()}55class TaurusSynopticWidget(SynopticWidget, TaurusWidget):56 """A SynopticWidget that connects to TANGO in order to57 get updates for models (attributes)."""58 tooltip_trigger = QtCore.pyqtSignal(str)59 def __init__(self, parent=None, **kwargs):60 super(TaurusSynopticWidget, self).__init__(parent=parent)61 print('init TaurusSynopticWidget')62 Manager().setSerializationMode(TaurusSerializationMode.Serial)63 self.tooltip_trigger.connect(self._update_device_tooltip)64 self._panels = {}65 def setModel(self, image, section=None):66 self.set_url(image)67 self.registry = Registry(self.attribute_listener,68 self.unsubscribe_listener)69 self.registry.start()70 self.js.plugin_command.connect(self.run_plugin_command)71 self.js.hovered.connect(self._hovered)72 # self._tooltip_data = {}73 # self.tooltip_registry = Registry(self._tooltip_updater)74 # self.tooltip_registry.start()75 def _hovered(self, sec, mods):76 attr = self.registry.get_listener(str(mods))77 def getModel(self):78 return self._url79 def closeEvent(self, event):80 "Clean things up when the widget is closed"81 self.registry.clear()82 self.registry.stop()83 self.registry.wait()84 self.registry = None85 def run_plugin_command(self, plugin, cmd, args):86 try:87 plugins = __import__("plugins.%s" % plugin, globals(),88 locals(), [cmd], -1)89 except ImportError as e:90 print "Could not initialize plugin '%s'!" % plugin91 print e92 return ""93 return getattr(plugins, cmd)(self, args)94 def handle_subscriptions(self, models=[]):95 print "handle_subscriptions ", models96 if self.registry:97 self.registry.subscribe(models)98 def unsubscribe_listener(self, unsubscribed):99 """Tell the synoptic about unsubscribed models. This is100 needed because it's all asunchronous so it cannot be assumed101 that a model is really unsubscribed until it is."""102 classes = STATE_CLASSES[None]103 for model in unsubscribed:104 self.js.evaluate("synoptic.setClasses('model', %r, %s)" %105 (model, classes))106 def filter_fragment(self, model, value):107 # the "fragment" is an optional part at the end of an eval attribute,108 # prefixed by a "#" and intended to make it possible to "filter" only109 # part of a spectrum or image through "slicing". It is up to the110 # client to do this, so we implement it here.111 frag = self.registry.eval_validator.getNames(model, fragment=True)[3]112 if frag:113 indices = frag[1:-1]114 try:115 # this is the special case where the slice is just an index116 # I'm not 100% that this should be allowed, but it's so useful!117 index = int(indices)118 return value[index]119 except ValueError:120 pass121 try:122 slice_ = [int(i) for i in indices.split(":")]123 return value[slice(*slice_)]124 except ValueError:125 pass126 return value127 def attribute_listener(self, model, evt_src, evt_type, evt_value):128 "Handle events"129 if evt_type == TaurusEventType.Error:130 return # handle errors somehow131 if evt_type == TaurusEventType.Config:132 return # need to do something here too133 value = evt_value.value134 # check for the presence of a "fragment" ending (e.g. ...#[3])135 if self.registry and self.registry.eval_validator.isValid(model):136 try:137 value = self.filter_fragment(model, value)138 except Exception:139 pass # fragment is a taurus 4 feature140 # handle the value differently depending on what it is141 # TODO: clean this up!142 quality = evt_value.quality143 quality_string = str(PyTango.AttrQuality.values[quality])144 if isinstance(value, (DevState, PyTango.DevState,145 PyTango._PyTango.DevState)):146 classes = STATE_CLASSES[value]147 device, attr = model.rsplit("/", 1)148 state = STATE_MAP[value]149 data = {"value": state, "quality": quality_string}150 if attr.lower() == "state":151 # this is the normal "State" attribute of the152 # device. Let's set the color of device models153 # too, for convenience.154 self.js.evaluate("synoptic.setClasses('model', %r, %s)" %155 (device, classes))156 self.js.evaluate("synoptic.setClasses('model', '%s/State', %s)" %157 (device, classes))158 self.js.evaluate("synoptic.setData('model', %r, %r)" %159 (device, data))160 self.js.evaluate("synoptic.setData('model', '%s/State', %r)" %161 (device, data))162 else:163 # Apparently it's an attribute of type DevState164 # but it is not the normal "State" attribute.165 self.js.evaluate("synoptic.setClasses('model', %r, %s)" %166 (model, classes))167 self.js.evaluate("synoptic.setData('model', %r, %s)" %168 (model, data))169 self.js.evaluate("synoptic.setText('model', %r, '%s')" %170 (model, value))171 elif isinstance(value, (bool, np.bool_)):172 classes = {"boolean": True,173 "boolean-true": bool(value),174 "boolean-false": not value}175 self.js.evaluate("synoptic.setClasses('model', %r, %s)" %176 (model, json.dumps(classes)))177 self.js.evaluate("synoptic.setText('model', %r, '%s')" %178 (model, value))179 self.js.evaluate("synoptic.setData('model', %r, %s)" %180 (model,181 json.dumps({"value": str(value).lower(),182 "quality": quality_string})))183 else:184 # everything else needs to be displayed as text185 if quality == PyTango.AttrQuality.ATTR_INVALID:186 text = "?" # do something more sophisticated here187 else:188 # TODO: need more sophisticated logic here; currently189 # spectrums/images break completely. I'm not sure190 # we should even support those...191 try:192 if TAURUS_VERSION == 4:193 fmt = evt_src.getFormat()194 value = fmt%value # taurus4 issue: values without format195 text = evt_src.displayValue(value)196 except AttributeError:197 text = str(value)198 try:199 unit = evt_src.getConfig().unit200 except AttributeError:201 unit = None202 if unit in (None, "No unit"):203 unit = ""204 self.js.evaluate("synoptic.setText('model', %r, '%s %s')" %205 (model, text, unit))206 self.js.evaluate("synoptic.setData('model', %r, %s)" %207 (model, json.dumps({"value": text,208 "quality": quality_string})))209 def on_click(self, kind, name):210 """The default behavior is to mark a clicked device and to zoom to a211 clicked section. Override this function if you need something212 else.213 """214 print "on_click", kind, name215 if kind == "model" and self.registry.device_validator.isValid(name):216 self.select(kind, [name])217 self.emit(Qt.SIGNAL("graphicItemSelected(QString)"), name)218 elif kind == "section":219 self.zoom_to(kind, name)220 else:221 self.unselect_all()222 def get_device_panel(self, device):223 """Override to change which panel is opened for a given device224 name. Return a widget class, a widget, or None if you're225 handling the panel yourself. TaurusDevicePanel is a reasonable226 fallback.227 """228 return TaurusDevicePanel229 def on_rightclick(self, kind, name):230 "The default behavior for right clicking a device is to open a panel."231 if kind == "model" and self.registry.device_validator.isValid(name):232 if name.lower() in self._panels:233 widget = self._panels[name.lower()]234 print "Found existing panel for %s:" % name, widget235 if not widget.isVisible():236 widget.show()237 widget.activateWindow()238 widget.raise_()239 return240 # check if we recognise the class of the device241 widget = self.get_device_panel(name)242 if not widget:243 # assume that the widget is handled somewhere else244 return245 if isclass(widget):246 # assume it's a widget class247 widget = widget()248 try:249 # try to set the model250 widget.setModel(name)251 except AttributeError:252 pass253 widget.setWindowTitle(name)254 # monkey patch to cleanup on close...255 widget.closeEvent = lambda _: self._cleanup_panel(widget)256 # keep a reference to the widget257 self._panels[name.lower()] = widget258 widget.show()259 def _cleanup_panel(self, w):260 """In the long run it seems like a good idea to try and clean up261 closed panels. In particular, the Taurus polling thread can262 become pretty bogged down."""263 if self.registry:264 with self.registry.lock:265 print "cleaning up panel for", w.getModel(), "..."266 self._panels.pop(str(w.getModel()).lower(), None)267 w.setModel(None)268 print "done!"269 # Note: the tooltip stuff is broken and not currently in use.270 # Currently there is only the default tooltip which displays the271 # model name.272 def on_tooltip(self, models):273 # FIXME: looks like tooltip listeners aren't cleaned up until a new274 # tooltip is displayed. This seems wasteful.275 if models:276 all_models = []277 for model in models:278 if self.registry.device_validator.isValid(model):279 all_models.append(model + "/State")280 all_models.append(model + "/Status")281 else:282 all_models.append(model)283 try:284 self.tooltip_registry.subscribe(all_models)285 except ValueError:286 pass287 self._tooltip_data = dict((str(model), {}) for model in models)288 else:289 self.tooltip_registry.subscribe()290 self._tooltip_data.clear()291 def _tooltip_updater(self, model, attr_value):292 value = attr_value.value293 device, attr = model.rsplit("/", 1)294 if attr in ("State", "Status"):295 if attr == "Status":296 # hack to keep newlines297 value = value.replace("\n", "<br>")298 self._tooltip_data.setdefault(device, {})[attr] = value299 #dev = evt_src.getParentObj()300 #info = dev.getHWObj().info()301 # self._tooltip_data[device]["Class"] = info.dev_class302 self.tooltip_trigger.emit(device)303 else:304 self._tooltip_data[model] = value305 def _update_device_tooltip(self, device):306 # TODO: redo this in a neat way.307 data = {"Class": "...", "State": "...", "Status": "..."}308 data.update(self._tooltip_data[device])309 html = json.dumps(310 ('<div>Class: <span>{Class}</span></div>' +311 '<div>State: <span class="{State}">{State}</span></div>' +312 '<div>Status: <span>{Status}</span></div>').format(**data))313 self.js.evaluate('synoptic.setTooltipHTML("%s", %s)' %314 (device, html))315 def closeEvent(self, event):316 # Get rid of all opened panels, otherwise the application will317 # not exit cleanly.318 super(TaurusSynopticWidget, self).closeEvent(event)319 for model, panel in self._panels.items():320 print "closing panel for", model321 panel.close()322if __name__ == '__main__':323 import sys324 print sys.argv[1]325 # qapp = Qt.QApplication([])326 app = TaurusApplication()327 sw = TaurusSynopticWidget()328 app.focusChanged.connect(sw.onFocus)329 sw.setModel(sys.argv[1])330 sw.show()...
histogram.py
Source:histogram.py
...25 if isinstance(val, Iterable):26 return self._value_format(val), val[7]27 else:28 return sup(x, *args)29 def _tooltip_data(self, node, value, x, y, classes=None, xlabel=None):30 super(CustomBox, self)._tooltip_data(node, value[0], x, y, classes=classes, xlabel=None)31 self.svg.node(node, 'desc', class_="x_label").text = value[1]32def make_plot(benchmarks, title, adjustment):33 class Style(DefaultStyle):34 colors = ["#000000" if row["path"] else DefaultStyle.colors[1]35 for row in benchmarks]36 font_family = 'Consolas, "Deja Vu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace'37 minimum = int(min(row["min"] * adjustment for row in benchmarks))38 maximum = int(max(39 min(row["max"], row["hd15iqr"]) * adjustment40 for row in benchmarks41 ) + 1)42 try:43 import pygaljs44 except ImportError:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!