Exemple #1
0
    def __init__(self, action, myorca):
        self.action = action
        self.myorca = myorca
        self.config = self.myorca.config

        def cleanUp(*args):
            if hasattr(__main__, "_KSpreadOrca"):
                getattr(__main__, "_KSpreadOrca").finalized()

        self.action.connect("started(Kross::Action*)", cleanUp)
        self.action.connect("finalized(Kross::Action*)", cleanUp)

        self._view = KSpread.view()
        self._setSheet(KSpread.currentSheet())

        def selectionChanged():
            print "Selection changed"
            s = KSpread.currentSheet()
            if s:
                if s.sheetName() != self.sheetName:
                    self._setSheet(s)
                    if self.config.sheetNameOnSheetChanged:
                        self.speakSheetName()
                else:
                    if self.config.cellNameOnSelectionChanged:
                        self.speakCellName()
                    if self.config.cellValueOnSelectionChanged:
                        self.speakCellValue()

        self._view.connect("selectionChanged()", selectionChanged)
Exemple #2
0
    def __init__(self, action, myorca):
        self.action = action
        self.myorca = myorca
        self.config = self.myorca.config

        def cleanUp(*args):
            if hasattr(__main__, "_KSpreadOrca"):
                getattr(__main__, "_KSpreadOrca").finalized()

        self.action.connect("started(Kross::Action*)", cleanUp)
        self.action.connect("finalized(Kross::Action*)", cleanUp)

        self._view = KSpread.view()
        self._setSheet(KSpread.currentSheet())

        def selectionChanged():
            print "Selection changed"
            s = KSpread.currentSheet()
            if s:
                if s.sheetName() != self.sheetName:
                    self._setSheet(s)
                    if self.config.sheetNameOnSheetChanged:
                        self.speakSheetName()
                else:
                    if self.config.cellNameOnSelectionChanged:
                        self.speakCellName()
                    if self.config.cellValueOnSelectionChanged:
                        self.speakCellValue()

        self._view.connect("selectionChanged()", selectionChanged)
Exemple #3
0
 def startLogging(self, sheetname, cellrange = ""):
     self.sheet = KSpread.sheetByName(sheetname)
     self.listener = KSpread.createListener(sheetname, cellrange)
     if not self.listener:
         raise "Failed to create listener for sheetname '%s' and range '%s'" % (sheetname,cellrange)
     self.addLog( "Start logging sheet='%s' range='%s'" % (sheetname,cellrange) )
     self.listener.connect("regionChanged(QVariantList)", self.regionChanged)
     self.listener.connect("cellChanged(int,int)", self.cellChanged)
Exemple #4
0
 def startLogging(self, sheetname, cellrange=""):
     self.sheet = KSpread.sheetByName(sheetname)
     self.listener = KSpread.createListener(sheetname, cellrange)
     if not self.listener:
         raise Exception, T.i18n(
             "Failed to create listener for sheetname '%1' and range '%2'",
             [sheetname], [cellrange])
     self.addLog("Start logging sheet='%s' range='%s'" %
                 (sheetname, cellrange))
     self.listener.connect("regionChanged(QVariantList)",
                           self.regionChanged)
     self.listener.connect("cellChanged(int,int)", self.cellChanged)
Exemple #5
0
    def _setSheet(self, sheet):
        self.sheet = sheet
        self.sheetName = self.sheet.sheetName()

        self._listener = KSpread.createListener(self.sheetName, self.config.sheetRange)
        if not self._listener:
            raise Exception, T.i18n("Failed to create listener")

        def cellChanged(column, row):
            text = self.sheet.text(column, row)
            if text:
                # if self.myorca.isSpeaking():
                #    self.myorca.stop()
                self.myorca.speak(text)

        self._listener.connect("cellChanged(int,int)", cellChanged)

        def sheetNameChanged(*args):
            self.myorca.speak(T.i18n("Sheet name changed"))

        self.sheet.connect("nameChanged()", sheetNameChanged)

        def sheetShowChanged(*args):
            self.myorca.speak(T.i18n("Show sheet %1", [self.sheetName]))

        self.sheet.connect("showChanged()", sheetShowChanged)

        def sheetHideChanged(*args):
            self.myorca.speak(T.i18n("Hide sheet %1"), [self.sheetName])

        self.sheet.connect("hideChanged()", sheetHideChanged)
Exemple #6
0
    def showExportDialog(self, reader):
        dialog = self.forms.createDialog(T.i18n("Kexi Export"))
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List")  #Auto Plain List Tree Tabbed

        savepage = dialog.addPage(T.i18nc("Options page name", "Save"),
                                  T.i18n("Export to Kexi Project File"),
                                  "document-save")
        savewidget = self.forms.createFileWidget(
            savepage, "kfiledialog:///kspreadkexidbexport")
        savewidget.setMode("Saving")
        savewidget.setFilter("*.kexi *.kexis *kexic|%(1)s\n*|%(2)s" % {
            '1': T.i18n("Kexi Project Files"),
            '2': T.i18n("All Files")
        })

        datapage = dialog.addPage(T.i18nc("Options page name", "Export"),
                                  T.i18n("Export sheets and ranges"),
                                  "document-export")
        sheetslistview = KSpread.createSheetsListView(datapage)
        sheetslistview.setSelectionType("MultiSelect")
        sheetslistview.setEditorType("Range")

        if dialog.exec_loop():
            projectfile = savewidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise Exception, T.i18n("File '%1' not found.", [projectfile])
            reader.setSheets(sheetslistview.sheets())
            connection = self.createConnection(projectfile)
            return connection
        return None
Exemple #7
0
    def importVCardFile(self, vcardfilename, currentSheet):
        self.componentDict = {}
        self.componentList = []
        
        writer = KSpread.writer()
        if not writer.setSheet(currentSheet):
            raise Exception, T.i18n("Invalid sheet \"%1\" defined.", [currentSheet])

        writer.next() #hack
        writer.next() #hack

        f = open(vcardfilename, 'r')
        lines = []
        for line in f:
            if not line.strip() == "":
                lines.append( line )
                continue
            if len(lines) > 0:
                self.importVCardLines(writer, lines)
                lines = []
        if len(lines) > 0:
            self.importVCardLines(writer, lines)

        if writer.setSheet(currentSheet):
            writer.next() #hack
            writer.setValues(self.componentList)
    def showImportDialog(self, writer):
        dialog = self.forms.createDialog(T.i18n("Kexi Import"))
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List") #Auto Plain List Tree Tabbed

        openpage = dialog.addPage(T.i18n("Open"),T.i18n("Import from Kexi Project File"),"document-open")
        openwidget = self.forms.createFileWidget(openpage, "kfiledialog:///kspreadkexidbimportopen")
        openwidget.setMode("Opening")
        openwidget.setFilter("*.kexi *.kexis *kexic|%(1)s\n*|%(2)s" % { '1' : T.i18n("Kexi Project Files"), '2' : T.i18n("All Files") } )

        datapage = dialog.addPage(T.i18n("Import"),T.i18n("Import to sheet beginning at cell"),"document-import")
        sheetslistview = KSpread.createSheetsListView(datapage)
        sheetslistview.setEditorType("Cell")

        if dialog.exec_loop():
            projectfile = openwidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise Exception, T.i18n("File '%1' not found.", [projectfile])

            currentSheet = sheetslistview.sheet()
            if not currentSheet:
                raise Exception, T.i18n("No current sheet.")
            if not writer.setSheet(currentSheet):
                raise Exception, T.i18n("Invalid sheet \"%1\" defined." [currentSheet])

            cell = sheetslistview.editor()
            if not writer.setCell(cell):
                raise Exception, T.i18n("Invalid cell \"%1\" defined.", [cell])

            connection = self.createConnection(projectfile)
            return connection
        return None
Exemple #9
0
    def doImport(self):
        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise "No current sheet."

        writer = KSpread.writer()
        if not writer.setSheet(currentSheet):
            raise "Invalid sheet \"%s\" defined." % currentSheet

        cell = self.sheetslistview.editor()
        if not writer.setCell(cell):
            raise "Invalid cell \"%s\" defined." % cell

        csvfilename = self.openwidget.selectedFile()
        if not os.path.isfile(csvfilename):
            raise "File '%s' not found." % csvfilename

        #writer.connect("valueChanged()",writer.next)

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename,'r')
        try:
            csvreader = csv.reader(csvfile, dialect="custom")
            try:
                while True:
                    record = csvreader.next()
                    if not writer.setValues(record):
                        print "Failed to set all of '%s' to cell '%s'" % (record,writer.cell())
                    #writer.insertValues(record)
                    writer.next()
            except StopIteration:
                pass
        finally:
            csvfile.close()
Exemple #10
0
    def doExport(self):
        reader = KSpread.reader()
        reader.setSheets( self.sheetslistview.sheets() )

        #if len(reader.sheetNames()) == 0:
            #raise "No sheet to export selected"

        csvfilename = self.savewidget.selectedFile()
        if not csvfilename:
            raise Exception, T.i18n("No CSV file chosen")
        if os.path.splitext(csvfilename)[1] == '':
            csvfilename += '.csv'

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename,'w')
        csvwriter = csv.writer(csvfile, dialect="custom")

        def changedSheet(sheetname):
            print "changedSheet sheetname=%s" % sheetname
            #csvfile.write("# %s\n" % sheetname)

        def changedRow(row):
            values = reader.currentValues()
            #print "changedRow row=%i values=%s" % (row,values)
            csvwriter.writerow(values)

        reader.connect("changedSheet(QString)",changedSheet)
        reader.connect("changedRow(int)",changedRow)
        reader.start()
        csvfile.close()
    def showDataSelectionDialog(self, writer, KPlato ):
        tabledialog = self.forms.createDialog("Property List")
        tabledialog.setButtons("Ok|Cancel")
        tabledialog.setFaceType("List") #Auto Plain List Tree Tabbed
        
        datapage = tabledialog.addPage(i18n("Destination"),i18n("Import to sheet beginning at cell"))
        sheetslistview = KSpread.createSheetsListView(datapage)
        sheetslistview.setEditorType("Cell")

        schedulepage = tabledialog.addPage(i18n("Schedules"),i18n("Select schedule"))
        schedulewidget = KPlato.createScheduleListView(schedulepage)

        sourcepage = tabledialog.addPage(i18n("Data"),i18n("Select data"))
        sourcewidget = KPlato.createDataQueryView(sourcepage)
        if tabledialog.exec_loop():
            currentSheet = sheetslistview.sheet()
            if not currentSheet:
                raise Exception, i18n("No current sheet.")
            if not writer.setSheet(currentSheet):
                raise Exception, i18n("Invalid sheet '%1' defined.", [currentSheet])

            cell = sheetslistview.editor()
            if not writer.setCell(cell):
                raise Exception, i18n("Invalid cell '%1' defined.", [cell])

            schedule = schedulewidget.currentSchedule()
            #print "schedule: ", schedule
            props = sourcewidget.selectedProperties()
            #print "props: ", props
            ot = sourcewidget.objectType()
            #print "objectType: ", ot
            return [ot, schedule, props, sourcewidget.includeHeaders() ]
        return None
    def showDataSelectionDialog(self, writer, Plan ):
        tabledialog = self.forms.createDialog("Property List")
        tabledialog.setButtons("Ok|Cancel")
        tabledialog.setFaceType("List") #Auto Plain List Tree Tabbed
        
        datapage = tabledialog.addPage(T.i18n("Destination"),T.i18n("Import to sheet beginning at cell"))
        sheetslistview = KSpread.createSheetsListView(datapage)
        sheetslistview.setEditorType("Cell")

        schedulepage = tabledialog.addPage(T.i18n("Schedules"),T.i18n("Select schedule"))
        schedulewidget = Plan.createScheduleListView(schedulepage)

        sourcepage = tabledialog.addPage(T.i18n("Data"),T.i18n("Select data"))
        sourcewidget = Plan.createDataQueryView(sourcepage)
        if tabledialog.exec_loop():
            currentSheet = sheetslistview.sheet()
            if not currentSheet:
                raise Exception, T.i18n("No current sheet.")
            if not writer.setSheet(currentSheet):
                raise Exception, T.i18n("Invalid sheet '%1' defined.", [currentSheet])

            cell = sheetslistview.editor()
            if not writer.setCell(cell):
                raise Exception, T.i18n("Invalid cell '%1' defined.", [cell])

            schedule = schedulewidget.currentSchedule()
            #print "schedule: ", schedule
            props = sourcewidget.selectedProperties()
            #print "props: ", props
            ot = sourcewidget.objectType()
            #print "objectType: ", ot
            return [ot, schedule, props, sourcewidget.includeHeaders() ]
        return None
Exemple #13
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        self.currentpath = self.scriptaction.currentPath()

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog(T.i18n("CSV Import"))
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("List")  # Auto Plain List Tree Tabbed

        openpage = self.dialog.addPage(T.i18n("Open"), T.i18n("Import from CSV File"), "document-open")
        self.openwidget = self.forms.createFileWidget(openpage, "kfiledialog:///kspreadcsvimportopen")
        self.openwidget.setMode("Opening")
        self.openwidget.setFilter(
            "*.csv *.txt|%(1)s\n*|%(2)s" % {"1": T.i18n("Comma-Separated-Value Files"), "2": T.i18n("All Files")}
        )

        datapage = self.dialog.addPage(T.i18n("Import"), T.i18n("Import to sheet beginning at cell"), "document-import")
        self.sheetslistview = KSpread.createSheetsListView(datapage)
        self.sheetslistview.setEditorType("Cell")

        optionspage = self.dialog.addPage(T.i18n("Options"), T.i18n("Comma Separated Value Options"), "configure")
        self.optionswidget = self.forms.createWidgetFromUIFile(
            optionspage, os.path.join(self.currentpath, "csvoptions.ui")
        )

        if self.dialog.exec_loop():
            try:
                self.doImport()
            except:
                self.forms.showMessageBox(
                    "Error",
                    T.i18n("Error"),
                    "%s" % "".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])),
                )
Exemple #14
0
    def doImport(self):
        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise Exception, T.i18n("No current sheet.")

        writer = KSpread.writer()
        if not writer.setSheet(currentSheet):
            self.forms.showMessageBox("Sorry", T.i18n('Invalid sheet "%1" defined.', [currentSheet]))

        cell = self.sheetslistview.editor()
        if not writer.setCell(cell):
            self.forms.showMessageBox("Sorry", T.i18n('Invalid cell "%1" defined.', [cell]))

        csvfilename = self.openwidget.selectedFile()
        if not os.path.isfile(csvfilename):
            self.forms.showMessageBox("Sorry", T.i18n("File '%1' not found.", [csvfilename]))

        # writer.connect("valueChanged()",writer.next)

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename, "r")
        try:
            csvreader = csv.reader(csvfile, dialect="custom")
            try:
                while True:
                    record = csvreader.next()
                    if not writer.setValues(record):
                        print "Failed to set all of '%s' to cell '%s'" % (record, writer.cell())
                    # writer.insertValues(record)
                    writer.next()
            except StopIteration:
                pass
        finally:
            csvfile.close()
Exemple #15
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        #self.undostack = KSpread.undoStack()
        #self.undostack.connect("indexChanged(int)",self.indexChanged)

        #file = os.path(self.getLogDir(),"KSpread.log")

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog("Logger")
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("Plain") #Auto Plain List Tree Tabbed

        savepage = self.dialog.addPage("Save","Save to Log File","document-save")
        self.savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///kspreadlogger")
        self.savewidget.setMode("Saving")
        self.savewidget.setFilter("*.txt *.log|Log File\n*|All Files")

        if self.dialog.exec_loop():
            filename = self.savewidget.selectedFile()
            if os.path.isfile(filename):
                if self.forms.showMessageBox("WarningContinueCancel", "Overwrite file?", "The file \"%s\" does already exist. Overwrite the file?" % filename) != "Continue":
                    raise "Aborted."
            sheetname = KSpread.currentSheet().sheetName()
            cellrange = "A1:F50" #FIXME
            try:
                self.file = open(filename, "w")
                self.startLogging(sheetname, cellrange)
            except IOError, (errno, strerror):
                raise "Failed to write Log File \"%s\":\n%s" % (filename,strerror)
Exemple #16
0
    def __init__(self, action, config):
        self.action = action
        self.config = config

        forms = Kross.module("forms")
        dialog = forms.createDialog(T.i18n("Import vCard"))
        #dialog.minimumWidth = 400
        #dialog.minimumHeight = 300
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List") #Auto Plain List Tree Tabbed
        
        filepage = dialog.addPage(T.i18n("Open"), T.i18n("vCard File"), "document-open")
        #deffile = "/home/kde4/vcardtest/addressbook.vcf" #"kfiledialog:///kspreadvcardimport"
        deffile = "kfiledialog:///kspreadvcardimport"
        self.openwidget = forms.createFileWidget(filepage, deffile)
        self.openwidget.setMode("Opening")
        self.openwidget.setFilter("*.vcf|%(1)s\n*|%(2)s" % { '1' : T.i18n("vCard Files"), '2' : T.i18n("All Files") } )
        
        datapage = dialog.addPage(T.i18n("Import"),T.i18n("Import to sheet beginning at cell"),"document-import")
        self.sheetslistview = KSpread.createSheetsListView(datapage)
        self.sheetslistview.setEditorType("Cell")

        if not dialog.exec_loop():
            return

        vcardfilename = self.openwidget.selectedFile()
        if not os.path.isfile(vcardfilename):
            raise Exception, T.i18n("File '%1' not found.", [vcardfilename])

        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise Exception, T.i18n("No current sheet.")

        self.importVCardFile(vcardfilename, currentSheet)
Exemple #17
0
    def importVCardFile(self, vcardfilename, currentSheet):
        self.componentDict = {}
        self.componentList = []

        writer = KSpread.writer()
        if not writer.setSheet(currentSheet):
            raise Exception, T.i18n("Invalid sheet \"%1\" defined.",
                                    [currentSheet])

        writer.next()  #hack
        writer.next()  #hack

        f = open(vcardfilename, 'r')
        lines = []
        for line in f:
            if not line.strip() == "":
                lines.append(line)
                continue
            if len(lines) > 0:
                self.importVCardLines(writer, lines)
                lines = []
        if len(lines) > 0:
            self.importVCardLines(writer, lines)

        if writer.setSheet(currentSheet):
            writer.next()  #hack
            writer.setValues(self.componentList)
Exemple #18
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        self.currentpath = self.scriptaction.currentPath()

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog(T.i18n("CSV Export"))
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("List") #Auto Plain List Tree Tabbed

        savepage = self.dialog.addPage(T.i18nc("Options page name", "Save"),T.i18n("Export to CSV File"),"document-save")
        self.savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///kspreadcsvexportsave")
        self.savewidget.setMode("Saving")
        self.savewidget.setFilter("*.csv *.txt|%(1)s\n*|%(2)s" % { '1' : T.i18n("Comma-Separated-Value Files"), '2' : T.i18n("All Files") } )

        datapage = self.dialog.addPage(T.i18nc("Options page name", "Export"),T.i18n("Export Sheets and ranges"),"document-export")
        self.sheetslistview = KSpread.createSheetsListView(datapage)
        self.sheetslistview.setSelectionType("MultiSelect")
        self.sheetslistview.setEditorType("Range")

        optionspage = self.dialog.addPage(T.i18n("Options"),T.i18n("Comma Separated Value Options"),"configure")
        self.optionswidget = self.forms.createWidgetFromUIFile(optionspage, os.path.join(self.currentpath, "csvoptions.ui"))

        if self.dialog.exec_loop():
            try:
                self.doExport()
            except:
                self.forms.showMessageBox("Error", T.i18n("Error"), "%s" % "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) ))
Exemple #19
0
    def _setSheet(self, sheet):
        self.sheet = sheet
        self.sheetName = self.sheet.sheetName()

        self._listener = KSpread.createListener(self.sheetName,
                                                self.config.sheetRange)
        if not self._listener:
            raise Exception, T.i18n("Failed to create listener")

        def cellChanged(column, row):
            text = self.sheet.text(column, row)
            if text:
                #if self.myorca.isSpeaking():
                #    self.myorca.stop()
                self.myorca.speak(text)

        self._listener.connect("cellChanged(int,int)", cellChanged)

        def sheetNameChanged(*args):
            self.myorca.speak(T.i18n("Sheet name changed"))

        self.sheet.connect("nameChanged()", sheetNameChanged)

        def sheetShowChanged(*args):
            self.myorca.speak(T.i18n("Show sheet %1", [self.sheetName]))

        self.sheet.connect("showChanged()", sheetShowChanged)

        def sheetHideChanged(*args):
            self.myorca.speak(T.i18n("Hide sheet %1"), [self.sheetName])

        self.sheet.connect("hideChanged()", sheetHideChanged)
Exemple #20
0
 def selectionChanged():
     print "Selection changed"
     s = KSpread.currentSheet()
     if s:
         if s.sheetName() != self.sheetName:
             self._setSheet(s)
             if self.config.sheetNameOnSheetChanged:
                 self.speakSheetName()
         else:
             if self.config.cellNameOnSelectionChanged:
                 self.speakCellName()
             if self.config.cellValueOnSelectionChanged:
                 self.speakCellValue()
Exemple #21
0
 def selectionChanged():
     print "Selection changed"
     s = KSpread.currentSheet()
     if s:
         if s.sheetName() != self.sheetName:
             self._setSheet(s)
             if self.config.sheetNameOnSheetChanged:
                 self.speakSheetName()
         else:
             if self.config.cellNameOnSelectionChanged:
                 self.speakCellName()
             if self.config.cellValueOnSelectionChanged:
                 self.speakCellValue()
Exemple #22
0
        def update(argument):
            print "Yweather.update !"
            location = argument[0]  #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KSpread.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(
                    location):
                func.error = T.i18n("Invalid location")
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = T.i18n("Web services request failed")
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(
                    namespace, 'condition')[0]
            except IndexError:
                func.error = T.i18n("Invalid condition")
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperature: %s" % temp
            func.result = temp
Exemple #23
0
        def update(argument):
            print "Yweather.update !"
            location = argument[0] #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KSpread.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(location):
                func.error = "Invalid location"
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = "Web services request failed"
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(namespace, 'condition')[0]
            except IndexError:
                func.error = "Invalid condition"
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperatur: %s" % temp
            func.result = temp
Exemple #24
0
    def start(self):
        writer = KSpread.writer()
        filename = self.showImportDialog(writer)
        if not filename:
            return  # no exception, user prob pressed cancel

        Plan = Kross.module("Plan")
        if Plan is None:
            raise Exception, T.i18n("Failed to start Plan. Is Plan installed?")

        Plan.openUrl(filename)
        proj = Plan.project()
        data = self.showDataSelectionDialog(writer, Plan)
        if len(data) == 0:
            raise Exception, T.i18n("No data to import")

        objectType = data[0]
        schedule = data[1]
        props = data[2]
        if len(props) == 0:
            raise Exception, T.i18n("No properties to import")

        record = []
        if data[3] == True:
            for prop in props:
                record.append(proj.headerData(objectType, prop))
            if not writer.setValues(record):
                if self.forms.showMessageBox(
                        "WarningContinueCancel", T.i18n("Warning"),
                        T.i18n(
                            "Failed to set all properties of '%1' to cell '%2'",
                            [", ".join(record),
                             writer.cell()])) == "Cancel":
                    return
            writer.next()

        if objectType == 0:  # Nodes
            self.importValues(writer, proj, proj, props, schedule)
        if objectType == 1:  # Resources
            for i in range(proj.resourceGroupCount()):
                self.importValues(writer, proj, proj.resourceGroupAt(i), props,
                                  schedule)
        if objectType == 2:  # Accounts
            for i in range(proj.accountCount()):
                self.importValues(writer, proj, proj.accountAt(i), props,
                                  schedule)
Exemple #25
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        #self.undostack = KSpread.undoStack()
        #self.undostack.connect("indexChanged(int)",self.indexChanged)

        #file = os.path(self.getLogDir(),"KSpread.log")

        self.forms = Kross.module("forms")
        self.dialog = self.forms.createDialog(T.i18n("Logger"))
        self.dialog.setButtons("Ok|Cancel")
        self.dialog.setFaceType("Plain")  #Auto Plain List Tree Tabbed

        savepage = self.dialog.addPage(T.i18nc("Options page name", "Save"),
                                       T.i18n("Save to Log File"),
                                       "document-save")
        self.savewidget = self.forms.createFileWidget(
            savepage, "kfiledialog:///kspreadlogger")
        self.savewidget.setMode("Saving")
        self.savewidget.setFilter("*.txt *.log|%(1)s\n*|%(2)s" % {
            '1': T.i18n("Log File"),
            '2': T.i18n("All Files")
        })

        if self.dialog.exec_loop():
            filename = self.savewidget.selectedFile()
            if os.path.isfile(filename):
                if self.forms.showMessageBox(
                        "WarningContinueCancel", T.i18n("Overwrite file?"),
                        T.i18n(
                            "The file \"%1\" does already exist. Overwrite the file?",
                            [filename])) != "Continue":
                    raise Exception, T.i18n("Aborted.")
            sheetname = KSpread.currentSheet().sheetName()
            cellrange = "A1:F50"  #FIXME
            try:
                self.file = open(filename, "w")
                self.startLogging(sheetname, cellrange)
            except IOError, (errno, strerror):
                raise Exception, T.i18n("Failed to write Log File \"%1\":\n%2",
                                        [filename], [strerror])
    def start(self):
        reader = KSpread.reader()

        connection = self.showExportDialog(reader)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()

            tableschema = self.showTableDialog(connection)
            if not tableschema:
                return

            fieldlist = tableschema.fieldlist()

            print "tableschema.name() = %s" % tableschema.name()
            print "tableschema.caption() = %s" % tableschema.caption()
            print "tableschema.description() = %s" % tableschema.description()
            print "fieldlist.names() = %s" % fieldlist.names()

            def changedSheet(sheetname):
                print "changedSheet sheetname=%s" % sheetname

            def changedRow(row):
                values = reader.currentValues()
                #values = [ "%s" % v for v in reader.currentValues() ]

                print "changedRow row=%i values=%s" % (row,values)
                if connection.insertRecord(fieldlist, values):
                    pass
                else:
                    print "=> insert failed: %s" % connection.lastError()

            reader.connect("changedSheet(QString)",changedSheet)
            reader.connect("changedRow(int)",changedRow)
            reader.start()

        finally:
            connection.disconnect()
Exemple #27
0
    def start(self):
        reader = KSpread.reader()

        connection = self.showExportDialog(reader)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()

            tableschema = self.showTableDialog(connection)
            if not tableschema:
                return

            fieldlist = tableschema.fieldlist()

            print "tableschema.name() = %s" % tableschema.name()
            print "tableschema.caption() = %s" % tableschema.caption()
            print "tableschema.description() = %s" % tableschema.description()
            print "fieldlist.names() = %s" % fieldlist.names()

            def changedSheet(sheetname):
                print "changedSheet sheetname=%s" % sheetname

            def changedRow(row):
                values = reader.currentValues()
                #values = [ "%s" % v for v in reader.currentValues() ]

                print "changedRow row=%i values=%s" % (row, values)
                if connection.insertRecord(fieldlist, values):
                    pass
                else:
                    print "=> insert failed: %s" % connection.lastError()

            reader.connect("changedSheet(QString)", changedSheet)
            reader.connect("changedRow(int)", changedRow)
            reader.start()

        finally:
            connection.disconnect()
Exemple #28
0
    def showImportDialog(self, writer):
        dialog = self.forms.createDialog(T.i18n("Kexi Import"))
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List")  #Auto Plain List Tree Tabbed

        openpage = dialog.addPage(T.i18n("Open"),
                                  T.i18n("Import from Kexi Project File"),
                                  "document-open")
        openwidget = self.forms.createFileWidget(
            openpage, "kfiledialog:///kspreadkexidbimportopen")
        openwidget.setMode("Opening")
        openwidget.setFilter("*.kexi *.kexis *kexic|%(1)s\n*|%(2)s" % {
            '1': T.i18n("Kexi Project Files"),
            '2': T.i18n("All Files")
        })

        datapage = dialog.addPage(T.i18n("Import"),
                                  T.i18n("Import to sheet beginning at cell"),
                                  "document-import")
        sheetslistview = KSpread.createSheetsListView(datapage)
        sheetslistview.setEditorType("Cell")

        if dialog.exec_loop():
            projectfile = openwidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise Exception, T.i18n("File '%1' not found.", [projectfile])

            currentSheet = sheetslistview.sheet()
            if not currentSheet:
                raise Exception, T.i18n("No current sheet.")
            if not writer.setSheet(currentSheet):
                raise Exception, T.i18n(
                    "Invalid sheet \"%1\" defined."[currentSheet])

            cell = sheetslistview.editor()
            if not writer.setCell(cell):
                raise Exception, T.i18n("Invalid cell \"%1\" defined.", [cell])

            connection = self.createConnection(projectfile)
            return connection
        return None
Exemple #29
0
    def doImport(self):
        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise Exception, T.i18n("No current sheet.")

        writer = KSpread.writer()
        if not writer.setSheet(currentSheet):
            self.forms.showMessageBox(
                "Sorry", T.i18n("Invalid sheet \"%1\" defined.",
                                [currentSheet]))

        cell = self.sheetslistview.editor()
        if not writer.setCell(cell):
            self.forms.showMessageBox(
                "Sorry", T.i18n("Invalid cell \"%1\" defined.", [cell]))

        csvfilename = self.openwidget.selectedFile()
        if not os.path.isfile(csvfilename):
            self.forms.showMessageBox(
                "Sorry", T.i18n("File '%1' not found.", [csvfilename]))

        #writer.connect("valueChanged()",writer.next)

        csv.register_dialect("custom", self.getCustomDialect())

        csvfile = open(csvfilename, 'r')
        try:
            csvreader = csv.reader(csvfile, dialect="custom")
            try:
                while True:
                    record = csvreader.next()
                    if not writer.setValues(record):
                        print "Failed to set all of '%s' to cell '%s'" % (
                            record, writer.cell())
                    #writer.insertValues(record)
                    writer.next()
            except StopIteration:
                pass
        finally:
            csvfile.close()
Exemple #30
0
    def __init__(self, action, config):
        self.action = action
        self.config = config

        forms = Kross.module("forms")
        dialog = forms.createDialog(T.i18n("Import vCard"))
        #dialog.minimumWidth = 400
        #dialog.minimumHeight = 300
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List")  #Auto Plain List Tree Tabbed

        filepage = dialog.addPage(T.i18n("Open"), T.i18n("vCard File"),
                                  "document-open")
        #deffile = "/home/kde4/vcardtest/addressbook.vcf" #"kfiledialog:///kspreadvcardimport"
        deffile = "kfiledialog:///kspreadvcardimport"
        self.openwidget = forms.createFileWidget(filepage, deffile)
        self.openwidget.setMode("Opening")
        self.openwidget.setFilter("*.vcf|%(1)s\n*|%(2)s" % {
            '1': T.i18n("vCard Files"),
            '2': T.i18n("All Files")
        })

        datapage = dialog.addPage(T.i18n("Import"),
                                  T.i18n("Import to sheet beginning at cell"),
                                  "document-import")
        self.sheetslistview = KSpread.createSheetsListView(datapage)
        self.sheetslistview.setEditorType("Cell")

        if not dialog.exec_loop():
            return

        vcardfilename = self.openwidget.selectedFile()
        if not os.path.isfile(vcardfilename):
            raise Exception, T.i18n("File '%1' not found.", [vcardfilename])

        currentSheet = self.sheetslistview.sheet()
        if not currentSheet:
            raise Exception, T.i18n("No current sheet.")

        self.importVCardFile(vcardfilename, currentSheet)
Exemple #31
0
    def start(self):
        writer = KSpread.writer()

        connection = self.showImportDialog(writer)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()
            print "queryNames = %s" % connection.queryNames()

            queryschema = self.showTableDialog(connection)
            if not queryschema:
                return

            print "queryschema.name() = %s" % queryschema.name()
            print "queryschema.caption() = %s" % queryschema.caption()
            print "queryschema.description() = %s" % queryschema.description()

            cursor = connection.executeQuerySchema(queryschema)
            if not cursor:
                raise Exception, T.i18n("Failed to create cursor.")
            if not cursor.moveFirst():
                raise Exception, T.i18n(
                    "The cursor has no records to read from.")

            while not cursor.eof():
                record = []
                for i in range(cursor.fieldCount()):
                    record.append(cursor.value(i))
                if writer.setValues(record):
                    writer.next()
                else:
                    print "Failed to set all of '%s' to cell '%s'" % (
                        record, writer.cell())
                cursor.moveNext()
        finally:
            connection.disconnect()
    def start(self):
        writer = KSpread.writer()
        filename = self.showImportDialog(writer)
        if not filename:
            return # no exception, user prob pressed cancel

        KPlato = Kross.module("KPlato")
        if KPlato is None:
            raise Exception, i18n("Failed to start KPlato. Is KPlato installed?")

        KPlato.document().openUrl( filename )
        proj = KPlato.project()
        data = self.showDataSelectionDialog( writer, KPlato )
        if len(data) == 0:
            raise Exception, i18n("No data to import")

        objectType = data[0]
        schedule = data[1]
        props = data[2]
        if len(props) == 0:
            raise Exception, i18n("No properties to import")

        record = []
        if data[3] == True:
            for prop in props:
                record.append( KPlato.headerData( objectType, prop ) )
            if not writer.setValues(record):
                if self.forms.showMessageBox("WarningContinueCancel", i18n("Warning"), i18n("Failed to set all properties of '%1' to cell '%2'", [", ".join(record), writer.cell()])) == "Cancel":
                    return
            writer.next()

        if objectType == 0: # Nodes
            self.importValues( writer, KPlato, proj, props, schedule )
        if objectType == 1: # Resources
            for i in range( proj.resourceGroupCount() ):
                self.importValues( writer, KPlato, proj.resourceGroupAt( i ), props, schedule )
        if objectType == 2: # Accounts
            for i in range( proj.accountCount() ):
                self.importValues( writer, KPlato, proj.accountAt( i ), props, schedule )
    def showExportDialog(self, reader):
        dialog = self.forms.createDialog(T.i18n("Kexi Export"))
        dialog.setButtons("Ok|Cancel")
        dialog.setFaceType("List") #Auto Plain List Tree Tabbed

        savepage = dialog.addPage(T.i18nc("Options page name", "Save"), T.i18n("Export to Kexi Project File"),"document-save")
        savewidget = self.forms.createFileWidget(savepage, "kfiledialog:///kspreadkexidbexport")
        savewidget.setMode("Saving")
        savewidget.setFilter("*.kexi *.kexis *kexic|%(1)s\n*|%(2)s" % { '1' : T.i18n("Kexi Project Files"), '2' : T.i18n("All Files") } )

        datapage = dialog.addPage(T.i18nc("Options page name", "Export"), T.i18n("Export sheets and ranges"),"document-export")
        sheetslistview = KSpread.createSheetsListView(datapage)
        sheetslistview.setSelectionType("MultiSelect")
        sheetslistview.setEditorType("Range")

        if dialog.exec_loop():
            projectfile = savewidget.selectedFile()
            if not os.path.isfile(projectfile):
                raise Exception, T.i18n("File '%1' not found.", [projectfile])
            reader.setSheets( sheetslistview.sheets() )
            connection = self.createConnection(projectfile)
            return connection
        return None
    def start(self):
        writer = KSpread.writer()

        connection = self.showImportDialog(writer)
        if not connection:
            return

        try:
            print "databaseNames = %s" % connection.databaseNames()
            print "tableNames = %s" % connection.tableNames()
            print "queryNames = %s" % connection.queryNames()

            queryschema = self.showTableDialog(connection)
            if not queryschema:
                return

            print "queryschema.name() = %s" % queryschema.name()
            print "queryschema.caption() = %s" % queryschema.caption()
            print "queryschema.description() = %s" % queryschema.description()

            cursor = connection.executeQuerySchema(queryschema)
            if not cursor:
                raise Exception, T.i18n("Failed to create cursor.")
            if not cursor.moveFirst():
                raise Exception, T.i18n("The cursor has no records to read from.")

            while not cursor.eof():
                record = []
                for i in range( cursor.fieldCount() ):
                    record.append( cursor.value(i) )
                if writer.setValues(record):
                    writer.next()
                else:
                    print "Failed to set all of '%s' to cell '%s'" % (record,writer.cell())
                cursor.moveNext()
        finally:
            connection.disconnect()
Exemple #35
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KSpread.function("YFINANCE")
        func.minparam = 3
        func.maxparam = 3
        func.comment = (T.i18n(
            "The YFINANCE() function uses the Yahoo! Finance Web Service to display stock values of a defined ticker symbol."
        ))
        func.syntax = T.i18n("YFINANCE(string,string,string)")
        func.addParameter("String", T.i18n("The ticker symbol."))
        func.addParameter("String", T.i18n("The date."))
        func.addParameter(
            "String",
            T.i18n(
                "The type: Date, Open, High, Low, Close, Volume or AdjClose."))
        func.addExample(T.i18n("YFINANCE(\"YHOO\";\"20060119\";\"Open\")"))
        func.addExample(T.i18n("YFINANCE(\"=C14\";\"=C15\";\"=C16\")"))

        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0]  #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KSpread.currentSheet().text(ticker[1:])

            todate = argument[1]  #e.g. "20060119"
            if todate.startswith('='):
                todate = KSpread.currentSheet().text(todate[1:])
            fromdate = todate

            typename = argument[2]  #e.g. "Open"
            if typename.startswith('='):
                typename = KSpread.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = T.i18n("Invalid symbol")
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = T.i18n("Invalid date")
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = T.i18n("Invalid type")
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = T.i18n("Web services request failed")
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0, len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = T.i18n("No stock")
                return
            if len(resultlist) < 7:
                func.error = T.i18n("Invalid stock")
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v, resultlist)
            func.result = v

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Exemple #36
0
 def speakCellValue(self):
     sheet = KSpread.currentSheet()
     (x1, y1, x2, y2) = KSpread.view().selection()
     t = sheet.text(x1, y1)
     self.myorca.speak(t)
Exemple #37
0
#!/usr/bin/env kross

import re, Kross, KSpread

T = Kross.module("kdetranslation")

func = KSpread.function("PYREGEXP")
func.minparam = 3
func.maxparam = 3
func.comment = T.i18n(
    "The PYREGEXP() function replaces substring in the input string with a given string using regular expression."
)
func.syntax = T.i18n("PYREGEXP(string)")
func.addParameter("String", T.i18n("The input string."))
func.addParameter("String", T.i18n("The regular expression."))
func.addParameter("String", T.i18n("Replace with."))
func.addExample(T.i18n("PYREGEXP(\"Some String\",\"(S|m)\",\"A\")"))


def update(args):
    s = args[0]
    regexp = args[1]
    repl = args[2]
    try:
        p = re.compile(regexp)
        func.result = p.sub(repl, s)
    except:
        func.error = T.i18n("Invalid regexp")


func.connect("called(QVariantList)", update)
Exemple #38
0
        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0]  #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KSpread.currentSheet().text(ticker[1:])

            todate = argument[1]  #e.g. "20060119"
            if todate.startswith('='):
                todate = KSpread.currentSheet().text(todate[1:])
            fromdate = todate

            typename = argument[2]  #e.g. "Open"
            if typename.startswith('='):
                typename = KSpread.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = T.i18n("Invalid symbol")
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = T.i18n("Invalid date")
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = T.i18n("Invalid type")
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = T.i18n("Web services request failed")
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0, len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = T.i18n("No stock")
                return
            if len(resultlist) < 7:
                func.error = T.i18n("Invalid stock")
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v, resultlist)
            func.result = v
Exemple #39
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KSpread.function("YWEATHER")
        func.minparam = 1
        func.maxparam = 2
        func.comment = (
            "The YWEATHER() function uses the Yahoo! Weather Web Service "
            "to display the weather of a location. "
        )
        func.syntax = "YWEATHER(string;string)"
        func.addParameter("String", "The US zip code, Location ID or cell that contains them.")
        func.addParameter("String", "Units for temperature. f=Fahrenheit and c=Celsius")
        func.addExample("YWEATHER(\"=A1\")")
        func.addExample("YWEATHER(\"GMXX0151\";\"c\")")

        def update(argument):
            print "Yweather.update !"
            location = argument[0] #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KSpread.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(location):
                func.error = "Invalid location"
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = "Web services request failed"
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(namespace, 'condition')[0]
            except IndexError:
                func.error = "Invalid condition"
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperatur: %s" % temp
            func.result = temp

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Exemple #40
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KSpread.function("YFINANCE")
        func.minparam = 3
        func.maxparam = 3
        func.comment = (
            T.i18n("The YFINANCE() function uses the Yahoo! Finance Web Service to display stock values of a defined ticker symbol.")
        )
        func.syntax = T.i18n("YFINANCE(string,string,string)")
        func.addParameter("String", T.i18n("The ticker symbol."))
        func.addParameter("String", T.i18n("The date."))
        func.addParameter("String", T.i18n("The type: Date, Open, High, Low, Close, Volume or AdjClose."))
        func.addExample(T.i18n("YFINANCE(\"YHOO\";\"20060119\";\"Open\")"))
        func.addExample(T.i18n("YFINANCE(\"=C14\";\"=C15\";\"=C16\")"))

        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0] #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KSpread.currentSheet().text(ticker[1:])

            todate = argument[1] #e.g. "20060119"
            if todate.startswith('='):
                todate = KSpread.currentSheet().text(todate[1:])
            fromdate=todate

            typename = argument[2] #e.g. "Open"
            if typename.startswith('='):
                typename = KSpread.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = T.i18n("Invalid symbol")
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = T.i18n("Invalid date")
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = T.i18n("Invalid type")
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = T.i18n("Web services request failed")
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0,len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = T.i18n("No stock")
                return
            if len(resultlist) < 7:
                func.error = T.i18n("Invalid stock")
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v,resultlist)
            func.result = v

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Exemple #41
0
 def speakCellValue(self):
     sheet = KSpread.currentSheet()
     (x1, y1, x2, y2) = KSpread.view().selection()
     t = sheet.text(x1, y1)
     self.myorca.speak(t)
Exemple #42
0
 def speakCellName(self):
     sheet = KSpread.currentSheet()
     (x1, y1, x2, y2) = KSpread.view().selection()
     p1 = sheet.cellName(x1, y1)
     self.myorca.speak(p1)
Exemple #43
0
 def speakSheetName(self):
     n = KSpread.view().sheet()
     self.myorca.speak(n)
Exemple #44
0
 def speakSheetName(self):
     n = KSpread.view().sheet()
     self.myorca.speak(n)
Exemple #45
0
#!/usr/bin/env kross

import time, Kross, KSpread

T = Kross.module("kdetranslation")

func = KSpread.function("PYTIME")
func.minparam = 0
func.maxparam = 1
func.comment = T.i18n("The PYTIME() function displays the current datetime.")
func.syntax = T.i18n("PYTIME(string)")
func.addParameter("String", T.i18n("The datetime format string."))
func.addExample(T.i18n("PYTIME()"))
func.addExample(T.i18n("PYTIME(\"%H:%M.%S\")"))
func.addExample(T.i18n("PYTIME(\"%Y-%M-%d\")"))

def update(args):
    try:
        func.result = time.strftime(args[0] or "%H:%M.%S")
    except:
        func.error = T.i18n("Invalid format")

func.connect("called(QVariantList)", update)
func.registerFunction()
Exemple #46
0
#!/usr/bin/env kross

import re, Kross, KSpread

T = Kross.module("kdetranslation")

func = KSpread.function("PYREGEXP")
func.minparam = 3
func.maxparam = 3
func.comment = T.i18n("The PYREGEXP() function replaces substring in the input string with a given string using regular expression.")
func.syntax = T.i18n("PYREGEXP(string)")
func.addParameter("String", T.i18n("The input string."))
func.addParameter("String", T.i18n("The regular expression."))
func.addParameter("String", T.i18n("Replace with."))
func.addExample(T.i18n("PYREGEXP(\"Some String\",\"(S|m)\",\"A\")"))

def update(args):
    s = args[0]
    regexp = args[1]
    repl = args[2]
    try:
        p = re.compile(regexp)
        func.result = p.sub(repl, s)
    except:
        func.error = T.i18n("Invalid regexp")

func.connect("called(QVariantList)", update)
func.registerFunction()
Exemple #47
0
    def __init__(self, scriptaction):
        self.scriptaction = scriptaction
        #self.currentpath = self.scriptaction.currentPath()

        func = KSpread.function("YWEATHER")
        func.minparam = 1
        func.maxparam = 2
        func.comment = (T.i18n(
            "The YWEATHER() function uses the Yahoo! Weather Web Service to display the weather of a location."
        ))
        func.syntax = T.i18n("YWEATHER(string;string)")
        func.addParameter(
            "String",
            T.i18n("The US zip code, Location ID or cell that contains them."))
        func.addParameter(
            "String",
            T.i18n("Units for temperature. f=Fahrenheit and c=Celsius"))
        func.addExample(T.i18n("YWEATHER(\"=A1\")"))
        func.addExample(T.i18n("YWEATHER(\"GMXX0151\";\"c\")"))

        def update(argument):
            print "Yweather.update !"
            location = argument[0]  #e.g. "GMXX0151"
            if location.startswith('='):
                sheet = KSpread.currentSheet()
                location = sheet.text(location[1:])

            if location == None or not re.compile('^[a-zA-Z0-9]+$').match(
                    location):
                func.error = T.i18n("Invalid location")
                return

            url = "http://weather.yahooapis.com/forecastrss?p=%s" % location
            if len(argument) >= 2:
                url += "&u=%s" % urllib.quote_plus(argument[1])

            print "url=%s" % url
            namespace = 'http://xml.weather.yahoo.com/ns/rss/1.0'
            dom = None
            try:
                dom = minidom.parse(urllib.urlopen(url))
            except:
                func.error = T.i18n("Web services request failed")
                return

            forecasts = []
            for node in dom.getElementsByTagNameNS(namespace, 'forecast'):
                forecasts.append({
                    'date': node.getAttribute('date'),
                    'low': node.getAttribute('low'),
                    'high': node.getAttribute('high'),
                    'condition': node.getAttribute('text')
                })

            try:
                ycondition = dom.getElementsByTagNameNS(
                    namespace, 'condition')[0]
            except IndexError:
                func.error = T.i18n("Invalid condition")
                return
            #my_current_condition = ycondition.getAttribute('text')
            #my_current_temp = ycondition.getAttribute('temp')
            #my_forecasts = forecasts
            #my_title = dom.getElementsByTagName('title')[0].firstChild.data

            temp = ycondition.getAttribute('temp')
            print "Y! Weather Temperature: %s" % temp
            func.result = temp

        func.connect("called(QVariantList)", update)
        func.registerFunction()
Exemple #48
0
 def speakCellName(self):
     sheet = KSpread.currentSheet()
     (x1, y1, x2, y2) = KSpread.view().selection()
     p1 = sheet.cellName(x1, y1)
     self.myorca.speak(p1)
Exemple #49
0
        def update(argument):
            print "Yfinance.update !"
            ticker = argument[0] #e.g. "yhoo" or "goog"
            if ticker.startswith('='):
                ticker = KSpread.currentSheet().text(ticker[1:])

            todate = argument[1] #e.g. "20060119"
            if todate.startswith('='):
                todate = KSpread.currentSheet().text(todate[1:])
            fromdate=todate

            typename = argument[2] #e.g. "Open"
            if typename.startswith('='):
                typename = KSpread.currentSheet().text(typename[1:])
            typename = typename.lower()

            if not re.compile('^[a-zA-Z0-9]+$').match(ticker):
                func.error = T.i18n("Invalid symbol")
                return

            if len(todate) != 8 or not re.compile('^[0-9]+$').match(todate):
                func.error = T.i18n("Invalid date")
                return

            typenr = None
            if typename == "date": typenr = 0
            elif typename == "open": typenr = 1
            elif typename == "high": typenr = 2
            elif typename == "low": typenr = 3
            elif typename == "close": typenr = 4
            elif typename == "volume": typenr = 5
            elif typename == "adjclose": typenr = 6
            else:
                func.error = T.i18n("Invalid type")
                return

            quote = dict()
            quote['s'] = ticker
            quote['d'] = str(int(todate[4:6]) - 1)
            quote['e'] = str(int(todate[6:8]))
            quote['f'] = str(int(todate[0:4]))
            quote['g'] = "d"
            quote['a'] = str(int(fromdate[4:6]) - 1)
            quote['b'] = str(int(fromdate[6:8]))
            quote['c'] = str(int(fromdate[0:4]))
            params = urllib.urlencode(quote)
            params += "&ignore=.csv"
            url = "http://ichart.yahoo.com/table.csv?%s" % params
            try:
                f = urllib.urlopen(url)
            except:
                func.error = T.i18n("Web services request failed")
                return
            result = f.read().split("\n")
            resultlist = []
            rx = re.compile('^[0-9]+')
            for i in range(0,len(result)):
                if rx.match(result[i]):
                    resultlist = result[i].split(',')
                    break

            if len(resultlist) < 1:
                func.error = T.i18n("No stock")
                return
            if len(resultlist) < 7:
                func.error = T.i18n("Invalid stock")
                return

            v = resultlist[typenr]
            print "Y! Finance: %s %s" % (v,resultlist)
            func.result = v
Exemple #50
0
        def __init__(self, functions, name, comment, format, params):
            self.__name__ = "R_%s" % name.upper()
            #self.__name__ = "R.%s" % name.upper()

            try:
                self.robj = getattr(rpy.r, name)
                self.isNewFunc = not KSpread.hasFunction(self.__name__)
                if self.isNewFunc:

                    def format2name(fchar):
                        if fchar == 'f': return 'Float'
                        if fchar == 'i': return 'Int'
                        if fchar == 's': return 'String'
                        if fchar == 'b': return 'Boolean'
                        raise "Unknown format char '%s'" % fchar

                    def format2value(fchar, value):
                        if fchar == 'f': return float(value or 0.0)
                        if fchar == 'i': return int(value or 0)
                        if fchar == 's': return "%s" % (value or '')
                        if fchar == 'b':
                            if type(value) == types.StringType:
                                v = value.strip().lower()
                                return bool( len(v)>0 and v!='0' and v!='no' and v!='false' )
                            else:
                                return bool(value)
                        raise "Unknown format char '%s' with value '%s'" % (fchar,value)

                    try:
                        req,opt = format.split('|')
                    except ValueError:
                        req,opt = [ format, [] ]

                    func = KSpread.function(self.__name__)

                    func.typeName = 'Float'
                    func.comment = comment

                    func.syntax = "%s(%s)" % (self.__name__,', '.join([ p.split(':')[0] for p in params ]))
                    #func.syntax = "%s(%s)" % (self.__name__,', '.join([ format2name(r) for r in req ]))

                    func.minparam = len(req)
                    func.maxparam = func.minparam + len(opt)
                    for i in range(0,len(req)):
                        func.addParameter(format2name(req[i]), params[i].split(':')[1])
                    for i in range(0,len(opt)):
                        func.addParameter(format2name(opt[i]), params[len(req)+i].split(':')[1])

                    def callback(arguments):
                        args = []
                        for i in range(0,len(req)):
                            args.append( format2value(req[i], arguments[i]) )
                        for i in range(0,len(opt)):
                            idx = len(req) + i + 1
                            if idx >= len(arguments):
                                break
                            args.append( format2value(opt[i], arguments[idx]) )

                        print "callback name=%s args=%s" % (self.__name__,args)

                        try:
                            func.result = self.robj(*args)
                            #func.result = getattr(self, name)(arguments)
                        except Exception, e:
                            func.error = "%s" % e
                    func.connect("called(QVariantList)", callback)
                    func.registerFunction()

                functions.append( self )
Exemple #51
0
#!/usr/bin/env kross

import time, Kross, KSpread

T = Kross.module("kdetranslation")

func = KSpread.function("PYTIME")
func.minparam = 0
func.maxparam = 1
func.comment = T.i18n("The PYTIME() function displays the current datetime.")
func.syntax = T.i18n("PYTIME(string)")
func.addParameter("String", T.i18n("The datetime format string."))
func.addExample(T.i18n("PYTIME()"))
func.addExample(T.i18n("PYTIME(\"%H:%M.%S\")"))
func.addExample(T.i18n("PYTIME(\"%Y-%M-%d\")"))


def update(args):
    try:
        func.result = time.strftime(args[0] or "%H:%M.%S")
    except:
        func.error = T.i18n("Invalid format")


func.connect("called(QVariantList)", update)
func.registerFunction()