Пример #1
0
 def BrowseDir(self, title, activetext):
     global basefolder
     if 'basefolder' in globals():
         if os.path.exists(basefolder):
             rd = QFileDialog.getExistingDirectory(self, title, basefolder, QFileDialog.ShowDirsOnly)
         else:
             rd = QFileDialog.getExistingDirectory(self, title, QDir.current().path(), QFileDialog.ShowDirsOnly)
     else:
         rd = QFileDialog.getExistingDirectory(self, title, QDir.current().path(), QFileDialog.ShowDirsOnly)
     if os.path.exists(rd):
         basefolder = os.path.dirname(rd)
         activetext.setText(rd)
         self.parent().statusBar().showMessage('ready')
Пример #2
0
 def BrowseFile(self, title, activetext):
     global basefolder
     if 'basefolder' in globals():
         if os.path.exists(basefolder):
             rf = QFileDialog.getOpenFileName(self, title, basefolder, 'dicom files (*.dcm);; all files (*.*)')
         else:
             rf = QFileDialog.getOpenFileName(self, title, QDir.current().path(), 'dicom files (*.dcm);; all files (*.*)')
     else:
         rf = QFileDialog.getOpenFileName(self, title, QDir.current().path(), 'dicom files (*.dcm);; all files (*.*)')
     rf = rf[0]
     if os.path.isfile(rf):
         basefolder = os.path.dirname(rf)
         activetext.setText(rf)
         self.parent().statusBar().showMessage('ready')
Пример #3
0
 def add_raster_layer(self,
                      layer_name,
                      file_path,
                      upper_left_bound,
                      lower_right_bound,
                      data=None):
     if not self.check_layer_name(layer_name):
         raise LayerAddingException("Incorrect layer name")
     if self.has_layer(layer_name):
         raise LayerAddingException("Layer with this name is already added")
     if data is None and not os.path.exists(file_path):
         raise FileOpeningException("File not found!")
     else:
         bounds = [upper_left_bound, lower_right_bound]
         string_bounds = "[[" + str(bounds[0][0]) + ", " + str(bounds[0][1]) + "], [" +\
                         str(bounds[1][0]) + ", " + str(bounds[1][1]) + "]]"
         if data is None:
             data = image_to_data(file_path)
         file = open("create_layer.js", 'w')
         file.writelines([
             'var createLayerData = "' + data + '";\n1',
             RASTER_LAYER_CREATION_SCRIPT %
             (layer_name, string_bounds, layer_name)
         ])
         file.close()
         path = QDir.current().filePath("create_layer.js")
         local = QUrl.fromLocalFile(path).toString()
         self.window.page().runJavaScript(
             '$("head").append("<script src=\'%s\'></script>");' % local)
         self.layers.append(RasterLayer(layer_name, data, bounds))
 def populate_plugin_menu(self):
     print("populate plugins - to be implemented")
     print(QDir.current())
     print(PLUGINS_SUBFOLDER)
     plugins_dir = (QDir(PLUGINS_SUBFOLDER))
     plugin_files = plugins_dir.entryInfoList(
         QDir.NoDotAndDotDot | QDir.Files, QDir.Name)
     for plugin in plugin_files:
         print(plugin.fileName())
         if plugin.fileName().startswith("pi_"):
             pi_fileName = plugin.fileName()[3:]
             print(pi_fileName)
             # exec("import " + PLUGINS_SUBFOLDER + plugin.baseName() + " as pi")
             # from cvplugins.copymakeborder_plugin import CopyMakeBorder_Plugin
             # self.currentPluginGui = CopyMakeBorder_Plugin()
             # self.currentPluginGui = QWidget()
             pluginAction = QAction(pi_fileName[0:-3], self)
             pluginAction.setProperty(FILE_ON_DISK_BASENAME_PROPERTY,
                                      plugin.baseName())
             # pluginAction.triggered.connect(self.on_PluginActionTriggered)
             slot_string = "pluginAction." + "triggered" + ".connect(" + "self.on_PluginActionTriggered" + ")"
             print(slot_string)
             exec(slot_string)
             self.ui.menu_Plugins.addAction(pluginAction)
         # slot_string = "action." + signal + ".connect(" + slot + ")"
     print("plugin actions:",
           self.ui.menu_Plugins.actions().count(pluginAction))
     if self.ui.menu_Plugins.actions().count(pluginAction) <= 0:
         text_string = f"This application cannot work without plugins!"\
          "\nMake sure that '" + f"{PLUGINS_SUBFOLDER}" + \
          "' folder exists in the\n same folder as the application and that "\
          "there\n are some filter plugins inside it"
         QMessageBox.critical(self, "No Plugins", text_string)
         self.setEnabled(False)
Пример #5
0
 def addImage(self):
     self.image, filter = QFileDialog.getOpenFileName(
         self, 'Open image',
         QDir.current().path(), "Image Files (*.png *.jpg)")
     if self.image != '':
         self.i = ImageDialog(self.image)
         self.i.btn.rejected.connect(self.i.close)
         self.i.btn.accepted.connect(self.putImagePos)
         self.i.show()
Пример #6
0
 def showOpenDialog(self):
     fName, filter = QFileDialog.getOpenFileName(self, 'Open file',
                                                 QDir.current().path())
     if fName != '':
         self.file = fName
         self.workspace.mediaPlayer.setMedia(
             QMediaContent(QUrl.fromLocalFile(fName)))
         self.workspace.playButton.setEnabled(True)
         self.workspace.mediaPlayer.play()
Пример #7
0
    def play_clip_sound(volume=100):
        filename = "sounds/clipsound.wav"
        fullpath = QDir.current().absoluteFilePath(filename)
        url = QUrl.fromLocalFile(fullpath)

        content = QMediaContent(url)
        player = QMediaPlayer()
        player.setMedia(content)
        player.setVolume(volume)
        player.play()
        time.sleep(0.3)
Пример #8
0
 def play_sound(self, name: str):
     """Play a file from the sound directory. Extension is not included, will be added automatically."""
     for file in os.listdir(self.SOUNDS_FOLDER):
         # if the file starts with the provided name and only contains an extension after, try to play it
         if file.startswith(name) and file[len(name):][0] == ".":
             path = QDir.current().absoluteFilePath(self.SOUNDS_FOLDER + file)
             url = QUrl.fromLocalFile(path)
             content = QMediaContent(url)
             self.player.setMedia(content)
             self.player.setVolume(self.volume_slider.value())
             self.player.play()
Пример #9
0
 def _ref_js(self, js_source):
     js_file = "_" + os.path.basename(js_source)
     try:
         if not os.path.exists(js_file):
             urlretrieve(js_source, js_file)
         _script_src = QUrl.fromLocalFile(
             QDir.current().filePath(js_file)).toString()
     except Exception as exc:
         print(('Download %s failed, using CDN: %s' % (js_source, exc)))
         _script_src = js_source
     return """<script src='""" + _script_src + """'></script>"""
Пример #10
0
 def openInternal(self, link):
     url = link.url()
     isLocalHtml = (link.scheme() in ('file', '') and url.endswith('.html'))
     if url.startswith('#'):
         self.scrollToAnchor(url[1:])
     elif link.isRelative():
         fileToOpen = QDir.current().filePath(url)
         if self.tab.openSourceFile(fileToOpen):
             return
     if globalSettings.handleWebLinks and isLocalHtml:
         self.setSource(link)
     else:
         QDesktopServices.openUrl(link)
Пример #11
0
class Example(QMainWindow):
    htmlPath = QDir.current()
    htmlPath.cd("html")
    def __init__(self):
        super().__init__()

        self.setObjectName('Main')
        QMetaObject.connectSlotsByName(self)

        self.view = QWebEngineView()
        self.view.settings().setAttribute(QWebEngineSettings.LocalStorageEnabled, True)
        self.view.setObjectName('MapWidget')

        self.window = QWidget()
        self.window.setObjectName('MainWidget')
        self.layout = QGridLayout(self.window)
        self.layout.addWidget(self.view)
        self.setCentralWidget(self.window)

        self.channel = QWebChannel(self.view.page())
        self.view.page().setWebChannel(self.channel)
        self.channel.registerObject("jshelper", self)

        principal = Figure()
        js = JavascriptLink(QUrl.fromLocalFile(self.htmlPath.absoluteFilePath("qwebchannel.js")).toString())
        principal.header.add_child(Element(js.render()))
        map = folium.Map(location=[36, -108],
                             zoom_start=5, tiles='StamenWatercolor').add_to(principal)
        fastestRoute = folium.PolyLine(((40, -110), (50, -110)),
                                       weight=5, color='blue').add_to(map)

        f = Figure()
        f.html.add_child(Element('<button id="myBtn">Try it</button>'))
        f.html.add_child(Element('<p>\n TEST \n</p>'))

        link = JavascriptLink(QUrl.fromLocalFile(self.htmlPath.absoluteFilePath("popup.js")).toString())
        f.html.add_child(Element(link.render()))

        iframe = branca.element.IFrame(html=f.render(), width=500, height=300)
        popup = folium.Popup(iframe, max_width=500)
        fastestRoute.add_child(popup)

        principal.save(self.htmlPath.absoluteFilePath("test.html"))
        self.view.load(QUrl().fromLocalFile(self.htmlPath.absoluteFilePath("test.html")))
        self.setGeometry(100, 100, 1200, 900)
        self.show()

    @pyqtSlot(str)
    def pathSelected(self, lat):
        print(lat)
Пример #12
0
	def openInternal(self, link):
		url = link.url()
		isLocalHtml = (link.scheme() in ('file', '') and url.endswith('.html'))
		if url.startswith('#'):
			self.scrollToAnchor(url[1:])
		elif link.isRelative() and get_markup_for_file_name(url, return_class=True):
			fileToOpen = QDir.current().filePath(url)
			if not QFileInfo(fileToOpen).completeSuffix() and self._fileName:
				fileToOpen += '.' + QFileInfo(self.tab.fileName).completeSuffix()
			self.tab.p.openFileWrapper(fileToOpen)
		elif globalSettings.handleWebLinks and isLocalHtml:
			self.setSource(link)
		else:
			QDesktopServices.openUrl(link)
Пример #13
0
 def openInternal(self, link):
     url = link.url()
     isLocalHtml = link.scheme() in ("file", "") and url.endswith(".html")
     if url.startswith("#"):
         self.scrollToAnchor(url[1:])
     elif link.isRelative() and get_markup_for_file_name(url, return_class=True):
         fileToOpen = QDir.current().filePath(url)
         if not QFileInfo(fileToOpen).completeSuffix() and self._fileName:
             fileToOpen += "." + QFileInfo(self.tab.fileName).completeSuffix()
         self.tab.p.openFileWrapper(fileToOpen)
     elif globalSettings.handleWebLinks and isLocalHtml:
         self.setSource(link)
     else:
         QDesktopServices.openUrl(link)
Пример #14
0
 def save_result(self):
     """Save analyze result."""
     filename = QFileDialog.getSaveFileName(
         self, 'Save analyze result',
         os.path.join(QDir.current().path(), 'result.csv'), 'File (*.csv)')
     with open(filename[0], 'w', encoding='utf-8') as file:
         row = self.model.rowCount()
         col = self.model.columnCount()
         for i in range(row):
             text = ''
             for j in range(col):
                 text += str(self.model.data(self.model.index(i, j))) + '\t'
             text += '\n'
             file.writelines(text)
Пример #15
0
    def refreshFig(self):
        ''' Updates the graph display with any changes to plotlyFigure '''
        path = QDir.current().filePath('plotly-latest.min.js')
        local = QUrl.fromLocalFile(path).toString()

        raw_html = '<html style="background-color: #31363b;"><head><meta charset="utf-8" />'
        raw_html += '<script src="{}"></script></head>'.format(local)
        raw_html += '<body style="margin: 0; padding: 0;">'
        raw_html += plotly.offline.plot(self.plotlyFigure,
                                        include_plotlyjs=False,
                                        output_type='div')
        raw_html += '</body></html>'

        # update the actual display with setHtml
        self.setHtml(raw_html)
Пример #16
0
    def __init__(self, gui, parent=None):
        super(MapCanvas, self).__init__(parent)

        icon = QIcon(
            QPixmap(
                pkg_resources.resource_filename(
                    'lcmap_tap', '/'.join(('Auxiliary', 'icon.PNG')))))

        self.setWindowIcon(icon)

        self.setWindowTitle('Locator Map')

        self.gui = gui

        self.setMinimumSize(400, 400)

        self.text = QLabel()

        self.text.setTextInteractionFlags(Qt.TextSelectableByMouse)

        self.file = QDir.current().absoluteFilePath(HTML)

        if USE == 'UseWebEngineView':
            self.map_view = QWebEngineView()

            self.backend = Backend(self)

            self.backend.pointChanged.connect(self.onPointChanged)

            self.channel = QWebChannel(self)

            self.channel.registerObject('backend', self.backend)

            self.map_view.page().setWebChannel(self.channel)

        else:
            self.map_view = QWebView()

            self.map_view.page().mainFrame().addToJavaScriptWindowObject(
                "MapCanvas", self)

        self.map_view.load(QUrl.fromLocalFile(self.file))

        self.layout = QVBoxLayout(self)

        self.layout.addWidget(self.map_view)

        self.layout.addWidget(self.text)
Пример #17
0
 def __init__(self, parent=None):
     super().__init__()
     uic.loadUi(QDir.current().absoluteFilePath('music.ui'), self)
     #print(QDir.current().absoluteFilePath('music.ui'))
     self.player = QMediaPlayer()
     self.playlist = QMediaPlaylist()
     self.player.setPlaylist(self.playlist)
     self.playMusicBtn.clicked.connect(self.player.play)
     self.pauseMusicBtn.clicked.connect(self.player.pause)
     self.stopMusicBtn.clicked.connect(self.player.stop)
     self.nextMusicBtn.clicked.connect(self.playlist.next)
     self.previousMusicButton.clicked.connect(self.playlist.previous)
     self.openFilesBtn.clicked.connect(self.openFiles)
     self.openDirectoryBtn.clicked.connect(self.openDir)
     self.playlist.currentMediaChanged.connect(self.updateLabels)
     self.show()
Пример #18
0
 def openInternal(self, link):
     url = link.url()
     if url.startswith('#'):
         self.scrollToAnchor(url[1:])
         return
     elif link.isRelative():
         fileToOpen = QDir.current().filePath(url)
     else:
         fileToOpen = link.toLocalFile() if link.isLocalFile() else None
     if fileToOpen is not None:
         if exists(fileToOpen):
             link = QUrl.fromLocalFile(fileToOpen)
             if globalSettings.handleWebLinks and fileToOpen.endswith(
                     '.html'):
                 self.setSource(link)
                 return
         # This is outside the "if exists" block because we can prompt for
         # creating the file
         if self.tab.openSourceFile(fileToOpen):
             return
     QDesktopServices.openUrl(link)
Пример #19
0
    def makeCollocGraph(self):
        #print "makeCollocGraph"
        if (self.autoSelect or not self.selectedTokeni
                or self.ngra not in self.sectrast.specollocs):
            return

        self.graphicsBoxTitle = self.graphicsBox.title()
        if debug:
            QtWebKit.QWebSettings.globalSettings().setAttribute(
                QtWebKit.QWebSettings.DeveloperExtrasEnabled, True)
        self.webView.setPage(None)  # necessary for repeated recentering
        #self.recenter=RecenterClass()

        #self.webView.settings().setUserStyleSheetUrl(QUrl(":images/images/graphstyle.css"));

        baseUrl = QUrl.fromLocalFile(
            QDir.current().absoluteFilePath("lib/resources/about.html")
        )  # any html file to base the setHtml!!!
        self.webView.setHtml(self.collocations.graph(self.nbBestKids), baseUrl)
        #self.webView.page().mainFrame().addToJavaScriptWindowObject("pyObj", self.recenter)
        #self.webView.page().mainFrame().addToJavaScriptWindowObject("pyObj", self.recenter)  # 2019 to recreate! https://doc.qt.io/qt-5/qtwebenginewidgets-qtwebkitportingguide.html
        #print 3
        self.graphicsBox.setTitle("Collocations")
        self.actionOpen_graph_in_browser.setEnabled(True)
Пример #20
0
 def __on_directory_clicked(self):
     new_directory = QFileDialog.getExistingDirectory(self,
                                                      QCoreApplication.translate('SettingsDialog', 'Open directory'),
                                                      QDir.current().path())
     if new_directory:
         self._directory.setText(new_directory)
Пример #21
0
def main():
    # Initialise.

    defaultContext = "@default"
    fetchedTor = MetaTranslator()
    codecForTr = ''
    codecForSource = ''
    tsFileNames = []
    uiFileNames = []

    verbose = False
    noObsolete = False
    metSomething = False
    numFiles = 0
    standardSyntax = True
    metTsFlag = False
    tr_func = None
    translate_func = None

    # Parse the command line.

    for arg in sys.argv[1:]:
        if arg == "-ts":
            standardSyntax = False

    argc = len(sys.argv)
    i = 1

    while i < argc:
        arg = sys.argv[i]
        i += 1

        if arg == "-help":
            printUsage()
            sys.exit(0)

        if arg == "-version":
            sys.stderr.write("pylupdate5 v%s\n" % PYQT_VERSION_STR)
            sys.exit(0)

        if arg == "-noobsolete":
            noObsolete = True
            continue

        if arg == "-verbose":
            verbose = True
            continue

        if arg == "-ts":
            metTsFlag = True
            continue

        if arg == "-tr-function":
            if i >= argc:
                sys.stderr.write(
                    "pylupdate5 error: missing -tr-function name\n")
                sys.exit(2)

            tr_func = sys.argv[i]
            i += 1
            continue

        if arg == "-translate-function":
            if i >= argc:
                sys.stderr.write(
                    "pylupdate5 error: missing -translate-function name\n")
                sys.exit(2)

            translate_func = sys.argv[i]
            i += 1
            continue

        numFiles += 1

        fullText = ""

        if not metTsFlag:
            f = QFile(arg)

            if not f.open(QIODevice.ReadOnly):
                sys.stderr.write("pylupdate5 error: Cannot open file '%s'\n" %
                                 arg)
                sys.exit(1)

            t = QTextStream(f)
            fullText = t.readAll()
            f.close()

        if standardSyntax:
            oldDir = QDir.currentPath()
            QDir.setCurrent(QFileInfo(arg).path())

            fetchedTor = MetaTranslator()
            codecForTr = ''
            codecForSource = ''
            tsFileNames = []
            uiFileNames = []

            for key, value in proFileTagMap(fullText).items():
                for t in value.split(' '):
                    if key == "SOURCES":
                        fetchtr_py(QDir.current().absoluteFilePath(t),
                                   fetchedTor, defaultContext, True,
                                   codecForSource, tr_func, translate_func)
                        metSomething = True

                    elif key == "TRANSLATIONS":
                        tsFileNames.append(QDir.current().absoluteFilePath(t))
                        metSomething = True

                    elif key in ("CODEC", "DEFAULTCODEC", "CODECFORTR"):
                        codecForTr = t
                        fetchedTor.setCodec(codecForTr)

                    elif key == "CODECFORSRC":
                        codecForSource = t

                    elif key == "FORMS":
                        fetchtr_ui(QDir.current().absoluteFilePath(t),
                                   fetchedTor, defaultContext, True)

            updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete,
                          verbose)

            if not metSomething:
                sys.stderr.write(
                    "pylupdate5 warning: File '%s' does not look like a "
                    "project file\n" % arg)
            elif len(tsFileNames) == 0:
                sys.stderr.write(
                    "pylupdate5 warning: Met no 'TRANSLATIONS' entry in "
                    "project file '%s'\n" % arg)

            QDir.setCurrent(oldDir)
        else:
            if metTsFlag:
                if arg.lower().endswith(".ts"):
                    fi = QFileInfo(arg)

                    if not fi.exists() or fi.isWritable():
                        tsFileNames.append(arg)
                    else:
                        sys.stderr.write(
                            "pylupdate5 warning: For some reason, I "
                            "cannot save '%s'\n" % arg)
                else:
                    sys.stderr.write(
                        "pylupdate5 error: File '%s' lacks .ts extension\n" %
                        arg)
            else:
                fi = QFileInfo(arg)

                if fi.suffix() in ("py", "pyw"):
                    fetchtr_py(fi.absoluteFilePath(), fetchedTor,
                               defaultContext, True, codecForSource, tr_func,
                               translate_func)
                else:
                    fetchtr_ui(fi.absoluteFilePath(), fetchedTor,
                               defaultContext, True)

    if not standardSyntax:
        updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose)

    if numFiles == 0:
        printUsage()
        sys.exit(1)
Пример #22
0
 def open_folder(self):
     """Set target folder."""
     self.folder_path = QFileDialog.getExistingDirectory(
         self, 'Open the folder', QDir.currentPath())
     if not self.folder_path:
         self.folder_path = QDir.current().path()
Пример #23
0
def test():
    path = QDir.current().filePath('plotly-latest.min.js')
    local = QUrl.fromLocalFile(path).toString()
    data_frame = pd.DataFrame(
        np.random.randn(100, 5),
        columns=['Date', 'Lines', 'Orders', 'Eaches', 'SKUs'])

    name = "test"

    trace_lines = go.Bar(x=data_frame['Date'],
                         y=data_frame['Lines'],
                         name='Lines',
                         visible=True)
    trace_orders = go.Bar(x=data_frame['Date'],
                          y=data_frame['Orders'],
                          name='Orders',
                          visible=False)
    trace_eaches = go.Bar(x=data_frame['Date'],
                          y=data_frame['Eaches'],
                          name='Eaches',
                          visible=False)
    trace_SKUs = go.Bar(x=data_frame['Date'],
                        y=data_frame['SKUs'],
                        name='SKUs',
                        visible=False)

    data = [trace_lines, trace_orders, trace_eaches, trace_SKUs]

    lines_title = "%s Lines" % name
    orders_title = "%s Orders" % name
    eaches_title = "%s Eaches" % name
    skus_title = "%s SKUs" % name

    update_menus = list([
        dict(active=0,
             buttons=list([
                 dict(label='Lines',
                      method='update',
                      args=[{
                          'visible': [True, False, False, False]
                      }, {
                          'title': lines_title
                      }]),
                 dict(label='Orders',
                      method='update',
                      args=[{
                          'visible': [False, True, False, False]
                      }, {
                          'title': orders_title
                      }]),
                 dict(label='Eaches',
                      method='update',
                      args=[{
                          'visible': [False, False, True, False]
                      }, {
                          'title': eaches_title
                      }]),
                 dict(label='SKUs',
                      method='update',
                      args=[{
                          'visible': [False, False, False, True]
                      }, {
                          'title': skus_title
                      }])
             ]))
    ])

    layout = dict(
        title=lines_title,
        showlegend=False,
        updatemenus=update_menus,
        xaxis=dict(rangeselector=dict(buttons=list([
            dict(count=1, label='1m', step='month', stepmode='backward'),
            dict(count=6, label='6m', step='month', stepmode='backward'),
            dict(step='all')
        ])),
                   rangeslider=dict(),
                   type='date'))

    fig = dict(data=data, layout=layout)

    raw_html = '<html><head><meta charset="utf-8" /><script src="{}"></script></head>'.format(
        local)
    raw_html += '<body>'
    raw_html += plotly.offline.plot(fig,
                                    include_plotlyjs=False,
                                    output_type='div')
    raw_html += '</body></html>'

    return raw_html
Пример #24
0
import quandl
import pandas as pd
import plotly
import plotly.graph_objects as go

#Mes fichiers
import excelImporter as ex
import dateUtils as date
import dataAnalysis as da

#Config
quandl.ApiConfig.api_key = "YOUR QUANDL API KEY"
Form, qtBaseClass = uic.loadUiType("dialog.ui")
sys.argv.append("--disable-web-security")

path = QDir.current().filePath('plotly-latest.min.js')
local = QUrl.fromLocalFile(path).toString()
targetData = 'Open'


class Ui(QtWidgets.QDialog, Form):
    def displayFigureInBrowser(self, figure):
        raw_html = '<html><head><meta charset="utf-8" />'
        raw_html += '<script src="{}"></script></head>'.format(local)
        raw_html += '<body>'
        raw_html += plotly.offline.plot(figure,
                                        include_plotlyjs=False,
                                        output_type='div')
        raw_html += '</body></html>'
        self.browser.setHtml(raw_html)
        self.browser.show()
Пример #25
0
class rutascenic(QMainWindow):

    htmlPath = QDir.current()
    htmlPath.cd("html")

    def __init__(self):

        super().__init__()
        self.setObjectName('MainWindow')
        QtCore.QMetaObject.connectSlotsByName(self)

        self.home = ""
        self.work = ""
        self.viaRoutes = []  #list of scenic routes added to journey
        self.journey = [
        ]  #list of coordinates from Origin till last via point(end of scenicroutes)
        self.end = []  # tail end of route for loadState

        self.notes = {}  # Annotation Dictionary

        self.true = scenicRouteModel.ScenicRoute_DB()
        self.loadJourney
        atexit.register(self.saveJourney)
        self.initUI()

    def initUI(self):

        # MENUBAR
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('File')

        impMenu = QMenu('Export', self)
        impAct = QAction('Export to .gpx (:TODO)', self)
        impMenu.addAction(impAct)

        newAct = QAction('clear journey', self)
        saveAct = QAction('Save Journey', self)
        loadAct = QAction('Load Journey', self)

        newAct.triggered.connect(self.clearJourney)
        saveAct.triggered.connect(self.saveJourney)
        loadAct.triggered.connect(self.loadJourney)

        fileMenu.addAction(newAct)
        fileMenu.addAction(saveAct)
        fileMenu.addAction(loadAct)
        fileMenu.addMenu(impMenu)

        self.statusBar().showMessage('The Journey is the Destination')

        # QTWIDGETS
        self.og = QLineEdit(self)
        self.og.move(50, 150)
        self.og.setText("San Francisco")

        self.dt = QLineEdit(self)
        self.dt.move(50, 200)
        self.dt.setText("Los Angeles")

        self.goButton = QPushButton('Go', self)
        self.goButton.move(50, 250)
        self.goButton.clicked.connect(self.gcTags)

        self.view = QtWebEngineWidgets.QWebEngineView()
        self.view.settings().setAttribute(
            QWebEngineSettings.LocalStorageEnabled, True)
        self.view.setObjectName('MapWidget')

        self.channel = QtWebChannel.QWebChannel(self.view.page())
        self.view.page().setWebChannel(self.channel)
        self.channel.registerObject("jshelper", self)

        homepage = Figure()
        js = JavascriptLink(
            QUrl.fromLocalFile(
                self.htmlPath.absoluteFilePath("qwebchannel.js")).toString())
        homepage.header.add_child(Element(js.render()))

        ####  RUN THIS CODE TO MODIFY THE STARTUP FILE

        ## create a map showing all scenic routes with their description
        ## and a link to their annotations in a popup

        #     self.us = folium.Map(location=[36,-108], zoom_start=4, tiles='StamenWatercolor')
        #
        #     link = JavascriptLink(QUrl.fromLocalFile(self.htmlPath.absoluteFilePath("popup.js")).toString())
        #     for route in self.true.designatedScenicRoutes.values():

        #
        #         # GET SCENIC ROUTES W/ CENTER IN BOUNDS OF fastestRoute
        #         # ll = route['ll']
        #         # #print(float(ll[0]))
        #         # #print(float(ll[1]))
        #
        #             # explore = FlickrRoute.ImageByLatLong(ll[1], ll[0])
        #         paths = route['path']
        #         # rtcolor = int('B22222', base=16) ...Hex()
        #         # explore = FlickrRoute.ImageByLatLong(ll[1], ll[0])
        #         for path in paths:
        #             decodedPath = polyline.decode(path.strip('"'))
        #             desgScenicRoute = folium.PolyLine(decodedPath, weight=3,color='yellow').add_to(self.us)
        #
        #             f = Figure()
        #
        #             f.html.add_child(Element('<div id="startLat">'))
        #             # f.html.add_child(Element(str(decodedPath[0][0])))
        #             f.html.add_child(Element('</div>'))
        #             f.html.add_child(Element('<div id="startLong">'))
        #             # f.html.add_child(Element(str(decodedPath[0][1])))
        #             f.html.add_child(Element('</div>'))
        #             f.html.add_child(Element('<div id="endLat">'))
        #             # f.html.add_child(Element(str(decodedPath[len(decodedPath)-1][0])))
        #             f.html.add_child(Element('</div>'))
        #             f.html.add_child(Element('<div id="endLong">'))
        #             # f.html.add_child(Element(str(decodedPath[len(decodedPath)-1][1])))
        #             f.html.add_child(Element('</div>'))
        #             f.html.add_child(Element('<code id="encodedPath">'))
        #             f.html.add_child(Element('</code>'))
        #             f.html.add_child(Element('<div id="name">'))
        #             f.html.add_child(Element(route['name']))
        #             f.html.add_child(Element('</div>'))
        #             # f.html.add_child(Element('<iframe id = "stv" width="285" height="220" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/streetview?key=AIzaSyDiHmblGevCJUXCkuSmeOR2l9wNErlRTw4&location='))#46.414382,10.013988"></iframe>'))
        #             # f.html.add_child(Element(str(ll[1]).strip()))
        #             # f.html.add_child(Element(','))
        #             # f.html.add_child(Element(str(ll[0]).strip()))
        #             # f.html.add_child(Element('&fov=100"></iframe>'))
        #             f.html.add_child(Element('<button id="MyBtn" hidden="1">Journal Entry</button>'))
        #             f.html.add_child(Element(link.render()))
        #
        #             iframe = branca.element.IFrame(html=f.render(), width=150, height=50)
        #             popup = folium.Popup(iframe, max_width=300)
        #
        #             desgScenicRoute.add_child(popup)
        #
        #
        #     self.us.add_to(homepage)
        #     homepage.save(self.htmlPath.absoluteFilePath("full.html"))

        self.view.load(QtCore.QUrl().fromLocalFile(
            os.path.split(os.path.abspath(__file__))[0] + '/html/full.html'))

        self.labelbox = QWidget()
        self.labelbox.setObjectName('Checkpoints')

        self.startpoint = QLabel(self.labelbox)
        self.endpoint = QLabel(self.labelbox)
        self.checkpoint_01 = QLabel(self.labelbox)
        self.checkpoint_01.setText('Take the scenic route')

        self.notepad = QLineEdit(self)
        self.notepad.setText('Welcome to ruta senika')
        self.notepad.editingFinished.connect(self.mischiefManaged)

        # // LAYOUT

        self.window = QWidget()
        self.window.setObjectName('MainWidget')
        QtCore.QMetaObject.connectSlotsByName(self.window)

        self.layout = QGridLayout()
        self.window.setLayout(self.layout)

        self.layout.addWidget(self.startpoint)
        self.layout.addWidget(self.checkpoint_01)
        self.layout.addWidget(self.notepad)
        self.layout.addWidget(self.endpoint)

        self.layout.addWidget(self.view)

        self.layout.addWidget(self.og)
        self.layout.addWidget(self.dt)
        self.layout.addWidget(self.goButton)

        # Set QWidget as the central layout of the main window
        self.setCentralWidget(self.window)

        self.setGeometry(0, 0, 640, 750)
        self.setWindowTitle('Submenu')

        self.show()

# GEOCODER

    def gcTags(self):
        # try:
        g = geocoder.osm(self.og.text())
        dg = geocoder.osm(self.dt.text())

        self.startpoint.setText(self.og.text())
        self.startpoint.adjustSize()
        self.endpoint.setText(self.dt.text())
        self.endpoint.adjustSize()

        self.home = g
        self.work = dg

        self.searchQuickestRoute(str(self.home.latlng[0]),
                                 str(self.home.latlng[1]), str(dg.latlng[0]),
                                 str(dg.latlng[1]))

    # except: # PRINTS DEFAULT SCREEN WHEN LINEEDIT BUGS
    #     self.view.load(QtCore.QUrl().fromLocalFile(
    #         os.path.split(os.path.abspath(__file__))[0]+'/html/full.html'
    #     ))

    def addPathToRoute(self, startLat, startLong, endLat, endLong):

        request = "https://graphhopper.com/api/1/route?"

        # point=51.131%2C12.414&point=48.224%2C3.867

        request += "point="
        request += str(startLat)
        request += "%2C"
        request += str(startLong)
        request += "&point="
        request += str(endLat).strip()
        request += "%2C"
        request += str(endLong).strip()

        request += "&vehicle=car&elevation=false&points_encoded=false&locale=en&key=2bbc7dfa-dc4e-4150-82e9-b75cb8fa088c"

        jsonRespDict = requests.get(request).json()

        for c in jsonRespDict['paths']:

            self.coords = (c['points'])

        self.coords = self.coords['coordinates']

        swap = [tuple(reversed(x)) for x in self.coords]

        return swap

    def addScPathToRoute(self, startLat, startLong, endLat, endLong, name,
                         encodedPath):

        if (len(self.viaRoutes) == 0):

            self.addScRtetoPathFromList(self.home.latlng[0],
                                        self.home.latlng[1],
                                        str(self.work.latlng[0]).strip(),
                                        str(self.work.latlng[1]).strip(),
                                        startLat, startLong, endLat, endLong,
                                        encodedPath)
        else:

            self.addScRtetoPathFromList(
                self.viaRoutes[len(self.viaRoutes) - 1][-1][0],
                self.viaRoutes[len(self.viaRoutes) - 1][-1][1],
                str(self.work.latlng[0]).strip(),
                str(self.work.latlng[1]).strip(), startLat, startLong, endLat,
                endLong, encodedPath)

# GRAPH-HOPPER MATRIX API

    def addScRtetoPathFromList(self, startLat, startLong, endLat, endLong,
                               scRt_startLat, scRt_startLong, scRt_endLat,
                               scRt_endLong, encodedPath):

        #curl "https://graphhopper.com/api/1/matrix?point=49.932707%2C11.588051&point=50.241935%2C10.747375&point=50.118817%2C11.983337&type=json&vehicle=car&debug=true&out_array=weights&out_array=times&out_array=distances&key=[YOUR_KEY]"

        request = "https://graphhopper.com/api/1/matrix?"

        request += "from_point="
        request += str(startLat)
        request += "%2C"
        request += str(startLong)

        request += "&from_point="
        request += str(endLat)
        request += "%2C"
        request += str(endLong)

        request += "&to_point="
        request += str(scRt_startLat)
        request += "%2C"
        request += str(scRt_startLong)

        request += "&to_point="
        request += str(scRt_endLat)
        request += "%2C"
        request += str(scRt_endLong)

        request += "&type=json&vehicle=car&out_array=weights&key=2bbc7dfa-dc4e-4150-82e9-b75cb8fa088c"

        jsonRespDict = requests.get(request).json()

        matrix = []
        for c in jsonRespDict['weights']:
            for weight in c:
                matrix.append(weight)

        scRt = polyline.decode(encodedPath.replace('\\\\', '\\'))

        if (matrix[0] + matrix[3]) > (matrix[1] + matrix[2]):
            scRt.reverse()

        self.viaRoutes.append(scRt)
        self.appendScenicRoute(scRt)

    def appendScenicRoute(self, scRt):

        if len(self.viaRoutes) > 1:
            before = self.addPathToRoute(
                self.journey[len(self.journey) - 1][0],
                self.journey[len(self.journey) - 1][1], scRt[0][0], scRt[0][1])
        else:
            before = self.addPathToRoute(str(self.home.latlng[0]),
                                         str(self.home.latlng[1]), scRt[0][0],
                                         scRt[0][1])
        after = self.addPathToRoute(scRt[len(scRt) - 1][0],
                                    scRt[len(scRt) - 1][1],
                                    str(self.work.latlng[0]).strip(),
                                    str(self.work.latlng[1]).strip())
        userpath = []

        for points in before:

            self.journey.append(points)

        for points in scRt:

            self.journey.append(points)

            self.end = []
        for points in after:
            userpath.append(points)
            self.end.append(points)

        self.showPathAndNearbyRoutes(self.journey + userpath)

    def searchQuickestRoute(self, olat, olong, dlat, dlong):

        # """
        # Routing API Requests
        #     from online resource
        # """

        request = "https://graphhopper.com/api/1/route?"

        # point=51.131%2C12.414&point=48.224%2C3.867
        request += "point="  #%2C12.414
        request += olat
        request += "%2C"
        request += olong
        request += "&point="
        request += dlat
        request += "%2C"
        request += dlong

        request += "&vehicle=car&elevation=false&points_encoded=false&locale=en&key=2bbc7dfa-dc4e-4150-82e9-b75cb8fa088c"

        self.statusBar().showMessage('The end of meaningless travel')

        jsonRespDict = requests.get(request).json()

        for c in jsonRespDict['paths']:
            self.bbox = (c['bbox'])
            self.coords = (c['points'])

        self.coords = self.coords['coordinates']

        swap = [tuple(reversed(x)) for x in self.coords]
        self.journey.append([self.home.latlng[0], self.home.latlng[1]])
        self.showPathAndNearbyRoutes(swap)

    def showPathAndNearbyRoutes(self, coordinate_list):
        # HEADER FOR EVERY MAP
        principal = Figure()
        js = JavascriptLink(
            QUrl.fromLocalFile(
                self.htmlPath.absoluteFilePath("qwebchannel.js")).toString())
        principal.header.add_child(Element(js.render()))

        midpoint = len(coordinate_list) / 2

        try:
            self.uk = folium.Map(  #max_bounds=False,
                location=coordinate_list[midpoint],
                zoom_start=5,
                # min_lat=self.bbox[1],
                # max_lat=self.bbox[3],
                # min_lon=self.bbox[2],
                # max_lon=self.bbox[0],
                # max_bounds=True,
                tiles='StamenTerrain')
        except:
            self.uk = folium.Map(  #max_bounds=False,
                # location=[37,-109],
                zoom_start=5,
                min_lat=self.bbox[1],
                max_lat=self.bbox[3],
                min_lon=self.bbox[2],
                max_lon=self.bbox[0],
                # max_bounds=True,
                tiles='StamenTerrain')

        self.uk.add_to(principal)

        fastestRoute = folium.PolyLine(coordinate_list,
                                       weight=4,
                                       color='#0095DD').add_to(self.uk)

        link = JavascriptLink(
            QUrl.fromLocalFile(
                self.htmlPath.absoluteFilePath("popup.js")).toString())
        self.statusBar().showMessage('Getting nearby scenic routes')
        for route in self.true.designatedScenicRoutes.values():

            # GET SCENIC ROUTES W/ CENTER IN BOUNDS OF fastestRoute
            ll = route['ll']

            if ((float(ll[0]) > float(self.bbox[0]))
                    and (float(ll[0]) < float(self.bbox[2]))
                    and (float(ll[1]) > float(self.bbox[1]))
                    and (float(ll[1]) < float(self.bbox[3]))):

                paths = route['path']

                for path in paths:
                    decodedPath = polyline.decode(path.strip('"'))
                    scenicRoute = folium.PolyLine(decodedPath,
                                                  weight=3,
                                                  color='yellow').add_to(
                                                      self.uk)

                    f = Figure()
                    # f.html.add_child(Element())
                    f.html.add_child(Element('<div id="startLat">'))
                    f.html.add_child(Element(str(decodedPath[0][0])))
                    f.html.add_child(Element('</div>'))
                    f.html.add_child(Element('<div id="startLong">'))
                    f.html.add_child(Element(str(decodedPath[0][1])))
                    f.html.add_child(Element('</div>'))
                    f.html.add_child(Element('<div id="endLat">'))
                    f.html.add_child(
                        Element(str(decodedPath[len(decodedPath) - 1][0])))
                    f.html.add_child(Element('</div>'))
                    f.html.add_child(Element('<div id="endLong">'))
                    f.html.add_child(
                        Element(str(decodedPath[len(decodedPath) - 1][1])))
                    f.html.add_child(Element('</div>'))
                    f.html.add_child(Element('<code id="encodedPath">'))

                    try:
                        f.html.add_child(Element(path))
                    except:
                        lat = float(ll[1])
                        lon = float(ll[0])
                        sp = []
                        sp.append(lat)
                        sp.append(lon)
                        sillypoint = str(polyline.encode(tuple(sp)))

                        f.html.add_child(Element(sillypoint))

                    f.html.add_child(Element('</code>'))
                    f.html.add_child(Element('<div id="name">'))
                    f.html.add_child(Element(route['name']))
                    f.html.add_child(Element('</div>'))
                    f.html.add_child(
                        Element(
                            '<iframe id = "stv" width="285" height="220" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/streetview?key=AIzaSyDiHmblGevCJUXCkuSmeOR2l9wNErlRTw4&location='
                        ))  #46.414382,10.013988"></iframe>'))
                    f.html.add_child(Element(str(ll[1]).strip()))
                    f.html.add_child(Element(','))
                    f.html.add_child(Element(str(ll[0]).strip()))
                    f.html.add_child(Element('&fov=100"></iframe>'))

                    f.html.add_child(
                        Element('<button id="MyBtn">Add to Journey</button>'))

                    f.html.add_child(Element(link.render()))

                    iframe = branca.element.IFrame(html=f.render(),
                                                   width=300,
                                                   height=300)
                    popup = folium.Popup(iframe, max_width=300)

                    scenicRoute.add_child(popup)

        principal.save(self.htmlPath.absoluteFilePath("test.html"))
        self.view.load(QUrl().fromLocalFile(
            self.htmlPath.absoluteFilePath("test.html")))
        self.statusBar().showMessage('The Means are the End')

        self.update()
        self.show()


## ANNOTATION SAVE ON FOCUSOUT EVENT

    def mischiefManaged(self):

        name = self.checkpoint_01.text()
        self.notes[name] = self.notepad.text()

    @pyqtSlot(str)
    def pathClicked(self, pathname):

        self.checkpoint_01.setText(pathname.strip())
        self.checkpoint_01.adjustSize()

        note = self.notes.get(
            pathname.strip(),
            "Annotate this route. Add tags like #coastal, #mountains, #forests, #etc & rate the route 1*, 2*...10*"
        )

        self.notepad.setText(note)

    @pyqtSlot(str, str, str, str, str, str)
    def pathSelected(self, startLat, startLong, endLat, endLong, name,
                     pathEncoded):
        self.statusBar().showMessage('Loading your route')
        startLat = startLat.replace("\n", "")
        startLong = startLong.replace("\n", "")
        endLat = endLat.replace("\n", "")
        endLong = endLong.replace("\n", "")
        startLat = startLat.strip()
        startLong = startLong.strip()
        endLat = endLat.strip()
        endLong = endLong.strip()

        name = name.strip()

        path = pathEncoded
        path = path.strip()
        path = path.strip('"')

        self.addScPathToRoute(startLat, startLong, endLat, endLong, name, path)

        self.checkpoint_01.adjustSize()

    def clearJourney(self):
        self.journey = []

    def saveJourney(self):

        with open("routetags.text", "w+") as mdFile:
            [
                mdFile.write('{0},{1}\n'.format(key, value))
                for key, value in self.notes.items()
            ]

        with open("journeytest.txt", "wb") as fp:
            pickle.dump(self.journey + self.end, fp)

    def loadJourney(self):

        with open("journeytest.txt", "rb") as fp:
            self.journey = pickle.load(fp)
            self.showPathAndNearbyRoutes(self.journey)

        with open("routetags.text", "r+") as mdFile:
            for line in mdFile:
                (key, value) = line.split(',')
                self.notes[key] = value
Пример #26
0
    def on_wordTableWidget_currentItemChanged(self, item, previous):
        #print "000",item, previous
        if not item: item = previous
        try:
            self.selectedWord = str(
                self.wordTableWidget.item(item.row(), 0).text())
            try:
                self.selectedTokeni = self.base.d.token2id[
                    self.
                    selectedWord]  # TODO: clean this mess up! .encode("utf-8")
            except:
                self.selectedTokeni = self.base.d.token2id[self.selectedWord]
        except Exception as e:
            print("oh, something wrong", Exception, e)
            self.selectedTokeni = 0
        #print 8888

        self.sectionMap.clearSelection()
        red = QtGui.QColor("red")
        green = QtGui.QColor("green")
        whitebrush = QtGui.QBrush(QtCore.Qt.white, QtCore.Qt.NoBrush)
        self.smin, self.smax, self.fmax = 0, 0, 0
        #		print self.currwordsectspecdic
        for i, section in enumerate(self.sectrast.sections):
            #s=self.currwordsectspecdic[(i, )]
            # print i,section,sorted(self.sectrast.specificity[self.selectedTokeni])
            # try:
            s = self.sectrast.specificity[self.selectedTokeni][(
                section, )]  # TODO: check why error on windows!
            # except:s=0
            if s > 0:
                #self.sectionMap.item(i).setBackgroundColor(red.darker(30*s))
                self.sectionMap.item(i).setBackground(
                    QtGui.QBrush(QtGui.QColor(QtCore.Qt.red).darker(30 * s)))
            elif s < 0:
                self.sectionMap.item(i).setBackground(
                    QtGui.QBrush(
                        QtGui.QColor(QtCore.Qt.green).darker(30 * -s)))
            else:
                self.sectionMap.item(i).setBackground(whitebrush)
            freq = self.sectrast.bows[section].get(self.selectedTokeni, 0)
            if freq:
                self.sectionMap.item(i).setForeground(
                    QtGui.QBrush(QtCore.Qt.magenta))
            else:
                self.sectionMap.item(i).setForeground(
                    QtGui.QBrush(QtCore.Qt.black))
            if s > self.smax: self.smax = s
            elif s < self.smin: self.smin = s

            if freq > self.fmax: self.fmax = freq

        self.updateInfo()
        #if self.currwordsectspecdic:
        #print ";.isChecked()",self.graphButton.isChecked()
        #print self.autoSelect,"jjj"
        if self.actionCollocations.isChecked(): self.colloc(self.selectedWord)
        #print self.autoSelect,"uuu"
        if self.autoSelect:
            #sleep(.5)
            #print self.recenter.word
            #if self.recenter.word==self.selectedWord:
            if self.autoSelect and self.graphButton.isChecked():
                #print "sleep",self.recenter.word

                #self.autoSelect=0
                #sleep(.5)
                baseUrl = QUrl.fromLocalFile(
                    QDir.current().absoluteFilePath("lib/resources/about.html")
                )  # any html file to base the setHtml!!!
                self.webView.setHtml(self.collocations.graph(self.nbBestKids),
                                     baseUrl)
                #self.makeCollocGraph()
                #sleep(.5)
                self.webView.page().mainFrame().addToJavaScriptWindowObject(
                    "pyObj", self.recenter)
                #self.autoSelect=1
                #print 111,self.recenter.word
            return

        if self.graphButton.isChecked(): self.makeCollocGraph()
        else: self.makeSpecGraph()
        #print "www"
        self.actionSelect_sections_with_occurrences.setEnabled(True)
        self.actionSelectposspecificsections.setEnabled(True)
        self.actionSelectnegspecificsections.setEnabled(True)
Пример #27
0
        self.page += 1

    def updateLabel(self):
        self.label1.setText("你已经{}次把时光机停在了正确的位置".format(self.cnt))
        self.label2.setText("你还有{}次暂停时光机的机会哦".format(self.total_times - self.hit_times))


if __name__ == "__main__":
    app = QApplication([])
    app.setStyle('Fusion')

    # music load and player initialization
    playlist = QMediaPlaylist()
    filenames = ['background.mp3']
    for filename in filenames:
        fullpath = QDir.current().absoluteFilePath(filename)
        url = QUrl.fromLocalFile(fullpath)
        playlist.addMedia(QMediaContent(url))
    playlist.setPlaybackMode(QMediaPlaylist.Loop)
    player = QMediaPlayer()
    player.setPlaylist(playlist)
    # player.play()

    # events load and initilization
    event_list = []
    with open('./major_events.txt',encoding='utf-8') as event_file:
        lines=event_file.readlines()
        for line in lines:
            line=line.strip()
            event=line.split('#')
            event_list.append(Event(event[0],event[1]))
Пример #28
0
def main():
    # Initialise.

    defaultContext = "@default"
    fetchedTor = MetaTranslator()
    codecForTr = ''
    codecForSource = ''
    tsFileNames = []
    uiFileNames = []

    verbose = False
    noObsolete = False
    metSomething = False
    numFiles = 0
    standardSyntax = True
    metTsFlag = False
    tr_func = None
    translate_func = None

    # Parse the command line.

    for arg in sys.argv[1:]:
        if arg == "-ts":
            standardSyntax = False

    argc = len(sys.argv)
    i = 1

    while i < argc:
        arg = sys.argv[i]
        i += 1

        if arg == "-help":
            printUsage()
            sys.exit(0)

        if arg == "-version":
            sys.stderr.write("pylupdate5 v%s\n" % PYQT_VERSION_STR)
            sys.exit(0)

        if arg == "-noobsolete":
            noObsolete = True
            continue

        if arg == "-verbose":
            verbose = True
            continue

        if arg == "-ts":
            metTsFlag = True
            continue

        if arg == "-tr-function":
            if i >= argc:
                sys.stderr.write(
                        "pylupdate5 error: missing -tr-function name\n")
                sys.exit(2)

            tr_func = sys.argv[i]
            i += 1
            continue

        if arg == "-translate-function":
            if i >= argc:
                sys.stderr.write(
                        "pylupdate5 error: missing -translate-function name\n")
                sys.exit(2)

            translate_func = sys.argv[i]
            i += 1
            continue

        numFiles += 1

        fullText = ""

        if not metTsFlag:
            f = QFile(arg)

            if not f.open(QIODevice.ReadOnly):
                sys.stderr.write(
                        "pylupdate5 error: Cannot open file '%s'\n" % arg)
                sys.exit(1)

            t = QTextStream(f)
            fullText = t.readAll()
            f.close()

        if standardSyntax:
            oldDir = QDir.currentPath()
            QDir.setCurrent(QFileInfo(arg).path())

            fetchedTor = MetaTranslator()
            codecForTr = ''
            codecForSource = ''
            tsFileNames = []
            uiFileNames = []

            for key, value in proFileTagMap(fullText).items():
                for t in value.split(' '):
                    if key == "SOURCES":
                        fetchtr_py(QDir.current().absoluteFilePath(t),
                                fetchedTor, defaultContext, True,
                                codecForSource, tr_func, translate_func)
                        metSomething = True

                    elif key == "TRANSLATIONS":
                        tsFileNames.append(QDir.current().absoluteFilePath(t))
                        metSomething = True

                    elif key in ("CODEC", "DEFAULTCODEC", "CODECFORTR"):
                        codecForTr = t
                        fetchedTor.setCodec(codecForTr)

                    elif key == "CODECFORSRC":
                        codecForSource = t

                    elif key == "FORMS":
                        fetchtr_ui(QDir.current().absoluteFilePath(t),
                                fetchedTor, defaultContext, True)

            updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete,
                    verbose)

            if not metSomething:
                sys.stderr.write(
                        "pylupdate5 warning: File '%s' does not look like a "
                        "project file\n" % arg)
            elif len(tsFileNames) == 0:
                sys.stderr.write(
                        "pylupdate5 warning: Met no 'TRANSLATIONS' entry in "
                        "project file '%s'\n" % arg)

            QDir.setCurrent(oldDir)
        else:
            if metTsFlag:
                if arg.lower().endswith(".ts"):
                    fi = QFileInfo(arg)

                    if not fi.exists() or fi.isWritable():
                        tsFileNames.append(arg)
                    else:
                        sys.stderr.write(
                                "pylupdate5 warning: For some reason, I "
                                "cannot save '%s'\n" % arg)
                else:
                    sys.stderr.write(
                            "pylupdate5 error: File '%s' lacks .ts extension\n" % arg)
            else:
                fi = QFileInfo(arg)

                if fi.suffix() in ("py", "pyw"):
                    fetchtr_py(fi.absoluteFilePath(), fetchedTor,
                            defaultContext, True, codecForSource, tr_func,
                            translate_func)
                else:
                    fetchtr_ui(fi.absoluteFilePath(), fetchedTor,
                            defaultContext, True)

    if not standardSyntax:
        updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose)

    if numFiles == 0:
        printUsage()
        sys.exit(1)
Пример #29
0
 def __on_directory_triggered(self):
     directory = QFileDialog.getExistingDirectory(self,
                                                  QCoreApplication.translate('NewWalletDialog', 'Choose directory'),
                                                  QDir.current().path())
     if directory:
         self._edit_directory.setText(directory)
Пример #30
0
    def __init__(self):
        super(MainWindow, self).__init__()

        self.folder_path = QDir.current().path()
        self.init_ui()