def getCameraSettings(self): """ Returns the login details of the camera """ #utils.log(4, 'SETTINGS :: Use Cache: %s; Camera %s; Camera Type: %s' %(useCache, self.camera_number, self.camera_type)) ''' Foscam Camera ''' if self.camera_type != GENERIC_IPCAM: host = settings.getSetting('host', self.camera_number) if not host: utils.log(3, 'Camera %s :: No host specified.' %self.camera_number) host = '' port = settings.getSetting('port', self.camera_number) if not port: utils.log(3, 'Camera %s :: No port specified.' %self.camera_number) port = '' username = settings.getSetting('user', self.camera_number) invalid = settings.invalid_user_char(username) if invalid: utils.log(3, 'Camera %s :: Invalid character in user name: %s' %(self.camera_number, invalid)) username = '' password = settings.getSetting('pass', self.camera_number) invalid = settings.invalid_password_char(password) if invalid: utils.log(3, 'SETTINGS :: Camera %s - Invalid character in password: %s' %(self.camera_number, invalid)) password = '' return [self.camera_number, host, port, username, password] else: ''' Generic IP Camera ''' return [self.camera_number, '', '', '', '']
def __init__(self, memorycontent, assertionTriggers, addr2line, pcInitValue=0): # Parameters self.pcoffset = 8 if getSetting("PCbehavior") == "+8" else 0 self.PCSpecialBehavior = getSetting("PCspecialbehavior") self.allowSwitchModeInUserMode = getSetting("allowuserswitchmode") self.maxit = getSetting("runmaxit") self.bkptLastFetch = None self.deactivatedBkpts = [] # Initialize history self.history = History() # Initialize components self.mem = Memory(self.history, memorycontent) self.regs = Registers(self.history) self.pcInitVal = pcInitValue # Initialize decoders self.decoders = { 'BranchOp': BranchOp(), 'DataOp': DataOp(), 'MemOp': MemOp(), 'MultipleMemOp': MultipleMemOp(), 'HalfSignedMemOp': HalfSignedMemOp(), 'SwapOp': SwapOp(), 'PSROp': PSROp(), 'MulOp': MulOp(), 'MulLongOp': MulLongOp(), 'SoftInterruptOp': SoftInterruptOp(), 'NopOp': NopOp() } self.decoderCache = {} # Initialize assertion structures self.assertionCkpts = set(assertionTriggers.keys()) self.assertionData = assertionTriggers self.assertionWhenReturn = set() self.callStack = [] self.addr2line = addr2line # Initialize execution errors buffer self.errorsPending = MultipleErrors() # Initialize interrupt structures self.interruptActive = False # Interrupt trigged at each a*(t-t0) + b cycles self.interruptParams = {'b': 0, 'a': 0, 't0': 0, 'type': "FIQ"} self.lastInterruptCycle = -1 self.stepMode = None self.stepCondition = 0 # Used to stop the simulator after n iterations in run mode self.runIteration = 0 self.history.clear()
def mjpeg_url(self): _mjpegUrl = settings.getSetting("mjpeg_url", self.camera_number) if mjpegUrl == "": _mjpegUrl = "http://{0}/cgi-bin/CGIStream.cgi?cmd={GetMJStream}&usr={1}&pwd={2}&".format( self.url, self.usr, self.pwd ) return _mjpegUrl
def snapshot_url(self): _snapshotUrl = settings.getSetting("snapshot_url", self.camera_number) if _snapshotUrl == "": _snapshotUrl = "http://{0}/cgi-bin/CGIProxy.fcgi?cmd={snapPicture2}&usr={1}&pwd={2}&".format( self.url, self.usr, self.pwd ) return _snapshotUrl
def ptz_get_sensitivity(self): if self.camera_type == FOSCAM_HD or self.camera_type == FOSCAM_HD_OVERRIDE: return settings.getSetting_float( 'ptz_hd_sensitivity%s' % self.camera_number) / 10 elif self.camera_type == FOSCAM_SD: return self.camera.ptz_set_sensitivity( settings.getSetting('ptz_sd_sensitivity%s' % self.camera_number))
def getCurrentInstructionAddress(self): """ Return the address of the instruction being executed """ self.sim.regs.deactivateBreakpoints() pc = self.sim.regs[15] self.sim.regs.reactivateBreakpoints() pc -= 8 if getSetting("PCbehavior") == "+8" else 0 return pc
def __init__(self, camera, monitor): self.camera = camera self.monitor = monitor self.cond_service = settings.getSetting_int('cond_service', self.camera.number) self.cond_manual = settings.getSetting_int('cond_manual', self.camera.number) self.dur_service = settings.getSetting_int('dur_service', self.camera.number) self.dur_manual = settings.getSetting_int('dur_manual', self.camera.number) self.prefix = 'Preview' self.buttons = [] # Positioning of the window WIDTH = 320 HEIGHT = 180 scaling = settings.getSetting_float('scaling', self.camera.number) width = int(float(WIDTH * scaling)) height = int(float(HEIGHT * scaling)) button_scaling = 0.5 * scaling button_width = int(round(Button.WIDTH * button_scaling)) position = settings.getSetting('position', self.camera.number).lower() if 'bottom' in position: y = 720 - height else: y = 0 if 'left' in position: x = 0 start = - width else: x = 1280 - width start = width animations = [('WindowOpen', ("effect=slide start={0:d} time=1300 tween=cubic easing=out").format(start)), ('WindowClose', ("effect=slide end={0:d} time=900 tween=back easing=inout").format(start))] self.black = xbmcgui.ControlImage(x, y, width, height, _black) self.addControl(self.black) self.black.setAnimations(animations) self.img1 = xbmcgui.ControlImage(x, y, width, height, '') self.img2 = xbmcgui.ControlImage(x, y, width, height, '') self.addControl(self.img1) self.addControl(self.img2) self.img1.setAnimations(animations) self.img2.setAnimations(animations) self.close_button = Button(self, 'close', x + width - button_width - 10, y + 10, scaling=button_scaling) self.addControl(self.close_button) self.close_button.setAnimations(animations) self.setProperty('zorder', "99") self.playFullscreen = False self.stop() #Initializes state and makes ready to be used
def open(self, wantToOpen): #opens apps (from settings) self.paths = settings.getSetting('apps') for self.path in self.paths: self.app = Application(self.path) if wantToOpen: self.app.open() else: self.app.close()
def getCurrentLine(self): self.regs.deactivateBreakpoints() pc = self.regs[15] self.regs.reactivateBreakpoints() pc -= 8 if getSetting("PCbehavior") == "+8" else 0 if pc in self.addr2line and len(self.addr2line[pc]) > 0: return self.addr2line[pc][-1] else: return None
def getmode(self): '''returns 🔆 if in free mode or 💼 if in workmode''' self.mode = settings.getSetting('mode') if self.mode == "work": self.work.state = 1 return "💼" else: self.work.state = 0 return "🔆"
def p_declarationsize(p): """declarationsize : VARDEC LISTINIT""" if p[1] not in (8, 16, 32): raise YaccError("Une variable peut avoir les tailles suivantes (en bits) : 8, 16 ou 32. {} n'est pas une taille valide".format(p[1])) if len(p[2]) > 1: raise YaccError("Une allocation de variable ne peut qu'être suivie d'un nombre d'éléments. Utilisez ASSIGN si vous voulez assigner des valeurs précises.") dimNbr = p[2][0] dimBytes = dimNbr * p[1] // 8 if dimBytes > 8192: raise YaccError("Demande d'allocation mémoire trop grande. Le maximum permis est de 8 Ko (8192 octets), mais la déclaration demande {} octets.".format(dimBytes)) assert dimBytes <= 8192, "Too large memory allocation requested! ({} bytes)".format(dimBytes) p[0] = (struct.pack("<" + "B" * dimBytes, *[getSetting("fillValue")] * dimBytes), None)
def start_program(self): '''calls everything related to the work mode''' self.thread = Thread() self.thread.switchMode(self.config['workDock'], self.config['workBG']) self.thread.open(True) self.thread.web() self.title = "💼" settings.updtSettings('mode', "work") if settings.getSetting('notification') == "True": rumps.notification(title=self.name, subtitle="You are now in work mode", message="")
def end_program(self): '''calls everything related to the normal mode''' self.thread = Thread() self.thread.switchMode(self.config['normalDock'], self.config['normalBG']) self.thread.open(False) self.title = "🔆" settings.updtSettings('mode', "free") if settings.getSetting('notification') == "True": rumps.notification(title=self.name, subtitle="You are now in normal mode", message="")
def switchMode(self, d, bg): #changes background, dock and DND self.DnD = DND() self.mode = settings.getSetting('mode') if self.mode == "free": self.DnD.turnOn() d = settings.getSetting('workDock') bg = settings.getSetting('workBG') elif self.mode == "work": self.DnD.turnOff() d = settings.getSetting('normalDock') bg = settings.getSetting('normalBG') else: pass self.backg = Background() self.backg.change(bg) self.dock = customDock() self.dock.removeAll() self.dock.addMultiple(reversed(d)) self.dock.save()
def getCameraSettings(self): """ Returns the login details of the camera """ #utils.log(4, 'SETTINGS :: Use Cache: %s; Camera %s; Camera Type: %s' %(useCache, self.camera_number, self.camera_type)) ''' Foscam Camera ''' if self.camera_type != GENERIC_IPCAM: host = settings.getSetting('host', self.camera_number) if not host: utils.log( 3, 'Camera %s :: No host specified.' % self.camera_number) host = '' port = settings.getSetting('port', self.camera_number) if not port: utils.log( 3, 'Camera %s :: No port specified.' % self.camera_number) port = '' username = settings.getSetting('user', self.camera_number) invalid = settings.invalid_user_char(username) if invalid: utils.log( 3, 'Camera %s :: Invalid character in user name: %s' % (self.camera_number, invalid)) username = '' password = settings.getSetting('pass', self.camera_number) invalid = settings.invalid_password_char(password) if invalid: utils.log( 3, 'SETTINGS :: Camera %s - Invalid character in password: %s' % (self.camera_number, invalid)) password = '' return [self.camera_number, host, port, username, password] else: ''' Generic IP Camera ''' return [self.camera_number, '', '', '', '']
def setMemory(self, addr, val): # if addr is not initialized, then do nothing # val is a bytearray of one element (1 byte) if self.sim.mem._getRelativeAddr(addr, 1) is None: return try: val = int(val, base=16) except ValueError: # Invalid value return self.sim.mem.set(addr, val[0], 1) pc = self.sim.regs[15].get(mayTriggerBkpt=False) pc -= 8 if getSetting("PCbehavior") == "+8" else 0 if 0 <= addr - pc < 4: # We decode the instruction again self.sim.fetchAndDecode()
def p_declarationsize(p): """declarationsize : VARDEC CONST""" if p[1] not in (8, 16, 32): raise YaccError( "Une variable peut avoir les tailles suivantes (en bits) : 8, 16 ou 32. {} n'est pas une taille valide" .format(p[1])) dimBytes = p[2] * p[1] // 8 if dimBytes > 8192: raise YaccError( "Demande d'allocation mémoire trop grande. Le maximum permis est de 8 Ko (8192 octets), mais la déclaration demande {} octets." .format(dimBytes)) assert dimBytes <= 8192, "Too large memory allocation requested! ({} bytes)".format( dimBytes) p[0] = (struct.pack("<" + "B" * dimBytes, *[getSetting("fillValue")] * dimBytes), None)
requests_counter = 0 clicked = False global response print("─╔╦═╦╦═╦╗╔══╦═╦══╦═╦╦╗") print("─║║╦╣║║║║╚╗╔╣╬╠║║╣╔╣╔╝") print("╔╣║╩╣║║║║─║║║╗╬║║╣╚╣╚╗") print("╚═╩═╩═╩═╝─╚╝╚╩╩══╩═╩╩╝") print("jew trick (client) v2.1\nhttps://jewtrick.ml") print("") motd = requests.get("https://jewtrick.ml/server/motdv21.html") if motd.status_code == 200: print(motd.text + "\n") for word in settings.settings_list: settings.getSetting(word) if(settings.getSetting("settings") == False): print("Вы можете настроить jew trick в файле settings.txt\n") if(settings.getSetting("autoclick") and settings.getSetting("settings")): response = "да" print("AutoClick установлен на " + response + "\n") elif(settings.getSetting("settings") and settings.getSetting("autoclick") == False): response = "нет" print("AutoClick установлен на " + response + "\n") else: print("Включить AutoClick?") print("Эта функция сделает двойной клик мышкой, когда придёт время заходить на 2b2t.\nВы можете просто навести курсор мыши на 2b2t в списке серверов и ждать.\nНапишите 'да' или 'нет'") while True: response = input() if response != "да" and response != "нет": print("Напишите 'да' или 'нет'")
def snapshot_url(self): _snapshotUrl = settings.getSetting('snapshot_url', self.camera_number) if _snapshotUrl == '': _snapshotUrl = "http://{0}/cgi-bin/CGIProxy.fcgi?cmd=snapPicture2&usr={1}&pwd={2}&".format( self.url, self.usr, self.pwd) return _snapshotUrl
def mjpeg_url(self): _mjpegUrl = settings.getSetting('mjpeg_url', self.camera_number) if mjpegUrl == '': _mjpegUrl = "http://{0}/cgi-bin/CGIStream.cgi?cmd=GetMJStream&usr={1}&pwd={2}&".format( self.url, self.usr, self.pwd) return _mjpegUrl
def video_url(self): _videoUrl = settings.getSetting('stream_url', self.camera_number) if _videoUrl == '': _videoUrl = "rtsp://{0}:{1}@{2}:{3}/videoMain".format( self.usr, self.pwd, self.host, self.rtsp) return _videoUrl
def parse(code): """ Parse and compile ARM assembly code. :param code: :return: A tuple containing : 1) a bytes object (the generated bytecode) 2) a list object which maps each address in the bytecode to a line in the provided ARM assembly 3) an error object which is an empty list if there is not error, else a 3-tuple: A) a string indicating where we want to write the error, either "error" (top display) or "codeerror" (in the code) B) if "error", description of the error if "codeerror", integer of the line of error C) if "codeerror", description of the error """ listErrors = [] if getSetting("PCbehavior") == "real": raise NotImplementedError("Actual PC behavior not implemented yet") pcoffset = 8 if getSetting("PCbehavior") == "+8" else 0 # First pass : the input code is passed through the lexer and the parser # Each line is parsed independently # The parser always returns a dictionnary assignedAddr = [] addrToLine = defaultdict(list) currentAddr, currentSection = -1, None labelsAddr = {} requiredLabelsPtr = [] maxAddrBySection = { "INTVEC": BASE_ADDR_INTVEC, "CODE": BASE_ADDR_CODE, "DATA": BASE_ADDR_DATA } snippetMode = False # We add a special field in the bytecode info to tell the simulator the start address of each section bytecode = { '__MEMINFOSTART': { "SNIPPET_DUMMY_SECTION": 0 }, '__MEMINFOEND': { "SNIPPET_DUMMY_SECTION": 0 } } unresolvedDepencencies = {} assertions = defaultdict(list) lastLineType = None totalMemAllocated = 0 emptyLines = set() lineToAddr = {} viewedSections = set() for i, line in enumerate(code): line = line.strip() if ';' in line: # Remove the comments line = line[:line.find(';')] if len(line) == 0: # Empty line emptyLines.add(i) continue line += "\n" try: # We ensure that we are in the initial state of the lexer (in case of error in the previous lines) lexer.begin("INITIAL") parsedLine = yaccparser.parser.parse(input=line) except ParserError as e: listErrors.append(("codeerror", i, str(e))) continue except LexError as e: listErrors.append( ("codeerror", i, "Format de l'instruction invalide")) continue except Exception as e: listErrors.append( ("codeerror", i, "Impossible d'interpréter l'instruction")) print(str(e)) continue else: if parsedLine is None or len(parsedLine) == 0: # Unknown error, but the instruction did not parse listErrors.append(("codeerror", i, "Instruction invalide")) continue # We also assign an address to each line assignedAddr.append(max(currentAddr, 0)) addrToLine[max(currentAddr, 0)].append(i) if "SECTION" in parsedLine: if snippetMode: listErrors.append(( "codeerror", i, "Vous ne pouvez pas écrire d'instruction avant le premier mot clé SECTION; si vous souhaitez tester un extrait de code, ne déclarez aucune section." )) continue lastLineType = "SECTION" if "SNIPPET_DUMMY_SECTION" in bytecode['__MEMINFOSTART']: bytecode['__MEMINFOSTART'] = maxAddrBySection.copy() bytecode['__MEMINFOEND'] = maxAddrBySection.copy() if currentSection is not None: maxAddrBySection[currentSection] = currentAddr bytecode['__MEMINFOEND'][currentSection] = currentAddr if parsedLine["SECTION"] == "INTVEC": currentSection = "INTVEC" currentAddr = max(BASE_ADDR_INTVEC, currentAddr) elif parsedLine["SECTION"] == "CODE": currentSection = "CODE" currentAddr = max(BASE_ADDR_CODE, currentAddr) elif parsedLine["SECTION"] == "DATA": currentSection = "DATA" currentAddr = max(BASE_ADDR_DATA, currentAddr) if currentSection in viewedSections: listErrors.append( ("codeerror", i, "La section '{}' est définie deux fois!".format( currentSection))) continue else: viewedSections.add(currentSection) # Ensure word alignement currentAddr += 4 - currentAddr % 4 if currentAddr % 4 != 0 else 0 bytecode[currentSection] = bytearray() if "ASSERTION" in parsedLine: if lastLineType is None or lastLineType in ("LABEL", "SECTION"): assertions[currentAddr].append( ("BEFORE", i, parsedLine["ASSERTION"])) elif lastLineType == "BYTECODE": assertions[currentAddr - 4].append( ("AFTER", i, parsedLine["ASSERTION"])) if ("LABEL" in parsedLine or "BYTECODE" in parsedLine) and currentAddr == -1: # No section defined, but we have a label or an instruction; we switch to snippet mode snippetMode = True currentAddr = 0 currentSection = "SNIPPET_DUMMY_SECTION" bytecode[currentSection] = bytearray() if "LABEL" in parsedLine: if parsedLine["LABEL"] in labelsAddr: # This label was already defined firstaddr = addrToLine[labelsAddr[parsedLine["LABEL"]]][0] listErrors.append(( "codeerror", i, "L'étiquette '{}' est définie deux fois (première définition à la ligne {})" .format(parsedLine["LABEL"], firstaddr + 1))) labelsAddr[parsedLine["LABEL"]] = currentAddr lastLineType = "LABEL" if "BYTECODE" not in parsedLine: lineToAddr[i] = [currentAddr] if "BYTECODE" in parsedLine: # The BYTECODE field contains a tuple # The first element is a bytes object containing the bytecode (so we just add it to the current one) # The second is the eventual missing dependencies (when using a label in a jump or mem operation) bytecode[currentSection].extend(parsedLine["BYTECODE"][0]) # If there are some unresolved dependencies, we note it dep = parsedLine["BYTECODE"][1] if dep is not None: unresolvedDepencencies[(currentSection, currentAddr, i)] = dep if dep[0] == "addrptr": # We will need to add a constant with this label address at the end of the section requiredLabelsPtr.append((dep[1], i)) # We add the size of the object to the current address (so this always points to the address of the next element) tmpAddr = currentAddr for tmpAddr in range( max(currentAddr, 0), max(currentAddr, 0) + len(parsedLine["BYTECODE"][0]), 4): addrToLine[tmpAddr].append(i) lineToAddr[i] = [ currentAddr + li for li in range(len(parsedLine["BYTECODE"][0])) ] currentAddr += len(parsedLine["BYTECODE"][0]) lastLineType = "BYTECODE" totalMemAllocated += len(parsedLine["BYTECODE"][0]) if currentSection == "INTVEC" and currentAddr > BASE_ADDR_CODE: listErrors.append(( "codeerror", i, "La déclaration située sur cette ligne fait déborder la section INTVEC dans la section CODE. Vérifiez que vous allouez le bon nombre d'octets (128 octets maximum pour la section INTVEC en entier)." )) if totalMemAllocated > getSetting("maxtotalmem"): return None, None, None, None, [( "error", "Le code demande une allocation totale de plus de {} octets de mémoire, ce qui est invalide." .format(getSetting("maxtotalmem")))] maxAddrBySection[currentSection] = currentAddr bytecode['__MEMINFOEND'][currentSection] = currentAddr if "SNIPPET_DUMMY_SECTION" not in bytecode: if "INTVEC" not in bytecode: listErrors.append(( "codeerror", 0, "La section INTVEC n'est déclarée nulle part (utilisez 'SECTION INTVEC' au début du code)!" )) return None, None, None, None, listErrors if "CODE" not in bytecode: listErrors.append(( "codeerror", 0, "La section CODE n'est déclarée nulle part (utilisez 'SECTION CODE')!" )) return None, None, None, None, listErrors if "DATA" not in bytecode: listErrors.append(( "codeerror", 0, "La section DATA n'est déclarée nulle part (utilisez 'SECTION DATA' à la fin de votre code)!" )) return None, None, None, None, listErrors # We resolve the pointer dependencies (that is, the instructions using =label) labelsPtrAddr = {} sectionToUse = "CODE" if "CODE" in bytecode[ '__MEMINFOSTART'] else "SNIPPET_DUMMY_SECTION" # At the end of the CODE section, we write all the label adresses referenced currentAddr = bytecode['__MEMINFOEND'][sectionToUse] for labelPtr, lineNo in requiredLabelsPtr: if labelPtr not in labelsAddr: listErrors.append(( "codeerror", lineNo, "Cette ligne demande l'adresse de l'étiquette {}, mais celle-ci n'est déclarée nulle part" .format(labelPtr))) continue if labelPtr in labelsPtrAddr: # Already added (it's just referenced at two different places) continue bytecode[sectionToUse].extend( struct.pack("<I", labelsAddr[labelPtr] & 0xFFFFFFFF)) labelsPtrAddr[labelPtr] = currentAddr currentAddr += 4 bytecode['__MEMINFOEND'][sectionToUse] = currentAddr if len(listErrors) > 0: # At least one line did not assemble, we cannot continue return None, None, None, None, listErrors # At this point, all dependencies should have been resolved (e.g. all the labels should have been seen) # We fix the bytecode of the affected instructions for (sec, addr, line), depInfo in unresolvedDepencencies.items(): # We retrieve the instruction and fit it into a 32 bit integer reladdr = addr - bytecode['__MEMINFOSTART'][sec] instrInt = struct.unpack("<I", bytecode[sec][reladdr:reladdr + 4])[0] if depInfo[0] in ('addr', 'addrptr'): # A LDR/STR on a label or a label's address dictToLookIn = (labelsAddr if depInfo[0] == 'addr' else labelsPtrAddr) try: addrToReach = dictToLookIn[depInfo[1]] except KeyError: # The label was never defined listErrors.append( ("codeerror", line, "L'étiquette {} n'est déclarée nulle part".format( depInfo[1]))) continue diff = addrToReach - (addr + pcoffset) if abs(diff) > 2**12 - 1: # Offset too big to be encoded as immediate listErrors.append(( "codeerror", line, "Accès à l'adresse identifiée par l'étiquette {} trop éloigné ({} octets d'écart) pour pouvoir être encodé" .format(depInfo[1], diff))) continue if diff >= 0: instrInt |= 1 << 23 instrInt |= abs(diff) elif depInfo[0] == 'addrbranch': # A branch on a given label # This is different than the previous case, since the offset is divided by 4 # (when taking the branch, the offset is "shifted left two bits, sign extended to 32 bits" try: addrToReach = labelsAddr[depInfo[1]] except KeyError: # The label was never defined listErrors.append( ("codeerror", line, "L'étiquette {} n'est déclarée nulle part".format( depInfo[1]))) continue diff = addrToReach - (addr + pcoffset) if diff % 4 != 0: listErrors.append(( "codeerror", line, "L'étiquette {} correspond à un décalage de {} octets, qui n'est pas un multiple de 4, ce qui est requis par ARM" .format(depInfo[1], diff))) instrInt |= (diff // 4) & 0xFFFFFF else: assert False # We put back the modified instruction in the bytecode b = struct.pack("<I", instrInt) bytecode[sec][reladdr:reladdr + 4] = b if len(listErrors) > 0: # At least one line did not assemble, we cannot continue return None, None, None, None, listErrors # No errors return bytecode, addrToLine, lineToAddr, assertions, []
def web(self): #Opens the Links (in settings) in Webbrowser self.links = settings.getSetting('Links') for self.link in self.links: webbrowser.open_new(self.link)
def video_url(self): _videoUrl = settings.getSetting('stream_url', self.camera_number) return _videoUrl
def ptz_get_sensitivity(self): if self.camera_type == FOSCAM_HD or self.camera_type == FOSCAM_HD_OVERRIDE: return settings.getSetting_float('ptz_hd_sensitivity%s' %self.camera_number) / 10 elif self.camera_type == FOSCAM_SD: return self.camera.ptz_set_sensitivity(settings.getSetting('ptz_sd_sensitivity%s' %self.camera_number))
import numpy as np import os, requests, time from xml.etree import ElementTree import playsound as ps import settings import requests as req import wikipediaapi as wikiapi import numpy as np import ResponseGen as RG from os.path import join subscription_key = settings.getSetting('speech_key') access_token = '' wiki = wikiapi.Wikipedia('en') def __get_token(): fetch_token_url = "https://northeurope.api.cognitive.microsoft.com/sts/v1.0/issuetoken" headers = {'Ocp-Apim-Subscription-Key': subscription_key} response = requests.post(fetch_token_url, headers=headers) return str(response.text) def __chooseQuestionWord(pageTitle, keywords): sections = [s.title for s in wiki.page(pageTitle).sections] return sections[0] # if len(sections) == 0: # return keywords[0] # elif len(sections) == 1: # return sections[0] # else:
def snapshot_url(self): _snapshotUrl = settings.getSetting('snapshot_url', self.camera_number) return _snapshotUrl
def mjpeg_url(self): _mjpegUrl = settings.getSetting('mjpeg_url', self.camera_number) return _mjpegUrl
def video_url(self): _videoUrl = settings.getSetting("stream_url", self.camera_number) if _videoUrl == "": _videoUrl = "rtsp://{0}:{1}@{2}/videoMain".format(self.usr, self.pwd, self.url) return _videoUrl
import subprocess, os, codecs, threading from time import time, strftime, sleep # Local Script Inclusion import settings home = os.getcwd() first = 0 setting = settings.getSetting() def logyeah(): global setting os.chdir(setting['directory'] + "\\logs" if setting['directory'] is not "" else home + "\\logs") fname = strftime(setting['filename']) directory = strftime("%Y.%m.%d") string = subprocess.check_output(["netstat", "-an"]) if os.path.exists(directory): pass else: os.mkdir(directory) os.chdir(directory) with open(fname, "wb") as f: f.write(string) os.chdir(home) print(fname)
def __init__(self, camera, monitor): self.camera = camera self.monitor = monitor self.cond_service = settings.getSetting_int('cond_service', self.camera.number) self.cond_manual = settings.getSetting_int('cond_manual', self.camera.number) self.dur_service = settings.getSetting_int('dur_service', self.camera.number) self.dur_manual = settings.getSetting_int('dur_manual', self.camera.number) self.prefix = 'Preview' self.buttons = [] # Positioning of the window WIDTH = 320 HEIGHT = 180 scaling = settings.getSetting_float('scaling', self.camera.number) width = int(float(WIDTH * scaling)) height = int(float(HEIGHT * scaling)) button_scaling = 0.5 * scaling button_width = int(round(Button.WIDTH * button_scaling)) position = settings.getSetting('position', self.camera.number).lower() if 'bottom' in position: y = 720 - height else: y = 0 if 'left' in position: x = 0 start = -width else: x = 1280 - width start = width animations = [ ('WindowOpen', ("effect=slide start={0:d} time=1300 tween=cubic easing=out" ).format(start)), ('WindowClose', ("effect=slide end={0:d} time=900 tween=back easing=inout" ).format(start)) ] self.black = xbmcgui.ControlImage(x, y, width, height, _black) self.addControl(self.black) self.black.setAnimations(animations) self.img1 = xbmcgui.ControlImage(x, y, width, height, '') self.img2 = xbmcgui.ControlImage(x, y, width, height, '') self.addControl(self.img1) self.addControl(self.img2) self.img1.setAnimations(animations) self.img2.setAnimations(animations) self.close_button = Button(self, 'close', x + width - button_width - 10, y + 10, scaling=button_scaling) self.addControl(self.close_button) self.close_button.setAnimations(animations) self.setProperty('zorder', "99") self.playFullscreen = False self.stop() #Initializes state and makes ready to be used
def getCurrentInstructionAddress(self): pc = self.sim.regs[15].get(mayTriggerBkpt=False) pc -= 8 if getSetting("PCbehavior") == "+8" else 0 return pc
def getCurrentLine(self): pc = self.sim.regs[15].get(mayTriggerBkpt=False) pc -= 8 if getSetting("PCbehavior") == "+8" else 0 assert pc in self.addr2line, "Line outside of linked memory!" assert len(self.addr2line[pc]) > 0, "Line outside of linked memory!" return self.addr2line[pc][-1]
from pprint import pprint from IPython.display import HTML import settings import Question from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() # Get WikiText CurriculumText = wiki.page(ssdk.top_doc).content # Compare texts subscription_key = settings.getSetting('text_key') assert subscription_key text_analytics_base_url = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.0/" key_phrase_api_url = text_analytics_base_url + "keyPhrases" print(key_phrase_api_url) documents = {'documents' : [ {'id': '1', 'text': ssdk.KimText}, {'id': '2', 'text': CurriculumText} ]} headers = {'Ocp-Apim-Subscription-Key': subscription_key} response = requests.post(key_phrase_api_url, headers=headers, json=documents) key_phrases = response.json()
def StartConversation(): # Creates an instance of a speech config with specified subscription key and service region. # Replace with your own subscription key and service region (e.g., "westus"). speech_key, service_region = settings.getSetting( 'speech_key'), "northeurope" speech_config = speechsdk.SpeechConfig(subscription=speech_key, region=service_region) # Creates a recognizer with the given settings speech_recognizer = speechsdk.SpeechRecognizer(speech_config=speech_config) print("Say something...") result = speech_recognizer.recognize_once() # Checks result. if result.reason == speechsdk.ResultReason.RecognizedSpeech: print("Recognized: {}".format(result.text)) elif result.reason == speechsdk.ResultReason.NoMatch: print("No speech could be recognized: {}".format( result.no_match_details)) elif result.reason == speechsdk.ResultReason.Canceled: cancellation_details = result.cancellation_details print("Speech Recognition canceled: {}".format( cancellation_details.reason)) if cancellation_details.reason == speechsdk.CancellationReason.Error: print("Error details: {}".format( cancellation_details.error_details)) KimText = result.text ### Text analytics - Key Phrases subscription_key = settings.getSetting('text_key') assert subscription_key text_analytics_base_url = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.0/" key_phrase_api_url = text_analytics_base_url + "keyPhrases" print(key_phrase_api_url) documents = { 'documents': [ { 'id': '1', 'text': KimText }, ] } headers = {'Ocp-Apim-Subscription-Key': subscription_key} response = requests.post(key_phrase_api_url, headers=headers, json=documents) key_phrases = response.json() pprint(key_phrases) table = [] for document in key_phrases["documents"]: text = next( filter(lambda d: d["id"] == document["id"], documents["documents"]))["text"] phrases = ",".join(document["keyPhrases"]) table.append("<tr><td>{0}</td><td>{1}</td>".format(text, phrases)) HTML("<table><tr><th>Text</th><th>Key phrases</th></tr>{0}</table>".format( "\n".join(table))) # Send information to Kim k_ph = key_phrases["documents"][0]["keyPhrases"] if len(k_ph) > 0: top_keywords = getWikiData.most_freq_keyword(KimText, k_ph) top_doc, keywords = getWikiData.getWikiData(top_keywords, k_ph, 1) # Recieve information from Kim if top_doc != '': Question.GenerateQuestion(top_keywords, top_doc) # Loop conversation def SaySome(): speech_recognizer = speechsdk.SpeechRecognizer( speech_config=speech_config) print("Say something...") result = speech_recognizer.recognize_once() if result.reason == speechsdk.ResultReason.RecognizedSpeech: print("Recognized: {}".format(result.text)) elif result.reason == speechsdk.ResultReason.NoMatch: print("No speech could be recognized: {}".format( result.no_match_details)) elif result.reason == speechsdk.ResultReason.Canceled: cancellation_details = result.cancellation_details print("Speech Recognition canceled: {}".format( cancellation_details.reason)) if cancellation_details.reason == speechsdk.CancellationReason.Error: print("Error details: {}".format( cancellation_details.error_details)) return (result) def AnalyzeSome(): text_analytics_base_url = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.0/" key_phrase_api_url = text_analytics_base_url + "keyPhrases" print(key_phrase_api_url) documents = { 'documents': [ { 'id': '1', 'text': KimText }, ] } headers = {'Ocp-Apim-Subscription-Key': subscription_key} response = requests.post(key_phrase_api_url, headers=headers, json=documents) key_phrases = response.json() pprint(key_phrases) table = [] for document in key_phrases["documents"]: text = next( filter(lambda d: d["id"] == document["id"], documents["documents"]))["text"] phrases = ",".join(document["keyPhrases"]) table.append("<tr><td>{0}</td><td>{1}</td>".format(text, phrases)) HTML("<table><tr><th>Text</th><th>Key phrases</th></tr>{0}</table>". format("\n".join(table))) k_ph = key_phrases["documents"][0]["keyPhrases"] if len(k_ph) > 0: top_keywords = getWikiData.most_freq_keyword(KimText, k_ph) top_doc, keywords = getWikiData.getWikiData(top_keywords, k_ph, 1) # KimConversation is the stored information from conversations txtfile = open(top_doc + ".txt", "w+") KimConversation = result.text KimText = result.text def StoreSome(): KimConversation = result.text KimText = result.text # Turn KimConversation into learned information # Create or open txt file with topic name with open(txtfile) as appendtext: appendtext.write(KimConversation) with open(txtfile, "r") as readtext: txtdata = readtext.readlines() numWords = len(txtdata.split()) i = 1 import similaritychecker as SCKR KimActive = True if numWords >= 100: if SCKR.precision >= 0.5: KimActive == False elif i >= 10: KimActive == False else: KimActive == True while KimActive: # talk to Kim SaySome() # save input StoreSome() # Analyse input AnalyzeSome() # get new question if top_doc != '': Question.GenerateQuestion(top_keywords, top_doc) i = 1 + i # evaluate perfermance and elaborate if precision is below 10 percent. # while i > 1: # if SCKR.precision <= 0.1: # Question.GenerateNegativeElaboration() # else: # Question.GenerateAppraise() # break # Elaborate, evaluate and start conversation # Flow in conversation text_analytics_base_url = "https://northeurope.api.cognitive.microsoft.com/text/analytics/v2.0/" key_phrase_api_url = text_analytics_base_url + "keyPhrases" print(key_phrase_api_url) documents = { 'documents': [ { 'id': '1', 'text': KimText }, ] } headers = {'Ocp-Apim-Subscription-Key': subscription_key} response = requests.post(key_phrase_api_url, headers=headers, json=documents) key_phrases = response.json() pprint(key_phrases) table = [] for document in key_phrases["documents"]: text = next( filter(lambda d: d["id"] == document["id"], documents["documents"]))["text"] phrases = ",".join(document["keyPhrases"]) table.append("<tr><td>{0}</td><td>{1}</td>".format(text, phrases)) HTML("<table><tr><th>Text</th><th>Key phrases</th></tr>{0}</table>".format( "\n".join(table))) # Turn KimConversation into learned information # Create or open txt file with topic name txtfile = open(top_doc + ".txt", "w+") with open(txtfile) as appendtext: appendtext.write(KimConversation)