def __init__(self): self.client = zulip.Client(site="https://chunkzz.zulipchat.com/api/") self.subscribe_all() self.chatbot = ChatBot( "Omega", trainer='chatterbot.trainers.ChatterBotCorpusTrainer') self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() self.tw = Twimega() self.motivate = Motivate() self.shortenedurl = Urlshortener() self.hacknews = Hackernews() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl" ]
def translate_func(self): self.speak( 'Opening Translate\nPlease Wait as opening Translate may take up to 4-5 seconds' ) from translate import Translate self.translate_win = Translate() self.translate_win.show()
def __call__(self, iq, cmd, form): lin = form.fields['in'].value louts = set(form.fields['out'].values) text = form.fields['text'].value.encode('utf-8') log.msg(u"From %s to %s: %s" % (lin, louts, unicode(text))) deferreds = [] responses = {} def _handleResponse(out, lang): responses[lang] = out for l in louts: try: t = Translate(Language(lin.upper()), Language(l.upper())) d = t.translate(text) deferreds.append(d) d.addCallback(_handleResponse, l) except: log.err() dl = defer.DeferredList(deferreds, consumeErrors=1) dl.addCallback(self._formatResponses, iq, cmd, responses) return dl
def __init__(self): self.client = zulip.Client(site="https://fazeup.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() # self.chatbot.train("chatterbot.corpus.english") self.crypto = Crypto() self.trans = Translate() self.g = Giphy() self.w = WikiPedia() # self.tw = Twimega() # self.motivate = Motivate() self.shortenedurl = Urlshortener() self.geo = Geocode() self.weather = Weather() self.dict_ = Dictionary() self.joke = Joke() self.pnr = Pnr() self.mustread = Mustread() self.ss = Ss() self.cricket = Cricket() self.poll = Poll() print("done init") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl", "movie", "currency", "holiday", "lyrics" ]
def __update(self, event): tr = Translate() text = self.__TextArea.get(1.0, END)[:-1] if len(text) > 0: bin = tr.toBin(text) doubles = tr.getDoubles() self.__TextTranslatedArea.delete(1.0, END) self.__TextTranslatedArea.insert(1.0, bin) self.__ListDict.delete(1, END) doubles = sorted(doubles, key=lambda x: x[1]) doubles.reverse() for d in doubles: if len(d) == 2: letter = d[0] count = d[1] if letter == " ": letter = "[SPACE]" elif letter == "µ": letter = "[NewLine]" count -= 0 if count > 0: self.__ListDict.insert(self.__ListDict.size(), letter + ": " + str(count)) else: self.__TextTranslatedArea.delete(1.0, END) self.__TextTranslatedArea.insert( 1.0, "le code Huffman apparaitera ici !") self.__ListDict.delete(1, END)
def targetcode(self): ''' 生成汇编代码 :return: ''' self.textBrowser.clear() t = Translate() s = self.textEdit.toPlainText() fg, info = t.entry(s) if fg: # t.optimize_code() ass_codes = gen_assemcodes(t.codes) info = ''.join(ass_codes) self.textBrowser.setText(info) self.textBrowser.selectAll() self.textBrowser.copy() # 提示已经复制到剪切板 icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) qw = QtWidgets.QWidget() qw.setWindowIcon(icon) QMessageBox.warning(qw, 'Tips', '汇编代码已复制!') else: pickle.dump((False, None), open('data/midway_sheet.pkl', 'wb')) info = '----- error !\n' + '\n'.join(info) self.textBrowser.setText(info) self.save()
def _translate_in_all_languages(self, language_o, words): for language in Language.list_all_languages().split('\n'): try: t = Translate(Language(language_o.upper()), Language(language)) t.translate(words.encode('utf-8')).addCallback(self._success, jid, prot, language) \ .addErrback(self._error, jid, prot) except Exception: pass
def __init__(self): self.client = zulip.Client(site="https://bint.zulipchat.com/api/") self.subscribe_all() self.translate = Translate() self.location = Location() self.news = News() self.subKeys = ["hello", "sample"] self.todoList = []
def _numba_compile(func): global __tr_map__ llvm = kws.pop("llvm", True) if func in __tr_map__: print ("Warning: Previously compiled version of %r may be " "garbage collected!" % (func,)) t = Translate(func, *args, **kws) t.translate() __tr_map__[func] = t return t.get_ctypes_func(llvm)
def __init__(self): # initialize crawler object for Article Scraper super(ArticleScraper, self).__init__() self.crawler = self.browser # initialize a translator object self.translator = Translate() self.CSS_SELECTOR = "div.bilingual.cf > div.cf.articleContent"
def generate_query(self): if 'workload' in self.scheme: rel_list = [(x.source, x.target, x.label) for x in self.relation_ins] wl = Workload(list(self.node_labels), rel_list, self.workload) queries = wl.generate_workload() filename = 'query.cypher' tl = Translate(filename) tl.translate(queries)
def getTranslatedResume(): #change to ajax inInfo = request.args.get("inInfo",type=str) outInfo = Translate(inInfo) outInfo.tr1() if 'login' in session: g.db.execute("insert into resumes (username,outresume) values(?,?)", [session["login"]["username"],outInfo.tojson()]) g.db.commit() return jsonify(result=outInfo.tojson())
def vectorize(func): try: t = Translate(func) t.translate() print t.mod return t.make_ufunc() except: print "Warning: Could not create fast version..." import numpy return numpy.vectorize(func)
def main(): Translate.make_note_dictionary(sys.argv[1]) Translate.translate_notes(sys.argv[2], sys.argv[3]) Lib.play_midi(sys.argv[4]) # Lib.create_histogram() # Lib.create_xml() # Lib.translate_german() Markov.markov_chains(sys.argv[5], sys.argv[6])
def translate_word(self): ab = self.TargetLanguageList1.get( self.TargetLanguageList1.curselection()) nput = self.imgTxtScrolled.get("1.0", END) obj2 = Translate(nput) obj2.translate(ab) translatedLang = obj2.translatedLang() self.TargetLanguageTextScrolled.delete('0', END) self.TargetLanguageTextScrolled.insert('0', translatedLang) print(ab)
def charts(): translate = Translate() words_to_translate = request.args['words'] count_words = translate.count_words(words_to_translate) words = translate.sort_words(count_words) visual = Visual(dict_words=words, file_name="line") return render_template('chart.html', title='Analysis', chart=visual.mkPie())
def _numba_compile(func): global __tr_map__ llvm = kws.pop('llvm', True) if func in __tr_map__: print( "Warning: Previously compiled version of %r may be " "garbage collected!" % (func, )) t = Translate(func, *args, **kws) t.translate() __tr_map__[func] = t return t.get_ctypes_func(llvm)
def __init__(self, **kwargs): self.span_list = [] kwargs[ 'class_'] = 'w-2/3 bg-white mt-20 rounded-lg shadow p-12 flex flex-wrap' kwargs['style'] = 'min-height: 20rem;' super().__init__(**kwargs) self.en_area = None self.tw_area = None self.sentence_list = [] self.ts = Translate('zh-TW', 'en')
def __call__(self, jid, prot, args): language_o, raw = args.split(' ', 1) words, languages = raw.split(' -> ') languages = [ lan.strip() for lan in languages.split(',') ] for language in languages: try: t = Translate(Language(language_o.upper()), Language(language.upper())) t.translate(words.encode('utf-8')).addCallback(self._success, jid, prot, language.lower()) \ .addErrback(self._error, jid, prot) except Exception, e: self._error(e.message, jid, prot)
def translate_words(): translate_server = getenv("TRANSLATE_SRV", "http://127.0.0.1:8080") translate = Translate(translate_server) words_to_translate = request.args['words'] count_words = translate.count_words(words_to_translate) translate_words = translate.translate_words(count_words) words = translate.sort_words(translate_words) return render_template('translate_words.html', title='Translated words', words=words)
def __init__(self): self.system_sound = SoundMP3('../sound/system_sound/registerd', '../sound/system_sound/dev') self.trans = Translate() self.gc_controller = GoogleCloudController('', api_key='') self.translater = Translate() self.forecast = Forecast('') self.mecab = MeCab.Tagger( "-d /home/linuxbrew/.linuxbrew/lib/mecab/dic/mecab-ipadic-neologd") self.temporary_data = '' self.return_state = {} self.jalan_controller = jalan_controller()
def my_validater(self): nput = self.InputText.get() self.OutputText.delete('0', END) ab = self.TargetLanguageList2.get( self.TargetLanguageList2.curselection()) obj2 = Translate(nput) obj2.translate(ab) translatedLang = obj2.translatedLang() self.OutputText.insert('0', translatedLang) return True
def vectorize(func): global __tr_map__ try: if func not in __tr_map__: t = Translate(func) t.translate() __tr_map__[func] = t else: t = __tr_map__[func] return t.make_ufunc() except: print "Warning: Could not create fast version..." import numpy return numpy.vectorize(func)
def translate(self): t = Translate() target = 'zh' plainText = self.plainEdit.toPlainText() if len(plainText) == 0: return else: # TODO 处理原始文本 plainText = self.utils.processPlainText(plainText) translatedText = t.translated_content(plainText, target) self.translatedEdit.setText(translatedText) if self.settings.autoCopy: self.clipboard.setText(translatedText) else: pass
def __init__(self): self.client = zulip.Client(site="https://saharsh.zulipchat.com/api/") self.subscribe_all() self.trans = Translate() self.tw = Twimega() self.pnr = Pnr() self.weather = Weather() self.geo = Geocode() print("Initialization Done ...") self.subkeys = [ "crypto", "translate", "define", "joke", "weather", "giphy", "pnr", "mustread", "poll", "hackernews", "hn", "HN", "motivate", "twitter", "screenshot", "memo", "cricnews", "help", "shorturl" ]
def __init__(self): self.client = zulip.Client(site="https://technh.zulipchat.com/api/", api_key="vkEQgQYDPUgAGmXaTXdMPsMwlkkgMfM5", email="*****@*****.**") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie= Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() self.github = GitHub() self.chatbot = ChatBot(name="technehru") print("done init") self.subkeys = ["use", "help", "translate", "hackernews", "hn", "hotel", "HN", "cricnews", "cricketnews", "movie", "currency", "holiday", "lyrics", "github"]
def Translate_event(self, value): val = self.memory.getData("translate") print("Evenement : Tranlate ??") if (val != "1"): print("Evenement : une demande de traduction de " + val) t = Translate(val) self.memory.raiseEvent("Translate_vers_Java", t)
async def add_order_price(message: types.Message): prices = Translate.get_prices(str(message.text)) if prices is not None: if self.order_type == 'buy': self.order_opening_price = prices[0] self.order_limit_price = prices[1] elif self.order_type == 'sell': self.order_opening_price = prices[1] self.order_limit_price = prices[0] reply_message = self.order_review() if is_time_between(self.OPENING_TIME, self.CHECK_OUT_TIME, datetime.now().time()): reply_message += '❕ امروزی یا فردایی؟' await message.reply( reply_message, reply_markup=keyboards.order_today_tomorrow_kb) else: reply_message += 'از ساعت تسویه حساب گذشته است. \nفقط سفارش امروزی ممکن میباشد.' await message.reply(reply_message, reply_markup=keyboards.order_today_kb) await BotStates.ENTER_TODAY_TOMORROW.set() else: await message.reply('قیمتها تشخیص داده نشد!', reply_markup=keyboards.cancel_kb)
def run(self): print("Interface Thread Started\n") self.translate = Translate() while True: # transfer user input to serial port cmd = raw_input(">>:") if cmd == "exit": sys.exit() else: self.sendData = self.translate.commandForKatie(cmd.lower()) self.serClient.write(self.sendData) # give the arduino time to receive, process and populate data buffer print("Sending data: " + self.sendData) time.sleep(1) # get data for millisecs as stated by user command # inWaiting() basically checks if there is anymore data in the serial buffer # its similar to waiting for EOF for files. while self.serClient.inWaiting(): try: data = self.serClient.readline() if "#" not in data: continue print(self.translate.dataFromKatie(data)) except KeyboardInterrupt: print("Exiting...") break
def __init__(self): self.client = zulip.Client(site="https://saharsh.zulipchat.com/api/") self.subscribe_all() self.trans = Translate() self.tw = Twimega() self.pnr = Pnr() self.weather = Weather() self.geo = Geocode() self.searching = Places() self.help = Help() print("Initialization Done ...") self.subkeys = [ "translate", "weather", "pnr", "post", "post_image", "twitter", "help", "search" ]
def vectorize(func): global __tr_map__ try: if func not in __tr_map__: t = Translate(func) t.translate() __tr_map__[func] = t else: t = __tr_map__[func] return t.make_ufunc() except Exception as msg: print "Warning: Could not create fast version...", msg import traceback traceback.print_exc() import numpy return numpy.vectorize(func)
def __init__(self): self.client = zulip.Client(site="https://myra.zulipchat.com/api/") self.subscribe_all() self.hacknews = Hackernews() self.trans = Translate() self.movie = Movie() self.lyrics = Lyrics() self.holiday = Holiday() self.currency = Currency() self.cricket = Cricket() print("done init") self.subkeys = [ "translate", "hackernews", "hn", "hotel", "HN", "askme", "cricnews", "movie", "currency", "holiday", "lyrics" ]
async def change_checkout(message: types.Message): new_checkout = Translate.get_time(message.text) if new_checkout is not None: self.CHECK_OUT_TIME = new_checkout reply_message = 'ساعت تسویه با موفقیت تغییر یافت.' await message.reply(reply_message, reply_markup=keyboards.cancel_kb) await BotStates.DEFAULT.set()
async def change_opening(message: types.Message): new_opening = Translate.get_time(message.text) if new_opening is not None: self.OPENING_TIME = new_opening reply_message = 'ساعت شروع با موفقیت تغییر یافت.' await message.reply(reply_message, reply_markup=keyboards.cancel_kb) await BotStates.DEFAULT.set()
def midcode(self): ''' 生成中间代码 :return: ''' self.textBrowser.clear() t = Translate() s = self.textEdit.toPlainText() fg, info = t.entry(s) if fg: t.optimize_code() pickle.dump((True, t.codes), open('data/midway_sheet.pkl', 'wb')) else: pickle.dump((False, None), open('data/midway_sheet.pkl', 'wb')) info = '----- error !\n' + '\n'.join(info) self.textBrowser.setText(info) self.save()
def getAllIngredients(self): df = self.df_AllergenData ingredients = df['IngredientsInfo'].tolist() productId = df['Gtin'].tolist() languageInfo = df['LanguageInfo'].tolist() wordToTranslation = {} uniqueIngredients = set() # product_ingredients_mapping = defaultdict(list) x = 0 for i in range(len(ingredients)): try: if (languageInfo[i] != 'en'): vals = re.findall(r'\(E\d+\)|([^\W\d]+(?:\s+[^\W\d]+)*)', ingredients[i]) instance = Translate() for item in vals: if (len(item) < 3): continue translatedItem = instance.TranslateWord( item, languageInfo[i]) uniqueIngredients.add(translatedItem.lower()) wordToTranslation.update({ item: [ translatedItem, instance.DetectLanguage(translatedItem) ] }) else: vals = re.findall(r'\(E\d+\)|([^\W\d]+(?:\s+[^\W\d]+)*)', ingredients[i]) for j in vals: if (len(item) < 3): continue uniqueIngredients.add(j.lower()) # product_ingredients_mapping[j].append(str(productId[i])) wordToTranslation.update({item: [item, 'en']}) except Exception as e: x += 1 # Dataframe of items ===> productId mapping # frame = pd.DataFrame(dict([ (k,Series(v)) for k,v in product_ingredients_mapping.items() ])).transpose() frame = pd.DataFrame(wordToTranslation, index=['Translation', 'Language']).transpose() frame.to_csv('frame.csv', sep=',', encoding='latin-1') return uniqueIngredients
def __init__(self, uiPrintMessage, sendQuit=None): self.settings = Settings(self.printMessage) self.turing = Backend() self.client = None self.server = None self.uiPrintMessage = uiPrintMessage self.sendQuit = sendQuit self.connexion = None self.server = Server(self.turing, self.printMessage, self.writeMessages) self.client = Client(self.turing, self.printMessage, self.writeMessages) self.username = self.settings.getSetting("username") self.otherUsername = None self.trustManager = TrustManager(self.printMessage) self.msgBuffer = [] self.fileList = [] self.translate = Translate(self.printMessage, self.settings.getSetting("language")) setObject(self.translate)
def parseImage(): self.progress.grid(row=1, column=0) self.progress.start() time.sleep(5) temp = os.path.basename(self.file_path) temp2 = os.path.dirname(self.file_path) filename, file_extension = os.path.splitext( self.file_path) print(file_extension) # if pdf if (file_extension == ".pdf"): print(file_extension) pdfread = Pdfread(self.file_path, filename) v = pdfread.extract() obj2 = Translate(v) detectedLang = obj2.detectLang() self.progress.stop() self.progress.grid_forget() elif (file_extension == ".odt" or file_extension == "docx"): obj = DocReader(self.file_path, filename) v = obj.extract() obj2 = Translate(v) detectedLang = obj2.detectLang() self.progress.stop() self.progress.grid_forget() else: obj = Converter(temp, temp2) v = obj.execute() obj2 = Translate(v) detectedLang = obj2.detectLang() self.progress.stop() self.progress.grid_forget() if not v.isspace(): self.setTempText(v) self.load_desc() self.load_detect_lang(detectedLang) else: tkinter.messagebox.showerror( "OOPS!", "No Text Found!!\n") self.browseTButton['state'] = 'normal'
def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ self.iface = iface self.translate = Translate() self.running = False # Declare instance attributes self.actions = [] self.menu = self.translate.tr(u'&Plugin Mapotempo') self.toolbar = self.iface.addToolBar(u'PluginMapotempo') self.toolbar.setObjectName(u'PluginMapotempo') self.iface.addToolBarWidget(self.toolbar) self.dlg = PluginMapotempoDialogBase() self.dlg_2 = CreateZoning() self.dock = DockWidget() #instance self.layer_inst = PluginMapotempoLayer( self.dlg, self.dock, self.iface, self.translate) self.handle = PluginMapotempoHandle( self.layer_inst, self.dlg, self.dlg_2, self.dock, self.translate) self.layer_inst.setHandler(self.handle) self.dock.setHandler(self.handle) self.dlg.pushButton.clicked.connect(self.handle.handleButtonSave) self.dlg_2.pushButton.clicked.connect(self.handle.handleButtonNewZoning) self.dock.pushButton.clicked.connect(self.handle.handleButtonConnect) self.dock.pushButton_2.clicked.connect(self.layer_inst.refresh) self.dock.pushButton_4.clicked.connect(self.handle.HandleParam) self.dock.pushButton_5.clicked.connect(self.handle.newZoningLayer) self.dock.comboBox.activated.connect(self.handle.HandleSelect) self.dock.pushButton_3.clicked.connect(self.handle.HandleApplyZoning) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock) self.handle.keyConnection = self.handle.s.value("PluginMapotempo/key") self.handle.hostConnection = self.handle.s.value("PluginMapotempo/host")
def setUp(self): self.xl = Translate()
def getTranslatedResume1(): #change to ajax inInfo = request.args.get("inInfo",type=str) outInfo = Translate(inInfo) outInfo.tr1() return jsonify(result=outInfo.tojson())
class TranslateTest(unittest.TestCase): xl = None; def setUp(self): self.xl = Translate() def tearDown(self): pass def testGenerateHeaderInfo(self): for i in ["reset", "encoders", "autoexplore", "move", "i2c"]: self.assertEqual(self.xl.cmdDict[i], self.xl.generateHeader(i), "it should generate header when correct command is entered") def testGenerateHeaderInfoForNonCommands(self): with self.assertRaises(Exception) as cm: self.xl.generateHeader("hello") self.assertEqual(str(cm.exception), "Command not recognized", "should generate error when incorrect command is entered") def testLeftPaddedNumericOperandsWithLessThan4Digits(self): # Normal Case self.assertEqual("0001", self.xl.generateOperand(1), "it should return string with 3 left padded zeros") self.assertEqual("0020", self.xl.generateOperand(20), "it should return string with 2 left padded zeros") self.assertEqual("0300", self.xl.generateOperand(300), "it should return string with 1 left padded zeros") self.assertEqual("4000", self.xl.generateOperand(4000), "it should return string with 0 left padded zeros") def testLeftPaddedNumericOperandsWithMoreThan4Digits(self): # Exception Case with self.assertRaises(Exception) as cm: self.xl.generateOperand(50000) self.assertEqual(str(cm.exception), "Operand larger than 4 digits", "should throw exception for incorrect number of digits") # def testSetHeaderFromCommand(self): # self.assertEqual(None, self.xl.sendHead, "should return None before setHeader() is called") ## Single Command only # self.assertEqual("@", self.xl.setHeader("command"), "should return @ with no errors") ## Single Command with 1 operand # self.assertEqual("@", self.xl.setHeader("command operand1"), "should return @ with no errors") ## Command Chain with operands in multiples of two # self.assertEqual("$", self.xl.setHeader("command operand1 operand2"), "should return $ with no errors") ## Command Chain with incorrect operands ## self.assertRaises(Exception, "Incorrect",self.xl.setHeader, "command operand1 operand 2") # # def testSetHeaderFromCommandRaisesException(self): # with self.assertRaises(Exception) as cm: # self.xl.setHeader("cmd op1 op2 op3") # self.assertEqual(str(cm.exception), "Incorrect Operands List", "should throw exception for incorrect number of operands") def testSetOperandsForCommands(self): # Command with 1 operand self.assertEqual("0040", self.xl.setOperands("40"), "should return left padded concatenated string for numeric list with 1 number") # Command with 2 operands # Turn Left self.assertEqual("3003002000000", self.xl.setOperands("left 30"), "should return left padded concatenated string for list with sub-command and operand") # Turn Right self.assertEqual("3-004502000000", self.xl.setOperands("right 45"), "should return left padded concatenated string for list with sub-command and operand") # Go Forward self.assertEqual("3000002000200", self.xl.setOperands("forward 200"), "should return left padded concatenated string for list with sub-command and operand") # Command with operands in multiples of 2 self.assertEqual("6003002000000000002000200", self.xl.setOperands("left 30 forward 200"), "should return left padded concatenated string for list with sub-command and operand") def testSetOperandsForCommandsWithIncorrectOperandList(self): # Unrecognized direction with self.assertRaises(Exception) as cm: self.xl.setOperands("down 40") self.assertEqual(str(cm.exception), "Movement Direction not recognized", "should throw exception for unrecognized direction") # Unrecognized list of operands with self.assertRaises(Exception) as cm: self.xl.setOperands("up down 40") self.assertEqual(str(cm.exception), "Operand List not Recognized", "should throw exception for unrecognized number of operands") def testUserCommands(self): self.assertEqual("@r", self.xl.commandForKatie("reset"), "should return translated command for user input - reset") self.assertEqual("@b0002", self.xl.commandForKatie("beep 2"), "should return translated command for user input - beep") self.assertEqual("$3000002000300", self.xl.commandForKatie("move forward 300"), "should return translated command for user input - move forward") self.assertEqual("$3009002000000", self.xl.commandForKatie("move left 90"), "should return translated command for user input - move forward") self.assertEqual("$3-004502000000", self.xl.commandForKatie("move right 45"), "should return translated command for user input - move forward") self.assertEqual("$6004502000000000001500300", self.xl.commandForKatie("move left 45 velocity 150 forward 300"), "should return translated command for user input - move forward") # Initial speed check self.xl.resetVelocity() self.assertEqual(200, self.xl.getVelocity(), "should return velocity as 200") self.assertEqual("Velocity changed", self.xl.commandForKatie("velocity 150"), "should change the velocity in the command sent over to katie to 150") self.assertEqual(150, self.xl.getVelocity(), "should return velocity as 150") def testDataHeaderRaisesExceptionForIncorrectHeaderFromKatie(self): with self.assertRaises(Exception) as cm: self.xl.convertHeader("hello") self.assertEqual("Incorrect data header received from Katie", str(cm.exception), "should return exception when incorrect header is supplied") def testDataFromKatie(self): self.assertEqual("Bump\tWall\tCliffL2\tCliffL1\tCliffR1\tCliffR2\n0000\t0000\t0000\t0000\t0000\t0000", self.xl.dataFromKatie("#cfs 0000 0000 0000 0000 0000 0000"), "should return formatted human readable") print(self.xl.dataFromKatie("#cfs 0000 0000 0000 0000 0000 0000"))
class PluginMapotempo: """QGIS Plugin Implementation.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ self.iface = iface self.translate = Translate() self.running = False # Declare instance attributes self.actions = [] self.menu = self.translate.tr(u'&Plugin Mapotempo') self.toolbar = self.iface.addToolBar(u'PluginMapotempo') self.toolbar.setObjectName(u'PluginMapotempo') self.iface.addToolBarWidget(self.toolbar) self.dlg = PluginMapotempoDialogBase() self.dlg_2 = CreateZoning() self.dock = DockWidget() #instance self.layer_inst = PluginMapotempoLayer( self.dlg, self.dock, self.iface, self.translate) self.handle = PluginMapotempoHandle( self.layer_inst, self.dlg, self.dlg_2, self.dock, self.translate) self.layer_inst.setHandler(self.handle) self.dock.setHandler(self.handle) self.dlg.pushButton.clicked.connect(self.handle.handleButtonSave) self.dlg_2.pushButton.clicked.connect(self.handle.handleButtonNewZoning) self.dock.pushButton.clicked.connect(self.handle.handleButtonConnect) self.dock.pushButton_2.clicked.connect(self.layer_inst.refresh) self.dock.pushButton_4.clicked.connect(self.handle.HandleParam) self.dock.pushButton_5.clicked.connect(self.handle.newZoningLayer) self.dock.comboBox.activated.connect(self.handle.HandleSelect) self.dock.pushButton_3.clicked.connect(self.handle.HandleApplyZoning) self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock) self.handle.keyConnection = self.handle.s.value("PluginMapotempo/key") self.handle.hostConnection = self.handle.s.value("PluginMapotempo/host") def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/mapotempo-qgis-plugin/icons/icon.png' self.add_action( icon_path, text=self.translate.tr(u'Plugin Mapotempo'), callback=self.run, parent=self.iface.mainWindow()) def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu( self.translate.tr(u'&Plugin Mapotempo'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar self.iface.removeDockWidget(self.dock) def run(self): """Run method that performs all the real work""" self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock)