Best Python code snippet using autotest_python
cfg.py
Source:cfg.py
1##############################################################################2# (c)2021 by Oberhesse (oh20@gmx.de)3# Creative Commons CC BY-NC-SA 3.0 License4# Check the file "LICENSE" for more informations5##############################################################################6VERSION = '102'7VERSIONSTR = '1.0.2'8VERSIONDATE = '06.01.2022'9from Components.ActionMap import ActionMap10from Components.config import config, ConfigInteger, ConfigClock, ConfigSubsection, ConfigOnOff, ConfigYesNo, ConfigEnableDisable, ConfigSelection, getConfigListEntry, NoSave, ConfigNothing, ConfigText11from Components.ConfigList import ConfigListScreen12from Components.MenuList import MenuList13from Components.Label import Label14from Components.Sources.StaticText import StaticText15from enigma import getDesktop, eTimer16from datetime import datetime, timedelta17from Screens.Screen import Screen18from Screens.MessageBox import MessageBox19import json20from os import path21from __init__ import _22desktopSize = getDesktop(0).size()23scale = desktopSize.width() / 1280.024_isDebugMode = None25PATH = "/usr/lib/enigma2/python/Plugins/Extensions/Warnmeldungen/"26##############################################################################27config.plugins.Warnung = ConfigSubsection()28config.plugins.Warnung.format = ConfigSelection(default="0",29 choices=[('0', 'Vollanzeige'), ('1', 'Kompaktanzeige oben'), ('2', _('Kompaktanzeige oben einger_ueckt'))])30config.plugins.Warnung.scale = ConfigSelection(default="0", choices=[('0', 'Standard'), ('1', 'Kompakt')])31config.plugins.Warnung.ARS = ConfigText(default='')32config.plugins.Warnung.ARS2 = ConfigText(default='')33config.plugins.Warnung.duration = ConfigInteger(default=30, limits=(0, 3600))34config.plugins.Warnung.interval = ConfigInteger(default=10, limits=(0, 240))35config.plugins.Warnung.afterAlarm = ConfigSelection(default="0", choices=[('0', _('Unver_aendert')),36 ('1', _('Min_uetliche Pr_uefung f_uer 1 Stunde')), ('2', _('Min_uetliche Pr_uefung f_uer 2 Stunden')),37 ('3', _('Min_uetliche Pr_uefung f_uer 3 Stunden')), ('4', _('Min_uetliche Pr_uefung f_uer 4 Stunden'))])38config.plugins.Warnung.ignoreInterval = ConfigInteger(default=0, limits=(0, 9999))39config.plugins.Warnung.resetOnStart = ConfigYesNo(default=True)40config.plugins.Warnung.highAlertOnly = ConfigYesNo(default=False)41config.plugins.Warnung.level = ConfigSelection(default="1", choices=[42 ('0', _('Alle Warnstufen')), ('1', _('Ab Warnstufe "Moderat"')), ('2', _('Ab Warnstufe "Hoch"')),43 ('3', _('Ab Warnstufe "Hoch" (Vollanzeige bei "Extrem")')), ('4', _('Nur Extremstufe'))])44config.plugins.Warnung.standbyMode = ConfigSelection(default="1", choices=[('0', _('Normalbetrieb')),45 ('1', _('Hintergrundpr_uefung aussetzen')),46 ('2', _('Bei Warnung Standby beenden')),47 ('3', _('Bei Warnung Standby beenden (06:00-00:00)')),48 ('4', _('Bei Warnung Standby beenden (08:00-22:00)')),49 ('5', _('Bei Extremwarnung Standby beenden')),50 ('6', _('Bei Extremwarnung Standby beenden (06:00-00:00)')),51 ('7', _('Bei Extremwarnung Standby beenden (08:00-22:00)'))])52config.plugins.Warnung.invertedOrder = ConfigYesNo(default=True)53#config.plugins.Warnung.noDouble = ConfigYesNo(default = False)54config.plugins.Warnung.noDouble = ConfigSelection(default="false", choices=[('false', _('Nein')),55 ('30', _('f_uer 30 Minuten')),56 ('60', _('f_uer 1 Stunde')),57 ('120', _('f_uer 2 Stunden')),58 ('180', _('f_uer 3 Stunden')),59 ('240', _('f_uer 4 Stunden')),60 ('300', _('f_uer 5 Stunden')),61 ('360', _('f_uer 6 Stunden')),62 ('true', _('Dauerhaft'))])63config.plugins.Warnung.lastAlert = ConfigText(default='')64config.plugins.Warnung.ignoreDoubleList = ConfigText(default='')65config.plugins.Warnung.ignoreList = ConfigText(default='')66config.plugins.Warnung.ignoreAllList = ConfigText(default='')67config.plugins.Warnung.whiteList = ConfigText(default=_('Unfall;Flut;Explosion;schwemmung;hang;rutsch'))68config.plugins.Warnung.debug = ConfigYesNo(default=False)69##############################################################################70def debugMode(reset=False):71 global _isDebugMode # buffer72 if reset or (_isDebugMode == None):73 _isDebugMode = config.plugins.Warnung.debug.value74 return _isDebugMode75def warnReset(val=''):76 try:77 config.plugins.Warnung.lastAlert.value = val78 config.plugins.Warnung.lastAlert.save()79 except:80 pass81def configValue(id, default="0"):82 try:83 res = getattr(config.plugins.Warnung, id).value84 if res == None:85 return default86 else:87 return res88 except:89 return default90def wakeUpOk():91 from data import extremeLevelFound92 type = int(config.plugins.Warnung.standbyMode.value)93 if (type >= 5) and not extremeLevelFound:94 return 095 if (type >= 5):96 type -= 397 hour = datetime.now().hour98 return (type == 2) or ((type == 3) and (hour >= 6)) or ((type == 4) and (hour >= 8) and (hour < 22))99def sleepDuringStandby(): #im Standby schlafen100 return int(config.plugins.Warnung.standbyMode.value) == 1101################################# SCREEN ###################################102class WarnCfg (Screen, ConfigListScreen):103 skin = """<screen position="center,center" size="*scrSize*" backgroundColor="#11111111" flags="wfNoBorder" title=" ">104 <eLabel position="*linePos1*" backgroundColor="#112233" size="*bottomBkSize*" />105 <eLabel position="0,0" size="*titleSize*" backgroundColor="#112233" zPosition="10"/>106 <eLabel position="*versionPos1*" font="Regular;*fs4*" valign="top" halign="left" foregroundColor="#999999"107 size="*titleSize*" text="*version1*" transparent="1" zPosition="10"/>108 <eLabel position="*versionPos2*" font="Regular;*fs4*" valign="top" halign="left" foregroundColor="#999999"109 size="*titleSize*" text="*version2*" transparent="1" zPosition="10"/>110 <eLabel position="*titlePos*" font="Regular;*fs*" valign="top" halign="center"111 size="*titleSize*" text="*title*" transparent="1" zPosition="10"/>112 <eLabel position="*linePos0*" backgroundColor="#606060" size="*lineSize*" zPosition="10"/>113 <widget name="config" itemHeight="*ih*" font="Regular;*fs*" position="*listPos*" size="*listSize*"114 backgroundColor="#11111111" scrollbarSliderForegroundColor="#bbaab4" scrollbarMode="showOnDemand"115 scrollbarSliderBorderColor="#00333333" scrollbarSliderBorderWidth="1" scrollbarWidth="*sb*" />116 <widget name="info" position="*labelPos*" valign="center" size="*labelSize*" font="Light;*fs2*"117 transparent="1" zPosition="9"/>118 <eLabel position="*linePos1*" backgroundColor="#606060" size="*lineSize*" zPosition="10"/>119 <eLabel position="*linePos2*" backgroundColor="#606060" size="*lineSize*" zPosition="10"/>120 *buttons*121 <widget name="saveMsg" backgroundColor="#006600" position="center,center" font="Regular;*fs*"122 size="*msgSize*" valign="center" halign="center" zPosition="99"/>123 </screen>"""124 def __init__(self, session, args=0):125 self.session = session126 Screen.__init__(self, session)127 self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "MenuActions", "EPGSelectActions"],128 {"cancel": self.abort, "red": self.abort, "green": self.save, "yellow": self.initSearch, "blue": self.blue}, -1)129 self["key_red"] = StaticText(_("Abbruch"))130 self["key_green"] = StaticText(_("Sichern"))131 self["key_yellow"] = StaticText(_("Regionalschl_uessel setzen"))132 self["key_blue"] = StaticText(_("Testalarm"))133 #self["key_menu"] = StaticText(_("Menu: Quellen"))134 self["saveMsg"] = Label(_("Gespeichert"))135 self["info"] = Label('')136 self.list = []137 self.infos = []138 self.createSetupList()139 self.initSkin()140 ConfigListScreen.__init__(self, self.list, session=self.session)141 self.onLayoutFinish.append(self.initMenu)142 self.cfgTimer = eTimer()143 self.cfgTimer.callback.append(self.onCfgTimerRun)144 self.initTimer = eTimer()145 self.initTimer.callback.append(self.onInitTimerRun)146 self["config"].onSelectionChanged.append(self.info)147 self.onCfgTimerRun()148 self.initTimer.start(200, True)149 globals()["_isDebugMode"] = None150 def endMsg(self, answer=0): pass151 def message(self, s, d=-1):152 if s != '':153 self.msgBox = self.session.openWithCallback(self.endMsg, MessageBox, s, MessageBox.TYPE_INFO, d)154 self.msgBox.setTitle(" ")155 def question(self, callback, s):156 self.msgBox = self.session.openWithCallback(endMessage, MessageBox, s, MessageBox.TYPE_YESNO)157 self.msgBox.setTitle(" ")158 def channelChoiceFinish(self, answer):159 import data160 if (answer != None):161 if (self["config"].getCurrentIndex() == 3):162 data.ARS2 = answer[1]163 config.plugins.Warnung.ARS2.value = answer[1].replace(', ', ', ')164 else:165 data.ARS = answer[1]166 config.plugins.Warnung.ARS.value = answer[1].replace(', ', ', ')167 def onInitTimerRun(self):168 self.initTimer.stop()169 if not config.plugins.Warnung.ARS.value:170 self.initSearch()171 def getChoice(self, choices=[]):172 from Screens.ChoiceBox import ChoiceBox173 if len(choices) == 0:174 message('Keine Eintr_aege gefunden')175 else:176 self.session.openWithCallback(self.channelChoiceFinish, ChoiceBox, title=_("Regionalschl_uessel"), list=choices)177 def holeSchluessel(self, spec='mar'):178 res = []179 F = PATH + 'Regionalschluessel.json'180 if not path.exists(F):181 return res182 try:183 with open(F) as json_file:184 data = json.load(json_file)185 for p in data['daten']:186 if str(p[1]).lower().startswith(spec.lower()):187 lst = (str(p[1]), str(p[0]) + ' (' + str(p[1]) + ')')188 res.append(lst)189 self.getChoice(sorted(res))190 except:191 pass192 return res193 def initSearch(self):194 from Screens.VirtualKeyBoard import VirtualKeyBoard195 idx = self["config"].getCurrentIndex()196 if (idx != 2) and (idx != 3):197 self.message(_('Bitte die Zeile f_uer den gew_uenschten Regionalschl_uessel selektieren (Zeilen3/4)'), 10)198 else:199 self.session.openWithCallback(self.searchReturn, VirtualKeyBoard, title='Erste Buchstaben des Gemeindenamens eingeben (mind. 3)', text='')200 def searchReturn(self, search):201 if search and search != '':202 self.holeSchluessel(search)203 def initSkin(self):204 _scale = scale205 if configValue('scale') == '1':206 _scale = _scale * 0.8207 def sizeStr(i1, i2): return str(i1) + ',' + str(i2)208 def lineStr(x, y, w, h):209 return '<eLabel backgroundColor="#444444" zPosition="99" position="' + sizeStr(x, y) + '" size="' + sizeStr(w, h) + '" />'210 iH = int(32 * _scale)211 labelH = int(70 * _scale)212 titleH = int(48 * _scale)213 buttonH = int(30 * _scale)214 fS = int(24 * _scale)215 fS2 = int(21 * _scale)216 lineH = int(round(_scale))217 listW = int(940 * _scale)218 dif = int(_scale * 10)219 scrW = listW + 2 * dif220 fS3 = int(20 * _scale)221 fS4 = int(17 * _scale)222 listH = min(16, len(self.list)) * iH223 scrH = listH + 4 * dif + labelH + buttonH + titleH224 self.skin = self.skin.replace('*title*', _('Einstellungen'))225 self.skin = self.skin.replace('*version1*', 'Version: ' + VERSIONSTR).replace('*version2*', 'Stand: ' + VERSIONDATE)226 self.skin = self.skin.replace('*titleSize*', sizeStr(scrW, titleH))227 self.skin = self.skin.replace('*titlePos*', sizeStr(0, int(8 * _scale)))228 self.skin = self.skin.replace('*versionPos1*', sizeStr(12, int(3 * _scale)))229 self.skin = self.skin.replace('*versionPos2*', sizeStr(12, int(23 * _scale)))230 self.skin = self.skin.replace('*scrSize*', sizeStr(scrW, scrH))231 self.skin = self.skin.replace('*listSize*', sizeStr(listW, listH))232 self.skin = self.skin.replace('*listPos*', sizeStr(dif, dif + titleH))233 self.skin = self.skin.replace('*linePos0*', sizeStr(1, titleH))234 self.skin = self.skin.replace('*linePos1*', sizeStr(1, listH + titleH + dif * 2))235 self.skin = self.skin.replace('*linePos2*', sizeStr(1, listH + titleH + dif * 2 + labelH))236 self.skin = self.skin.replace('*lineSize*', sizeStr(scrW, lineH))237 self.skin = self.skin.replace('*labelPos*', sizeStr(dif * 2, listH + titleH + dif * 2))238 self.skin = self.skin.replace('*labelSize*', sizeStr(listW, labelH))239 self.skin = self.skin.replace('*bottomBkSize*', sizeStr(scrW, labelH))240 self.skin = self.skin.replace('*msgSize*', sizeStr(int(220 * _scale), int(56 * _scale))).replace('*fs4*', str(fS4))241 self.skin = self.skin.replace('*fs*', str(fS)).replace('*fs2*', str(fS2)).replace('*ih*', str(iH)).replace('*sb*', str(int(_scale * 7)))242 #buttons/label243 cPos = pos = 0244 s = ''245 step = int(scrW / 4) + 1246 but = '<widget source="key_%1" render="Label" position="%2,' + str(scrH - buttonH - dif)247 but += '" zPosition="1" size="' + sizeStr(step, buttonH) + '" '248 but += ' font="Regular;' + str(fS3) + '" foregroundColor="foreground" halign="center" valign="top" transparent="1" />'249 lab = '<eLabel backgroundColor="#%3" position="%4,' + str(scrH - dif) + '" size="' + sizeStr(step, dif) + '" zPosition="2"/>'250 for k in ["red", "green", "yellow", "blue"]:251 s += but.replace("%1", k).replace("%2", str(pos))252 pos += step253 for c in ["b81c46", "009f3c", "9ca81b", "2673ec"]:254 s += lab.replace("%3", c).replace("%4", str(cPos))255 cPos += step256 s += lineStr(0, 0, scrW, 1)257 s += lineStr(0, scrH - 1, scrW, 1)258 s += lineStr(0, 0, 1, scrH)259 s += lineStr(scrW - 1, 0, 1, scrH)260 self.skin = self.skin.replace("*buttons*", s)261 def onCfgTimerRun(self):262 try:263 self.cfgTimer.stop()264 self["saveMsg"].hide()265 except:266 pass267 def cfgOut(self, cfg):268 for (text, id, notify) in cfg:269 if text.startswith('- -'):270 self.separatorPos.append(len(self.list))271 self.list.append(getConfigListEntry(text, NoSave(ConfigNothing())))272 else:273 x = getattr(config.plugins.Kiosk, id)274 self.list.append(getConfigListEntry(_(text), x))275 if notify:276 x.addNotifier(self.refresh, initial_call=False)277 def separator(self, s, add=''): return '- - - - - - - ' + _(s) + add + ' - - - - - - -'278 def info(self):279 try:280 self["info"].setText(self.infos[self["config"].getCurrentIndex()])281 except:282 pass283 def createSetupList(self, reset=False):284 def _info(s): self.infos.append(_(s.replace('$', 'Begriffe mit ";" trennen, Gro_ss-/Kleinschreibung muss nicht beachtet werden')))285 self.list = []286 self.infos = []287 self.list.append(getConfigListEntry(_('Warnfenster (Einblendung)'), config.plugins.Warnung.format))288 _info('_Aenderung der Anzeige wird erst beim n_aechsten Fensteraufruf wirksam.')289 self.list.append(getConfigListEntry(_('Anzeigegr_oe_sse'), config.plugins.Warnung.scale))290 _info('_Aenderung der Anzeige wird erst beim n_aechsten Fensteraufruf wirksam.')291 self.list.append(getConfigListEntry(_('Regionalschl_uessel, Ort (Gelbe Taste)'), config.plugins.Warnung.ARS))292 _info('Amtlicher Regionalschl_uessel zum Zugriff auf die NINA-Schnittstelle. Die Abfrage erfolgt KREISGENAU _ueber die ersten 5 Stellen des Schl_uessels. WICHTIG: Den Gemeindenamen hinter der Nummer eintragen.')293 self.list.append(getConfigListEntry(_('Regionalschl_uessel, Sekund_aerort (Gelbe T.)'), config.plugins.Warnung.ARS2))294 _info('OPTIONAL - Der Sekund_aerort muss in einem anderen Kreis liegen, da sonst Doppelmeldungen erzeugt werden. Weitere Schl_uessel k_oennen ggfl. manuell in der Datei ars.txt eingetragen werden.')295 self.list.append(getConfigListEntry(_('Abfrageintervall (Minuten, 0=keine Hintergrundpr_uefung)'), config.plugins.Warnung.interval))296 _info('Zeitabstand f_uer Hintergrundabfragen')297 self.list.append(getConfigListEntry(_('Abfrageintervall nach Warnungen (Minuten)'), config.plugins.Warnung.afterAlarm))298 _info('Reduzierter Zeitabstand f_uer Hintergrundabfragen, nachdem eine neue Warnung eingegangen ist..')299 self.list.append(getConfigListEntry(_('Warnstufe f_uer Einblendungen'), config.plugins.Warnung.level))300 _info('Legt das Verhalten fest, das f_uer automatische Einblendungen gilt.')301 self.list.append(getConfigListEntry(_('Warnanzeige (Sekunden)'), config.plugins.Warnung.duration))302 _info('Dauer der Warnungseinblendung in Sekunden.\nEine Warnungseinblendung kann mit mit Ok/Exit geschlossen werden.')303 self.list.append(getConfigListEntry(_('Verhalten im Standby'), config.plugins.Warnung.standbyMode))304 _info('Wichtig: Diese Einstellungen gelten mir f_uer das einfache Standby. Im Deep-Standby sind keine Abfragen m_oeglich.')305 self.list.append(getConfigListEntry(_('Warnungswiederholungen vermeiden'), config.plugins.Warnung.noDouble))306 _info('Gilt nur f_uer automatische Warnungen, wenn deren Text identisch geblieben ist')307 self.list.append(getConfigListEntry(_('Eingrenzungsbegriffe f_uer Wiederholungsvermeidung'),308 config.plugins.Warnung.ignoreDoubleList))309 _info('Doppelmeldung nur vermeiden, wenn sie einen der eingetragenen Begriffe enthalten ($). Leer: Immer Doppelvermeidung ')310 self.list.append(getConfigListEntry(_('Alter f_uer zu ignorierende Meldungen (Tage, 0=nicht ign.)'),311 config.plugins.Warnung.ignoreInterval))312 _info('Gilt f_uer alle Warnungsanzeigen')313 self.list.append(getConfigListEntry(_('Neue Meldungen zuerst'), config.plugins.Warnung.invertedOrder))314 _info('Reihenfolge der Meldungen (bezogen auf den Ort')315 self.list.append(getConfigListEntry(_('Alarm-Ignorierliste'), config.plugins.Warnung.ignoreList))316 _info('Neue Warnungen nicht automatisch einblenden, wenn sie einen der eingetragenen Begriffe enthalten ($)')317 self.list.append(getConfigListEntry(_('Sperrliste (f_uer alle Meldungen)'), config.plugins.Warnung.ignoreAllList))318 _info('Meldungen in allen Anzeigen ignorieren, wenn sie einen der eingetragenen Begriffe enthalten ($)')319 self.list.append(getConfigListEntry(_('Wichtige Alarmbegriffe'), config.plugins.Warnung.whiteList))320 _info('Neue Warnungen immer automatisch einblenden, wenn sie einen der eingetragenen Begriffe enthalten ($)')321 self.list.append(getConfigListEntry(_('Debugmodus'), config.plugins.Warnung.debug))322 _info('Erzeugt eine Debugdatei (debug.txt) mit Daten der letzten Hintergrundabfrage. Die Datei emulate.json kann f_uer Testalarme genutzt werden.')323 def initMenu(self): self["config"].instance.setWrapAround(True)324 def yellow(self): pass325 def blue(self):326 import plugin327 plugin.pNina.loop = -1328 plugin.forceAlarm = True329 self.session.open(MessageBox, _("Automatische Warnung 5 Sekunden nach dem Schlie_ssen des Meldungsfensters"),330 MessageBox.TYPE_INFO)331 def onChanged(self): pass332 def refresh(self, *args, **kwargs): self.onChanged()333 def startMenuMode(self):334 self["config"].instance.setWrapAround(True)335 for x in self["config"].list:336 x[1].cancel()337 def save(self):338 try:339 self["saveMsg"].show()340 self.cfgTimer.start(1300, True)341 except:342 pass343 self.saveAll()344 try:345 for x in self["config"].list:346 x[1].cancel()347 except:348 pass349 try:350 self.createSetupList()351 self["config"].list = self.list352 except:353 self.close()...
GigamonAPI.py
Source:GigamonAPI.py
1'''2Class GigamonAPI3Author: Kyle Smith4Company: Aplura, LLC5API Credit: Gigamon, Inc.6Copyright 20157'''8import logging, json, requests, os, time9import logging as logger10class Error(Exception):11 pass12class ConfigurationError(Exception):13 def __init__(self, expr, msg):14 self.expr = expr15 self.msg = json.dumps(msg)16 def __str__(self):17 return repr(self.msg)18class HTTPError(Exception):19 def __init__(self, *args, **kwargs):20 response = kwargs.pop('response',None)21 self.response = response22 self.request = kwargs.pop('request',None)23 if (response is not None and not self.request and hasattr(response,'request')):24 self.request = self.response.request25 super(Exception,self).__init__(*args,**kwargs)26class GigamonAPIBase:27 """ Base Class for Gigamon FM API : Should not be instantiated directly """28 _session = None29 _hostname = None30 _log = logger31 _isDebugMode = False32 _useJson = False33 _lastUrl = None34 35 def __init__(self, **kwargs):36 """Construct an instance of the GigamonAPIBase"""37 self._log.debug("starting __init__ base")38 try:39 username = kwargs["username"]40 password = kwargs["password"]41 hostname = kwargs["hostname"]42 except KeyError as ne:43 self._log.warn("action=failure msg=\"required argument not passed\" argument=\"%s\" "%ne)44 raise ValueError("Required argument not passed: %s"%ne)45 self._session = requests.session()46 self._session.auth = (username, password)47 self._hostname = hostname48 try:49 self._useJson = kwargs["useJson"]50 except:51 pass52 def _toggleDebug(self):53 if(self._isDebugMode):54 self._isDebugMode = False55 else: 56 self._isDebugMode = True57 def _formatReturn(self, obj):58 if (self._useJson ):59 return json.loads(obj)60 else:61 return obj62 def _read(self, url):63 self._log.debug("starting %s read from url:%s"%(self._version, url))64 self._lastUrl = url65 #return "I would have returned. But I was delayed."66 r = self._session.get(url, verify=False)67 if r.status_code == 200:68 return self._formatReturn(r.content)69 else:70 self._log.error(" action=read api_version=%s status=%s content=\"%s\" "%(self._version, r.status_code, r.content) )71 self._raise_for_status(r)72 def _raise_for_status(self,r):73 """Raises stored :class:`HTTPError`, if one occurred."""74 myJson = {}75 try:76 myJson = json.loads(r.content)77 except:78 pass79 additional_info = ""80 if "errors" in myJson:81 additional_info = myJson["errors"][0]["msg"]82 http_error_msg = ''83 if 400 <= r.status_code < 500:84 http_error_msg = '%s Client Error: reason="%s" url="%s" additional_info="%s"' % (r.status_code, r.reason, r.url, additional_info)85 elif 500 <= r.status_code < 600:86 http_error_msg = '%s Server Error: reason="%s" url="%s" additional_info="%s"' % (r.status_code, r.reason, r.url, additional_info)87 if http_error_msg:88 raise HTTPError(http_error_msg, response=r)89 def _gen_date_time(self):90 """ Generate a timestamp """91 st = time.localtime()92 tm = time.mktime(st)93 return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(tm))94 95 def _validateIP(self, ipAddr):96 """ Test and Validate an IP """97 from IPy import IP98 IP(ipAddr)99 100 def get_last_url(self):101 return self._lastUrl102 def ConnectionTest(self):103 """Test the Connection to make sure it is up and running"""104 return self._read(self._buildUrl("", ""))105 def get_version(self):106 return self._version107################################################108###### Add additional version classes here #####109################################################110global _API111from GigamonAPIv1 import GigamonAPIv1112from GigamonAPIv1_1 import GigamonAPIv1_1113from GigamonAPIv1_2 import GigamonAPIv1_2114from GigamonAPIv1_3 import GigamonAPIv1_3115################################################116### To add a new Version, first import it #117### above, and then add the version number and #118### classname to _API below. #119################################################120_API = {121 "v1" : GigamonAPIv1,122 "v1.1" : GigamonAPIv1_1,123 "v1.2" : GigamonAPIv1_2,124 "v1.3" : GigamonAPIv1_3125 }126######127## Begin Function call to build required class128######129def GigamonAPI(api_version="v1",**kwargs):130 '''131 Interface with the Gigamon FM API132 '''133 global _API134 _valid_apis = [] # Which versions will we accept?135 _version = None136 [ _valid_apis.append(x) for x in _API ]137 if (api_version not in _valid_apis):138 _log.warn("action=failure msg=\"invalid api specified\" api_version=\"%s\" "%api_version)139 raise ConfigurationError("api_version","Invalid API Version Specified: %s"%api_version)...
ScreenUpdatePlugin.py
Source:ScreenUpdatePlugin.py
1class ScreenUpdatePlugin:2 def __init__(self, callback, isDebugMode):3 self._callback = callback4 self._isDebugMode = isDebugMode5 def GetIntervalSeconds(self):6 return 5 if self._isDebugMode else 607 def Execute(self):...
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!!