Пример #1
0
    def merge(self, baseLesson, otherLesson):
        merge = copy.deepcopy(baseLesson)
        with contextlib.ignored(KeyError):
            merge["list"]["items"].extend(otherLesson["list"]["items"])
        with contextlib.ignored(KeyError):
            merge["list"]["tests"].extend(otherLesson["list"]["tests"])

        return merge
Пример #2
0
	def correctLastAnswer(self, result):
		self._test["results"][-1] = result

		with contextlib.ignored(IndexError):
			if self._indexes[-1] == self._previousIndex:
				del self._indexes[-1]

		with contextlib.ignored(IndexError):
			#2 became 1 because of the new word
			if self._indexes[1] == self._previousIndex:
				del self._indexes[1]
Пример #3
0
    def disable(self):
        del self._modules
        with contextlib.ignored(AttributeError):
            del self.tts
        with contextlib.ignored(AttributeError):
            del self.say
        with contextlib.ignored(AttributeError):
            del self._ttsVoice
        with contextlib.ignored(AttributeError):
            del self._ttsSpeed

        self.active = False
Пример #4
0
	def disable(self):
		del self._modules
		with contextlib.ignored(AttributeError):
			del self.tts
		with contextlib.ignored(AttributeError):
			del self.say
		with contextlib.ignored(AttributeError):
			del self._ttsVoice
		with contextlib.ignored(AttributeError):
			del self._ttsSpeed

		self.active = False
Пример #5
0
 def _loadLesson(self, lesson):
     if not lesson:
         return
     lesson["changed"] = True
     with contextlib.ignored(NotImplementedError):
         self._modules.default("active", type="loaderGui").loadFromLesson(
             "words", lesson)
Пример #6
0
    def save(self, type, lesson, path):
        #Copy, because we're going to modify it
        wordList = copy.deepcopy(lesson.list)

        for word in wordList.get("items", []):
            #results
            word["results"] = {"right": 0, "wrong": 0}
            for test in wordList.get("tests", []):
                for result in test["results"]:
                    if result["itemId"] == word["id"]:
                        with contextlib.ignored(KeyError):
                            word["results"][result["result"]] += 1
            #known, foreign and second
            word["known"] = self._compose(word["questions"])
            if len(word["answers"]) == 1 and len(word["answers"][0]) > 1:
                word["foreign"] = word["answers"][0][0]
                word["second"] = self._compose([word["answers"][0][1:]])
            else:
                word["foreign"] = self._compose(word["answers"])
                word["second"] = u""

        templatePath = self._mm.resourcePath("template.xml")
        t = pyratemp.Template(open(templatePath).read())
        data = {"wordList": wordList}
        content = t(**data)
        with open(path, "w") as f:
            f.write(content.encode("UTF-8"))

        lesson.path = None
Пример #7
0
	def load(self, path, resourceFilenames={}):
		with contextlib.closing(zipfile.ZipFile(path, "r")) as zipFile:
			listFile = zipFile.open("list.json")
			list = json.load(listFile)
			list = self._stringsToDatetimes(list)

			resources = {}
			for resourceKey, filename in resourceFilenames.iteritems():
				tf = tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(filename)[1])
				path2 = tf.name
				
				self._tempPaths.add(path2)
				with contextlib.ignored(KeyError):
					#KeyError: the file might not be in the zip. That's
					#not important enough to break on. It happens when
					#importing .ottp files created with OT < 3.2 e.g.
					resourceFile = zipFile.open(filename)
					
					shutil.copyfileobj(resourceFile, tf)
					tf.close()
					
					resources[resourceKey] = path2

		return {
			"resources": resources,
			"list": list,
		}
Пример #8
0
	def setResult(self, result):
		# Add the test to the list (if it's not already there)
		self._appendTest()

		self.askedItems += 1

		self._test["results"].append(result)
		if result["result"] == "wrong":
			with contextlib.ignored(IndexError):
				if self._indexes[-1] != self._currentIndex:
					self._indexes.append(self._currentIndex)
			with contextlib.ignored(IndexError):
				if self._currentIndex not in (self._indexes[1], self._indexes[2]):
					self._indexes.insert(2, self._currentIndex)

		self._sendNext()
Пример #9
0
		def addTakenTestlayoutumn(self, studentInTest):
			takenTestWidget = TakenTestWidget(self.connection, studentInTest, self.compose, self.answerChecker, self.appName)
			takenTestWidget.message.connect(self.message.emit)
			
			with contextlib.ignored(AttributeError):
				self.widget(2).setParent(None)
			self.insertWidget(2, takenTestWidget)
Пример #10
0
	def save(self, type, lesson, path):
		#Copy, because we're going to modify it
		wordList = copy.deepcopy(lesson.list)

		for word in wordList.get("items", []):
			#results
			word["results"] = {"right": 0, "wrong": 0}
			for test in wordList.get("tests", []):
				for result in test["results"]:
					if result["itemId"] == word["id"]:
						with contextlib.ignored(KeyError):
							word["results"][result["result"]] += 1
			#known, foreign and second
			word["known"] = self._compose(word["questions"])
			if len(word["answers"]) == 1 and len(word["answers"][0]) > 1:
				word["foreign"] = word["answers"][0][0]
				word["second"] = self._compose([word["answers"][0][1:]])
			else:
				word["foreign"] = self._compose(word["answers"])
				word["second"] = u""

		templatePath = self._mm.resourcePath("template.xml")
		t = pyratemp.Template(open(templatePath).read())
		data = {
			"wordList": wordList
		}
		content = t(**data)
		with open(path, "w") as f:
			f.write(content.encode("UTF-8"))

		lesson.path = None
Пример #11
0
	def _testSavingType(self, type, lesson):
		if self.mode not in MODES:
			self.skipTest("This tests isn't run in this mode.")
		for saver in self._mm.mods("active", type="save"):
			if not type in saver.saves:
				continue

			lessonCopy = copy.deepcopy(lesson)

			#save lesson
			for ext in saver.saves[type]:
				fd, path = tempfile.mkstemp(".%s" % ext)
				os.close(fd)
				saver.save(type, lesson, path)

				#file should exist after saving.
				self.assertTrue(os.path.isfile(path))
				#and it should not be empty.
				self.assertTrue(os.path.getsize(path) > 0)

				os.remove(path)
				with contextlib.ignored(OSError):
					#html saver
					shutil.rmtree(path + ".resources")

			try:
				self.assertEqual(lesson.list, lessonCopy.list)
				self.assertEqual(lesson.resources, lessonCopy.resources)
			except AssertionError:
				print "%s modified the lesson object passed to save(), which isn't allowed. More info:" % saver
				raise
Пример #12
0
 def stop_queue():
     stdout_stop.set()
     stderr_stop.set()
     with ignored(OSError):
         p.terminate()
     stdout_t.join()
     stderr_t.join()
Пример #13
0
		def paint(self, painter, option, index):
			self.initStyleOption(option, index)

			#set up document with syntax highlighting
			document = QtGui.QTextDocument()

			check = lambda item: True
			split = lambda words: []
			with contextlib.ignored(AttributeError):
				if index.column() == 0:
					check = self.checkQuestion
					split = self.splitQuestion
				elif index.column() == 1:
					check = self.checkAnswer
					split = self.splitAnswer
			SpellingHighlighter(check, split, document)

			#get elided text
			text = option.widget.fontMetrics().elidedText(option.text, option.textElideMode, option.rect.width() - document.documentMargin())
			#set elided text
			document.setHtml(text)

			#calculate place to start rendering
			yPos = option.rect.center().y() - option.widget.fontMetrics().height() / 2 - document.documentMargin()
			startPoint = QtCore.QPoint(option.rect.x(), yPos)

			#move to place to start rendering, render, and move back.
			painter.translate(startPoint)
			document.drawContents(painter)
			painter.translate(-startPoint)
Пример #14
0
 def retranslate(self):
     self.createLessonGroupBox.setTitle(_("Create lesson:"))
     self.loadLessonGroupBox.setTitle(_("Load lesson:"))
     self.helpGroupBox.setTitle(_("Help"))
     self.loadFromInternetButton.setText(_("Load from the internet"))
     with contextlib.ignored(AttributeError):
         self.recentlyOpenedGroupBox.setTitle(_("Recently opened:"))
Пример #15
0
        def retranslate(self):
            #disconnect the signal, so we can change some stuff without
            #other classes notice
            with contextlib.ignored(TypeError):
                #TypeError: not yet connected (first pass)
                super(TeachLessonTypeChooser,
                      self).currentIndexChanged.disconnect(
                          self.currentIndexChanged.emit)

            #save status
            i = self.currentIndex()

            #update data
            self.clear()
            self._lessonTypeModules = base._modules.sort("active",
                                                         type="lessonType")
            for lessontype in self._lessonTypeModules:
                self.addItem(lessontype.name, lessontype)

            #restore status
            if i != -1:
                self.setCurrentIndex(i)

            #re-connect signal
            super(TeachLessonTypeChooser, self).currentIndexChanged.connect(
                self.currentIndexChanged.emit)
Пример #16
0
    def disable(self):
        self.active = False

        del self._modules
        del self._js
        del self.code
        with contextlib.ignored(AttributeError):
            del self.translationIndex
Пример #17
0
        def retranslate(self):
            self.thinkWidget.retranslate()
            self.answerWidget.retranslate()

            curWid = self.currentWidget()
            with contextlib.ignored(AttributeError):
                self.newItem(self._currentWord)
            self.setCurrentWidget(curWid)
Пример #18
0
 def retranslate(self):
     self._levelLabelLabel.setText(_("Level"))
     self._speedLabelLabel.setText(_("Speed (words per minute)"))
     self._mistakesLabelLabel.setText(_("Amount of mistakes"))
     self._button.setText(_("Start exercise"))
     with contextlib.ignored(AttributeError):
         #requires self.username, which might not be set yet.
         self.updateInstruction()
Пример #19
0
		def retranslate(self):
			self._levelLabelLabel.setText(_("Level"))
			self._speedLabelLabel.setText(_("Speed (words per minute)"))
			self._mistakesLabelLabel.setText(_("Amount of mistakes"))
			self._button.setText(_("Start exercise"))
			with contextlib.ignored(AttributeError):
				#requires self.username, which might not be set yet.
				self.updateInstruction()
 def _resultsFor(self, word):
     results = []
     with contextlib.ignored(KeyError):
         for test in self._list["tests"]:
             results.extend(test)
     filteredResults = filter(lambda result: result["itemId"] == word["id"],
                              results)
     return map(lambda result: result["result"], filteredResults)
Пример #21
0
		def addTestlayoutumn(self, testInfo, studentsView, answerChecker):
			testWidget = TestWidget(self.connection, testInfo, studentsView, answerChecker)
			testWidget.takenTestSelected.connect(self.addTakenTestlayoutumn)
			testWidget.message.connect(self.message.emit)
			
			with contextlib.ignored(AttributeError):
				self.widget(1).setParent(None)
			self.insertWidget(1, testWidget)
Пример #22
0
    def save():
        try:
            list = json.loads(flask.request.form["list"])
        except KeyError:
            return json_err(
                "Please specify the 'list' field in the body form data.")
        except ValueError:
            return json_err("The posted list is invalid json.")

        dateFormat = "%Y-%m-%dT%H:%M:%S.%fZ"
        for item in list.get("items", []):
            with contextlib.ignored(KeyError):
                item["created"] = datetime.datetime.strptime(
                    item["created"], dateFormat)
        for test in list.get("tests", []):
            for result in test.get("results", []):
                with contextlib.ignored(KeyError):
                    result["active"]["start"] = datetime.datetime.strptime(
                        result["active"]["start"], dateFormat)
                    result["active"]["end"] = datetime.datetime.strptime(
                        result["active"]["end"], dateFormat)
        lesson = DummyLesson(list)

        try:
            filename = flask.request.form["filename"]
        except KeyError:
            return json_err(
                "Please specify the 'filename' field in the body form data.")

        #[1:] tears of the . in .txt
        ext = os.path.splitext(filename)[1][1:]
        if not ext in save_exts():
            return json_err("Unsupported filename extension. (%s)" % ext)

        fd, path = tempfile.mkstemp("." + ext)
        os.close(fd)
        for saver in savers:
            if ext in saver.saves.get("words", []):
                saver.save("words", lesson, path)
                resp = flask.send_file(path,
                                       as_attachment=True,
                                       attachment_filename=filename)
                break

        os.remove(path)
        return resp
Пример #23
0
def block_until_ssh_connection(hostname):
	while True:
		p = subprocess.Popen(["ssh", hostname], stdin=subprocess.PIPE)
		with contextlib.ignored(OSError):
			#the with statement handles the rare case of a broken pipe
			p.communicate("exit 0")
			p.wait()
			if p.returncode == 0:
				break
Пример #24
0
def block_until_ssh_connection(hostname):
    while True:
        p = subprocess.Popen(["ssh", hostname], stdin=subprocess.PIPE)
        with contextlib.ignored(OSError):
            #the with statement handles the rare case of a broken pipe
            p.communicate("exit 0")
            p.wait()
            if p.returncode == 0:
                break
Пример #25
0
	def testHasAttrs(self):
		for mod in self._mm.mods("active", type="load"):
			self.assertTrue(mod.getFileTypeOf)
			self.assertTrue(mod.load)
			self.assertTrue(mod.name)
			for type, ext in mod.loads.iteritems():
				self.assertTrue(type)
				self.assertTrue(ext)
			with contextlib.ignored(AttributeError):
				#optional. But not empty
				self.assertTrue(mod.mimetype)
Пример #26
0
 def __del__(self):
     '''
     User should explicit call (del BaseWrapper class) to avoid some abnormal process issue
     '''
     self.logger.info("Kill %s process created by this class", self._binaryname)
     for proc in self.subproc_list:
         if proc.returncode is None:
             self.logger.warning("PID %d is runing, try to kill it", proc.pid)
             with ignored(OSError):
                 proc.kill()
     self.logger.info("All %s process is clean", self._binaryname)
Пример #27
0
		def loadUrl(self, *args):
			with contextlib.ignored(KeyError): self.webview.setHtml(eval("7b2261626f75743a6d6f7a696c6c61223a20223c626f6479207374796c653d276261636b67726f756e642d636f6c6f723a6d61726f6f6e3b636f6c6f723a77686974653b666f6e742d66616d696c793a73657269663b666f6e742d7374796c653a6974616c69633b273e3c68313e4966206f6e6c7920517420776f756c64206a75737420737570706f7274204765636b6f2e2e2e3c2f68313e3c2f626f64793e222c2261626f75743a6368726f6d65223a20226d65682e222c2261626f75743a6f70657261223a20224f706572613f2057686174277320746861743f20536f6d657468696e6720656469626c65204920686f70653f222c2261626f75743a756e697665727365223a20223432222c2261626f75743a6965223a20223c626f6479207374796c653d276261636b67726f756e642d636f6c6f723a6c696d653b636f6c6f723a70696e6b3b666f6e742d66616d696c793a637572736976653b273e3c68313e25733c2f68313e3c2f626f64793e222025202822426c656768212022202a20313030292c2261626f75743a6f70656e74656163686572223a20223c7363726970743e73657454696d656f75742866756e6374696f6e202829207b77696e646f772e6c6f636174696f6e3d272573273b7d2c2033303030293c2f7363726970743e3c68313e596179213c2f68313e2220252073656c662e5f7374617274506167652c7d".decode("hex"))[unicode(self.urlbar.text())]); return

			if not unicode(self.urlbar.text()).startswith(u"http://"):
				#add http:// if it's not there yet
				self.url = QtCore.QUrl(u"http://" + self.urlbar.text(), QtCore.QUrl.TolerantMode)
			else:
				#otherwise just parse the url directly
				self.url = QtCore.QUrl(self.urlbar.text(), QtCore.QUrl.TolerantMode)
			#and load it
			self.webview.load(self.url)
Пример #28
0
	def retranslate(self):
		self.setWindowTitle(_("WRDS - login please:"))

		self.flayout.itemAt(0, QtGui.QFormLayout.LabelRole).widget().setText(
			_("Email:")
		)
		self.flayout.itemAt(1, QtGui.QFormLayout.LabelRole).widget().setText(
			_("Password:"******"<a href='https://wrds.eu/'>%s</a>" % _("Click here for more information about WRDS and its registration page."))
		with contextlib.ignored(AttributeError):
			self.saveCheckbox.setText(_("Remember email address and password"))
Пример #29
0
    def run(self):
        self._modules = set(self._mm.mods(type="modules")).pop()
        self._uiModule = self._modules.default("active", type="ui")

        self._connectEvents()
        self._updateMenuItems()

        with contextlib.ignored(IndexError):
            self.open_(sys.argv[1])

        self._uiModule.run(self._onCloseRequested)
        self._disconnectEvents()
Пример #30
0
	def run(self):
		self._modules = set(self._mm.mods(type="modules")).pop()
		self._uiModule = self._modules.default("active", type="ui")

		self._connectEvents()
		self._updateMenuItems()

		with contextlib.ignored(IndexError):
			self.open_(sys.argv[1])

		self._uiModule.run(self._onCloseRequested)
		self._disconnectEvents()
Пример #31
0
	def enable(self):
		global QtCore, QtGui, QtWebKit
		try:
			from PyQt4 import QtCore, QtGui, QtWebKit
		except ImportError:
			return
		installQtClasses()

		self._modules = set(self._mm.mods(type="modules")).pop()

		with contextlib.ignored(IndexError):
			#Keeps track of all created lessons
			for module in self._mm.mods("active", type="lesson"):
				module.lessonCreated.handle(self._lessonAdded)

		try:
			self._enabled = self._modules.default(type="settings").registerSetting(**{
				"internal_name": "org.openteacher.hiddenBrowser.enabled",
				"type": "boolean",
				"defaultValue": False,
				"callback": {
					"args": ("active",),
					"kwargs": {
						"type": "webbrowser"
					},
					"method": "updateActive"
				},
			})
		except IndexError:
			self._enabled = {
				"value": False,
			}
		metadata = self._modules.default("active", type="metadata").metadata
		
		#Register for retranslating
		try:
			translator = self._modules.default("active", type="translator")
		except IndexError:
			pass
		else:
			translator.languageChanged.handle(self._retranslate)
		#translate everything for the first time
		self._retranslate()

		#FIXME 3.1: This object is now built even if the webview is
		#never shown. Since building it is quite heavy (e.g. a Java
		#VM starts if installed), that should be delayed.
		self.browser = WebBrowserWidget(self._mm.resourcePath, metadata["website"])
		
		self._lessons = set()
		
		self.active = True
Пример #32
0
	def save():
		try:
			list = json.loads(flask.request.form["list"])
		except KeyError:
			return json_err("Please specify the 'list' field in the body form data.")
		except ValueError:
			return json_err("The posted list is invalid json.")

		dateFormat = "%Y-%m-%dT%H:%M:%S.%fZ"
		for item in list.get("items", []):
			with contextlib.ignored(KeyError):
				item["created"] = datetime.datetime.strptime(item["created"], dateFormat)
		for test in list.get("tests", []):
			for result in test.get("results", []):
				with contextlib.ignored(KeyError):
					result["active"]["start"] = datetime.datetime.strptime(result["active"]["start"], dateFormat)
					result["active"]["end"] = datetime.datetime.strptime(result["active"]["end"], dateFormat)
		lesson = DummyLesson(list)

		try:
			filename = flask.request.form["filename"]
		except KeyError:
			return json_err("Please specify the 'filename' field in the body form data.")

		#[1:] tears of the . in .txt
		ext = os.path.splitext(filename)[1][1:]
		if not ext in save_exts():
			return json_err("Unsupported filename extension. (%s)" % ext)

		fd, path = tempfile.mkstemp("." + ext)
		os.close(fd)
		for saver in savers:
			if ext in saver.saves.get("words", []):
				saver.save("words", lesson, path)
				resp = flask.send_file(path, as_attachment=True, attachment_filename=filename)
				break

		os.remove(path)
		return resp
Пример #33
0
		def updateList(self, list, dataType):
			self.testsModel.list = list
			self.testsModel.dataType = dataType
			self.notesWidget.updateList(list)
			self.detailsWidget.updateList(list, dataType)
			with contextlib.ignored(AttributeError):
				self.percentNotesViewer.hide()
			try:
				self.percentNotesViewer = self._createPercentNotesViewer(list["tests"])
			except (TypeError, KeyError):
				pass
			else:
				self.addWidget(self.percentNotesViewer)
Пример #34
0
 def kill_binary_proc(self):
     '''
     From System level to kill all binary process(create by this class)
     '''
     self.logger.info("Kill %s process start", self._binaryname)
     if self.subproc_list == []:
         self.logger.info("there is no %s process found", self._binaryname)
         return True
     for process in self.subproc_list:
         self.logger.info("Try to kill %s, PID: %d", self._binaryname, process.pid)
         with ignored(Exception):
             process.kill()
     return True
Пример #35
0
        def __init__(self, keyboardWidget, *args, **kwargs):
            super(TeachLessonWidget, self).__init__(*args, **kwargs)

            self.changeSettingsButton = QtGui.QPushButton()
            self.wordLabel = QtGui.QLabel()
            self.questionLabel = QtGui.QLabel()
            font = QtGui.QFont()
            font.setPointSize(24)
            self.questionLabel.setFont(font)
            self.questionLabel.setWordWrap(True)
            self.commentLabel = QtGui.QLabel()
            self.commentLabel.setWordWrap(True)
            if keyboardWidget is not None:
                self.keyboardWidget = keyboardWidget
            self.commentAfterAnsweringLabel = QtGui.QLabel()
            self.commentAfterAnsweringLabel.setWordWrap(True)
            self.nextButton = QtGui.QPushButton()
            self.teachTabWidget = QtGui.QTabWidget()
            self.progressBar = QtGui.QProgressBar()

            self.sideWidget = QtGui.QSplitter(QtCore.Qt.Vertical)

            leftLayout = QtGui.QVBoxLayout()
            leftLayout.addWidget(self.wordLabel)
            leftLayout.addWidget(self.questionLabel)
            leftLayout.addWidget(self.commentLabel)
            leftLayout.addStretch()
            leftLayout.addWidget(self.teachTabWidget)
            leftLayout.addWidget(self.commentAfterAnsweringLabel)
            leftLayout.addWidget(self.nextButton)
            leftLayout.addWidget(self.progressBar)

            leftWidget = QtGui.QWidget()
            leftWidget.setLayout(leftLayout)

            rightLayout = QtGui.QVBoxLayout()
            with contextlib.ignored(AttributeError):
                rightLayout.addWidget(self.keyboardWidget)
            rightLayout.addWidget(self.changeSettingsButton)

            rightWidget = QtGui.QWidget()
            rightWidget.setLayout(rightLayout)

            self.addWidget(self.sideWidget)
            self.addWidget(leftWidget)
            self.addWidget(rightWidget)

            #set stretch factor for widget indexes
            self.setStretchFactor(0, 1)
            self.setStretchFactor(1, 255)
            self.setStretchFactor(2, 1)
Пример #36
0
 def updateList(self, list, dataType):
     self.testsModel.list = list
     self.testsModel.dataType = dataType
     self.notesWidget.updateList(list)
     self.detailsWidget.updateList(list, dataType)
     with contextlib.ignored(AttributeError):
         self.percentNotesViewer.hide()
     try:
         self.percentNotesViewer = self._createPercentNotesViewer(
             list["tests"])
     except (TypeError, KeyError):
         pass
     else:
         self.addWidget(self.percentNotesViewer)
Пример #37
0
    def _retranslate(self):
        global _, ngettext

        #Translations
        try:
            translator = self._modules.default("active", type="translator")
        except IndexError:
            _, ngettext = unicode, lambda a, b, n: a if n == 1 else b
        else:
            _, ngettext = translator.gettextFunctions(
                self._mm.resourcePath("translations"))
        self.name = _("Play hangman")
        with contextlib.ignored(AttributeError):
            self.widget.retranslate()
Пример #38
0
	def _retranslate(self):
		global _, ngettext

		#Translations
		try:
			translator = self._modules.default("active", type="translator")
		except IndexError:
			_, ngettext = unicode, lambda a, b, n: a if n == 1 else b
		else:
			_, ngettext = translator.gettextFunctions(
				self._mm.resourcePath("translations")
			)
		self.name = _("Play hangman")
		with contextlib.ignored(AttributeError):
			self.widget.retranslate()
Пример #39
0
		def retranslate(self):
			with contextlib.ignored(TypeError):
				#TypeError: not yet connected (first pass)
				self.currentIndexChanged.disconnect(self.changeLessonOrder)

			i = self.currentIndex()
			self.clear()

			self.addItem(_("Place - Name"), 0)
			self.addItem(_("Name - Place"), 1)

			if i != -1:
				self.setCurrentIndex(i)

			self.currentIndexChanged.connect(self.changeLessonOrder)
Пример #40
0
	def nextQuestion(self, item):
		"""What happens when the next question should be asked"""

		#set the next question
		self.currentItem = item
		if self.order == Order.Inversed:
			#set the question
			self.teachWidget.questionLabel.setText(_("Please click this place: ") + self.currentItem["name"])
		else:
			#set the arrow to the right position
			self.teachWidget.mapBox.setArrow(self.currentItem["x"],self.currentItem["y"])
		# Set the start of the thinking time to now
		self.startThinkingTime = datetime.datetime.now()
		# Delete the end of the thinking time
		with contextlib.ignored(AttributeError):
			del self.endThinkingTime
Пример #41
0
		def _connectSignals(self):
			self._removeSelectedRowsButton.clicked.connect(
				self.removeSelectedRows
			)
			with contextlib.ignored(AttributeError):
				self._keyboardWidget.letterChosen.handle(self.addLetter)

			self._titleTextBox.textEdited.connect(
				self._wordsTableModel.updateTitle
			)
			self._questionLanguageTextBox.textEdited.connect(
				self._wordsTableModel.updateQuestionLanguage
			)
			self._answerLanguageTextBox.textEdited.connect(
				self._wordsTableModel.updateAnswerLanguage
			)
Пример #42
0
	def nextQuestion(self, item):
		"""What happens when the next question should be asked"""

		# set the next question
		self.currentItem = item
		# set the question field
		self.teachWidget.questionLabel.setText(self.currentItem["question"])
		# set the name field
		self.teachWidget.nameLabel.setText(self.currentItem["name"])
		# set the mediawidget to the right location
		self.teachWidget.mediaDisplay.showMedia(self.currentItem["filename"], self.currentItem["remote"], True)
		# Set the start of the thinking time to now
		self.startThinkingTime = datetime.datetime.now()
		# Delete the end of the thinking time
		with contextlib.ignored(AttributeError):
			del self.endThinkingTime
Пример #43
0
	def _sendNext(self):
		with contextlib.ignored(AttributeError):
			self._previousIndex = self._currentIndex
		try:
			self._currentIndex = self._indexes.pop(0)
		except IndexError:
			#end of lesson
			if len(self._test["results"]) != 0:
				self._test["finished"] = True
				try:
					self.list["tests"]
				except KeyError:
					self.list["tests"] = []
			self.lessonDone.send()
		else:
			item = self.list["items"][self._currentIndex]
			self.newItem.send(self._modifyItem(item))
Пример #44
0
		def setModel(self, *args, **kwargs):
			with contextlib.ignored(AttributeError):
				#AttributeError: first time.
				self.model().modelReset.disconnect(self._modelReset)
				self.model().questionLanguageChanged.disconnect(self._questionLanguageChanged)
				self.model().answerLanguageChanged.disconnect(self._answerLanguageChanged)

			result = super(WordsTableView, self).setModel(*args, **kwargs)

			self.model().modelReset.connect(self._modelReset)
			self.model().questionLanguageChanged.connect(self._questionLanguageChanged)
			self.model().answerLanguageChanged.connect(self._answerLanguageChanged)

			#setting the model is 'resetting' too.
			self._modelReset()

			return result
Пример #45
0
		def _buildUi(self, createChecker, keyboardWidget):
			self._titleLabel = QtGui.QLabel()
			self._titleTextBox = QtGui.QLineEdit(self)
			self._questionLanguageTextBox = QtGui.QLineEdit(self)
			self._questionLanguageLabel = QtGui.QLabel()
			self._answerLanguageTextBox = QtGui.QLineEdit(self)
			self._answerLanguageLabel = QtGui.QLabel()
			self._wordsTableView = WordsTableView(createChecker)

			topLayout = QtGui.QGridLayout()
			topLayout.addWidget(self._titleLabel, 0, 0)
			topLayout.addWidget(self._titleTextBox, 0, 1)

			topLayout.addWidget(self._questionLanguageLabel, 1, 0)
			topLayout.addWidget(self._questionLanguageTextBox, 1, 1)

			topLayout.addWidget(self._answerLanguageLabel, 2, 0)
			topLayout.addWidget(self._answerLanguageTextBox, 2, 1)

			leftLayout = QtGui.QVBoxLayout()
			leftLayout.addLayout(topLayout)
			leftLayout.addWidget(self._wordsTableView)

			leftLayoutWidget = QtGui.QWidget()
			leftLayoutWidget.setLayout(leftLayout)

			if keyboardWidget is not None:
				self._keyboardWidget = keyboardWidget
			self._removeSelectedRowsButton = QtGui.QPushButton(self)
			shortcut = QtGui.QShortcut(QtGui.QKeySequence.Delete, self)
			shortcut.activated.connect(self._removeSelectedRowsButton.animateClick)

			rightLayout = QtGui.QVBoxLayout()
			with contextlib.ignored(AttributeError):
				rightLayout.addWidget(self._keyboardWidget)
			rightLayout.addWidget(self._removeSelectedRowsButton)

			rightLayoutWidget = QtGui.QWidget()
			rightLayoutWidget.setLayout(rightLayout)

			self.addWidget(leftLayoutWidget)
			self.addWidget(rightLayoutWidget)

			self.setStretchFactor(0, 255)
			self.setStretchFactor(1, 1)
Пример #46
0
	def endLesson(self, showResults=True):
		"""Ends the lesson"""

		self.teachWidget.inLesson = False
		
		# Update and go to results widget, only if the test is progressing
		try:
			self.itemList["tests"][-1]
		except IndexError:
			pass
		else:
			if showResults:
				with contextlib.ignored(IndexError):
					# Go to results widget
					module = base._modules.default("active", type="resultsDialog")
					module.showResults(self.itemList, "topo", self.itemList["tests"][-1])
		
		self.teachWidget.lessonDone.emit()
Пример #47
0
	def _retranslate(self):
		#Install translator for this file
		global _
		global ngettext

		try:
			translator = self._modules.default("active", type="translator")
		except IndexError:
			_, ngettext = unicode, lambda a, b, n: a if n == 1 else b
		else:
			_, ngettext = translator.gettextFunctions(
				self._mm.resourcePath("translations")
			)
			
		self._enabled.update({
			"name": _("Enable hidden browser (hide it by moving the slider)"),
		})
		with contextlib.ignored(AttributeError):
			#AttributeError: first time it's not there
			self.browser.retranslate()
Пример #48
0
		def retranslate(self):
			with contextlib.ignored(TypeError):
				#TypeError: not yet connected (first pass)
				self.currentIndexChanged.disconnect(self.changeLessonType)

			#save status
			i = self.currentIndex()

			#update data
			self.clear()
			self._lessonTypeModules = base._modules.sort("active", type="lessonType")
			for lessontype in self._lessonTypeModules:
				self.addItem(lessontype.name, lessontype)

			#restore status
			if i != -1:
				self.setCurrentIndex(i)

			#re-connect signal
			self.currentIndexChanged.connect(self.changeLessonType)
	def _run(self):
		nameToCode = {}
		codeToName = {}
		for localeCode in babel.Locale("en").languages.keys():
			with contextlib.ignored(babel.UnknownLocaleError):
				locale = babel.Locale(localeCode)
				codeToName[localeCode] = locale.display_name
				nameToCode[localeCode] = localeCode
				for code, name in locale.languages.iteritems():
					nameToCode[name.lower()] = code

		#make the test suite pass ;).
		nameToCode["frisian"] = "fy"
		nameToCode["frysk"] = "fy"
		nameToCode["fy"] = "fy"

		codeToName["fy"] = "Frysk"

		data = FILE_TEMPLATE % (repr(nameToCode), repr(codeToName))

		print data.encode("UTF-8")