def main(): """ Main program to handle command line parameters and then run what they want. """ # Handle command line parameters from optparse import OptionParser parser = OptionParser( version="v{}".format( versionString ) ) parser.add_option("-e", "--export", action="store_true", dest="export", default=False, help="export the XML file to .py and .h tables suitable for directly including into other programs") Globals.addStandardOptionsAndProcess( parser ) if Globals.verbosityLevel > 1: print( "{} V{}".format( progName, versionString ) ) if Globals.commandLineOptions.export: lgC = _ISO_639_3_Languages_Converter().loadAndValidate() # Load the XML lgC.exportDataToPython() # Produce the .py tables lgC.exportDataToJSON() # Produce a json output file lgC.exportDataToC() # Produce the .h and .c tables else: # Must be demo mode # Demo the converter object lgC = _ISO_639_3_Languages_Converter().loadAndValidate() # Load the XML print( lgC ) # Just print a summary # Demo the languages object lg = ISO_639_3_Languages().loadData() # Doesn't reload the XML unnecessarily :) print( lg ) # Just print a summary print( "qwq valid?", lg.isValidLanguageCode("qwq") ) print( "qwq name:", lg.getLanguageName("qwq") ) print( "mbt valid?", lg.isValidLanguageCode("mbt") ) print( "mbt name:", lg.getLanguageName("mbt") )
def getImporterInfo(id): """ Module function to get information for the given source id. @param id id of the browser ("chrome" or "chromium") @return tuple with an icon (QPixmap), readable name (string), name of the default bookmarks file (string), an info text (string), a prompt (string) and the default directory of the bookmarks file (string) @exception ValueError raised to indicate an invalid browser ID """ if id == "opera": if Globals.isWindowsPlatform(): standardDir = os.path.expandvars("%APPDATA%\\Opera\\Opera") elif Globals.isMacPlatform(): standardDir = os.path.expanduser( "~/Library/Opera") else: standardDir = os.path.expanduser("~/.opera") return ( UI.PixmapCache.getPixmap("opera.png"), "Opera", "bookmarks.adr", QCoreApplication.translate( "OperaImporter", """Opera stores its bookmarks in the <b>bookmarks.adr</b> """ """text file. This file is usually located in"""), QCoreApplication.translate( "OperaImporter", """Please choose the file to begin importing bookmarks."""), standardDir, ) else: raise ValueError("Unsupported browser ID given ({0}).".format(id))
def LoadEvent(self, event, xmlNode, isDead=False): """ Restores an Event from its version 0.10 XML representation. Parameters: event -- the Event instance to apply loaded properties to. xmlNode -- the XML node to retreive data from. """ params = xmlNode.getElementsByTagName("Parameters")[0] Utils.LoadParametersFromXML(event, params) try: xmlPoints = xmlNode.getElementsByTagName("FadePoints")[0] except IndexError: Globals.debug("Missing FadePoints in Event XML") else: event._Event__fadePointsDict = Utils.LoadDictionaryFromXML(xmlPoints) if not isDead: if event.isLoading or event.isRecording: event.GenerateWaveform() else: levels_path = event.GetAbsLevelsFile() try: event.levels_list.fromfile(levels_path) except LevelsList.CorruptFileError: Globals.debug("Cannot load levels from file", levels_path) if not event.levels_list: event.GenerateWaveform() event._Event__UpdateAudioFadePoints() event.CreateFilesource()
def main(): """ Main program to handle command line parameters and then run what they want. """ # Handle command line parameters from optparse import OptionParser parser = OptionParser( version="v{}".format( versionString ) ) parser.add_option("-e", "--export", action="store_true", dest="export", default=False, help="export the XML file to .py and .h/.c formats suitable for directly including into other programs, as well as .json.") Globals.addStandardOptionsAndProcess( parser ) if Globals.verbosityLevel > 1: print( "{} V{}".format( progName, versionString ) ) if Globals.commandLineOptions.export: bbcc = _BibleBooksCodesConverter().loadAndValidate() # Load the XML bbcc.exportDataToPython() # Produce the .py tables bbcc.exportDataToJSON() # Produce a json output file bbcc.exportDataToC() # Produce the .h and .c tables else: # Must be demo mode # Demo the converter object bbcc = _BibleBooksCodesConverter().loadAndValidate() # Load the XML print( bbcc ) # Just print a summary # Demo the BibleBooksCodes object bbc = BibleBooksCodes().loadData() # Doesn't reload the XML unnecessarily :) print( bbc ) # Just print a summary print( "Esther has {} expected chapters".format(bbc.getExpectedChaptersList("EST")) ) print( "Apocalypse of Ezra has {} expected chapters".format(bbc.getExpectedChaptersList("EZA")) ) print( "Names for Genesis are:", bbc.getEnglishNameList_NR("GEN") ) print( "Names for Sirach are:", bbc.getEnglishNameList_NR('SIR') ) print( "All BBBs:", bbc.getAllReferenceAbbreviations() ) print( "PT triples:", bbc.getAllParatextBooksCodeNumberTriples() ) print( "Single chapter books (and OSIS):\n {}\n {}".format(bbc.getSingleChapterBooksList(), bbc.getOSISSingleChapterBooksList()) )
def demo(): """ Main program to handle command line parameters and then run what they want. """ # Handle command line parameters from optparse import OptionParser parser = OptionParser( version="v{}".format( versionString ) ) Globals.addStandardOptionsAndProcess( parser ) if Globals.verbosityLevel>0: print( "{} V{}".format( progName, versionString ) ) # Demo the writer object outputFolder = "OutputFiles" if not os.access( outputFolder, os.F_OK ): os.mkdir( outputFolder ) # Make the empty folder if there wasn't already one there xw = XMLWriter().setOutputFilePath( os.path.join( outputFolder, "test.xml" ) ) xw.setHumanReadable( "All" ) xw.start() xw.writeLineOpen( "vwxyz", [("xmlns","http://someURL.net/namespace"),("xmlns:xsi","http://someURL.net/XMLSchema-instance"),("xsi:schemaLocation","http://someURL.net/namespace http://someURL.net/myOwn.xsd")] ) xw.writeLineOpen( "header" ) xw.writeLineOpenClose( "title", "myTitle" ) xw.writeLineClose( "header" ) xw.writeLineOpen( "body" ) xw.writeLineOpen( "division", [('id','Div1'),('name','First division')] ) xw.writeLineOpenClose( "text", "myText in here", ("font","favouriteFont") ) xw.autoClose() print( xw ) # Just print a summary
def LoadEvent(self, event, xmlNode): """ Loads event properties from a Jokosher 0.1 XML node and saves then to the given Event instance. Parameters: event -- the Event instance to apply loaded properties to. xmlNode -- the XML node to retreive data from. """ params = xmlNode.getElementsByTagName("Parameters")[0] Utils.LoadParametersFromXML(event, params) try: xmlPoints = xmlNode.getElementsByTagName("FadePoints")[0] except IndexError: Globals.debug("Missing FadePoints in Event XML") else: for n in xmlPoints.childNodes: if n.nodeType == xml.Node.ELEMENT_NODE: pos = float(n.getAttribute("position")) value = float(n.getAttribute("fade")) event._Event__fadePointsDict[pos] = value event.GenerateWaveform() event._Event__UpdateAudioFadePoints() event.CreateFilesource()
def LoadEvent(self, event, xmlNode, isDead=False): """ Restores an Event from its version 0.2 XML representation. Parameters: event -- the Event instance to apply loaded properties to. xmlNode -- the XML node to retreive data from. """ params = xmlNode.getElementsByTagName("Parameters")[0] Utils.LoadParametersFromXML(event, params) try: xmlPoints = xmlNode.getElementsByTagName("FadePoints")[0] except IndexError: Globals.debug("Missing FadePoints in Event XML") else: event._Event__fadePointsDict = Utils.LoadDictionaryFromXML(xmlPoints) if not isDead: #if event.isLoading or event.isRecording: # we have to always generate waveform because 0.10 uses different levels format event.GenerateWaveform() event._Event__UpdateAudioFadePoints() event.CreateFilesource()
def manage_addRDFCalendar(self, id, title='', first_day_week='Monday', week_day_len=3, REQUEST=None): """Add a new RDFCalendar object with id=title.""" ob=RDFCalendar(id, title, first_day_week, week_day_len) ob.id = id self._setObject(id, ob) indexfile = open(join(Globals.package_home(globals()) , \ 'dtml','RDFCalendarIndex.dtml')) content = indexfile.read() indexfile.close() ob.manage_addDTMLMethod('index_html', title='Calendar Events', file=content) show_events_file = open(join(Globals.package_home(globals()) , \ 'dtml','RDFCalendar_dayevents.dtml')) content = show_events_file.read() show_events_file.close() ob.manage_addDTMLMethod('show_day_events', title='Show events for one day', file=content) if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1)
def LoadInstrument(self, instr, xmlNode): """ Loads instrument properties from a Jokosher 0.1 XML node and saves them to the given Instrument instance. Parameters: instr -- the Instrument instance to apply loaded properties to. xmlNode -- the XML node to retreive data from. """ params = xmlNode.getElementsByTagName("Parameters")[0] Utils.LoadParametersFromXML(instr, params) #work around because in >0.2 instr.effects is a list not a string. instr.effects = [] for ev in xmlNode.getElementsByTagName("Event"): try: id = int(ev.getAttribute("id")) except ValueError: id = None e = Event.Event(instr, None, id) self.LoadEvent(e, ev) e.levels_file = e.GetFilename() + Event.Event.LEVELS_FILE_EXTENSION instr.events.append(e) pixbufFilename = os.path.basename(instr.pixbufPath) instr.instrType = os.path.splitext(pixbufFilename)[0] instr.pixbuf = Globals.getCachedInstrumentPixbuf(instr.instrType) if not instr.pixbuf: Globals.debug("Error, could not load image:", instr.instrType) #initialize the actuallyIsMuted variable instr.OnMute()
def createList(self, packages, part = None, selected = [], disabled = []): head = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> ''' if not part: part = self.part self.selected = selected self.disabled = disabled Globals.setWaitCursor() try: part.view().setContentsPos(0, 0) part.begin() part.write(head) part.write("<style type=\"text/css\">%s</style>" % self.css) part.write("<script language=\"JavaScript\">%s</script>" % self.javascript) part.write("</head><body>") if set(packages) - set(selected): part.write('''<font size="-2"><a href="#selectall">'''+i18n("Select all packages in this category")+'''</a></font>''') else: part.write('''<font size="-2"><a href="#selectall">'''+i18n("Reverse package selections")+'''</a></font>''') part.write(self.createListForPackages(packages)) part.end() finally: Globals.setNormalCursor()
def __init__(self, parent=None): """ Constructor @param parent reference to the parent object (QObject) """ super(E5SslErrorHandler, self).__init__(parent) caList = self.__getSystemCaCertificates() if Preferences.Prefs.settings.contains("Help/CaCertificatesDict"): # port old entries stored under 'Help' certificateDict = Globals.toDict( Preferences.Prefs.settings.value("Help/CaCertificatesDict")) Preferences.Prefs.settings.setValue( "Ssl/CaCertificatesDict", certificateDict) Preferences.Prefs.settings.remove("Help/CaCertificatesDict") else: certificateDict = Globals.toDict( Preferences.Prefs.settings.value("Ssl/CaCertificatesDict")) for server in certificateDict: for cert in QSslCertificate.fromData(certificateDict[server]): if cert not in caList: caList.append(cert) sslCfg = QSslConfiguration.defaultConfiguration() sslCfg.setCaCertificates(caList) sslCfg.setProtocol(QSsl.AnyProtocol) try: sslCfg.setSslOption(QSsl.SslOptionDisableCompression, True) except AttributeError: pass QSslConfiguration.setDefaultConfiguration(sslCfg)
def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products folder_permissions = get_folder_permissions() meta_types=[] done={} get_transaction().note('Prior to product installs') get_transaction().commit() products = get_products() for priority, product_name, index, product_dir in products: # For each product, we will import it and try to call the # intialize() method in the product __init__ module. If # the method doesnt exist, we put the old-style information # together and do a default initialization. if done.has_key(product_name): continue done[product_name]=1 install_product(app, product_dir, product_name, meta_types, folder_permissions) Products.meta_types=Products.meta_types+tuple(meta_types) Globals.default__class_init__(Folder.Folder)
def printTrace(entity='', **kw): assert len(kw)==1, 'only one phrase per printTrace supported for the moment' from Globals import G import Globals time=G.env.now charLimit=60 remainingChar=charLimit-len(entity)-len(str(time)) if(G.console=='Yes'): print time,entity, for key in kw: if key not in Globals.getSupportedPrintKwrds(): raise ValueError("Unsupported phrase %s for %s" % (key, entity)) element=Globals.getPhrase()[key] phrase=element['phrase'] prefix=element.get('prefix',None) suffix=element.get('suffix',None) arg=kw[key] if prefix: print prefix*remainingChar,phrase,arg elif suffix: remainingChar-=len(phrase)+len(arg) suffix*=remainingChar if key=='enter': suffix=suffix+'>' print phrase,arg,suffix else: print phrase,arg
def updateStatusBar(self): Globals.setWaitCursor() try: self.basket.update() finally: Globals.setNormalCursor() if not self.basket.packages: text = i18n("Currently your basket is empty.") elif self.state == install_state or self.state == upgrade_state: text = i18n("Currently there are <b>%1</b> selected package(s) of total <b>%2</b> of size ").arg(len(self.basket.packages)).arg(Globals.humanReadableSize(self.basket.packagesSize)) if self.basket.extraPackages: text += i18n("with <b>%3</b> extra dependencies of total <b>%4</b> of size ").arg(len(self.basket.extraPackages)).arg(Globals.humanReadableSize(self.basket.extraPackagesSize)) text += i18n("in your basket.") elif self.state == remove_state: text = i18n("Currently there are <b>%1</b> selected package(s) of total <b>%2</b> of size ").arg(len(self.basket.packages)).arg(Globals.humanReadableSize(self.basket.packagesSize)) if self.basket.extraPackages: text += i18n("with <b>%3</b> reverse dependencies of total <b>%4</b> of size ").arg(len(self.basket.extraPackages)).arg(Globals.humanReadableSize(self.basket.extraPackagesSize)) text += i18n("in your basket.") self.parent.updateStatusBarText(text)
def enter_entry(self): if not Globals.PLAYER is None: Globals.PLAYER.kill(False) Globals.PLAYER = None World.cleanupCompletely() Globals.CURRENT_LEVEL = "one" Globals.initSunTracker(True) Globals.PLAYER_MAX_HEALTH = 15 SKILL_MAX_HEALTH = 0 PLAYER_REGEN_TIME = 7 PLAYER_DAMAGE = 5 SKILL_DAMAGE = 0 PLAYER_MAX_MP = 10 PLAYER_SKILL = 0 PLAYER_JUMP = 610.0 SKILL_JUMP = 0 ARROW_VELOCITY = 700.0 ARROW_HITS = 1 ARROW_DAMAGE = 2 BOW_COOLDOWN = 0.7 MAX_SKILL = 9 MINI_SUNS = 0 LEVELS_BEAT = 0 SCORE = 0 TIME = 120 Globals.STATE = ControlScreen.ControlScreen()
def slotQuit(self): if self.mainwidget.command.inProgress(): return # Don't know why but without this, after exiting package-manager, crash occurs. This may be a workaround or a PyQt bug. self.mainwidget.deleteLater() Globals.debug("package-manager is quiting.") kapp.quit()
def __init__(self,parent=None,name=None): KMainWindow.__init__(self,parent,name) self.statusLabel = QLabel("", self.statusBar()) self.statusBar().addWidget(self.statusLabel) self.statusBar().setSizeGripEnabled(True) self.setCaption(i18n("Package Manager")) self.aboutus = KAboutApplication(self) self.helpWidget = None self.mainwidget = MainApplicationWidget(self) self.setCentralWidget(self.mainwidget) self.setupMenu() self.setupGUI(KMainWindow.ToolBar|KMainWindow.Keys|KMainWindow.StatusBar|KMainWindow.Save|KMainWindow.Create) self.fixHelpMenu() self.toolBar().setIconText(KToolBar.IconTextRight) self.dcop = PmDcop.PmDcop(self) self.tray = Tray.Tray(self) if self.mainwidget.settings.getBoolValue(Settings.general, "SystemTray"): if self.mainwidget.settings.getBoolValue(Settings.general, "UpdateCheck"): Globals.debug("Update check option is set.") interval = self.mainwidget.settings.getNumValue(Settings.general, "UpdateCheckInterval") Globals.debug("Update check will start in %s minute(s)" % interval) self.tray.updateInterval(interval) self.tray.show() self.connect(self.tray, SIGNAL("quitSelected()"), self.slotQuit) self.connect(kapp, SIGNAL("shutDown()"), self.slotQuit)
def event(self, event): if event.type == PG.MOUSEBUTTONDOWN: if Menu.Menu.check_mouse(Menu.Menu(), 340, 40, 20, 20): if (G.Globals.FX_VOL - 1) >= 0: G.Globals.FX_VOL -= 1 elif Menu.Menu.check_mouse(Menu.Menu(), 430, 40, 20, 20): if (G.Globals.FX_VOL + 1) <= 10: G.Globals.FX_VOL += 1 elif Menu.Menu.check_mouse(Menu.Menu(), 340, 100, 20, 20): if (G.Globals.MUSIC_VOL - 1) >= 0: G.Globals.MUSIC_VOL -= 1 elif Menu.Menu.check_mouse(Menu.Menu(), 430, 100, 20, 20): if (G.Globals.MUSIC_VOL + 1) <= 10: G.Globals.MUSIC_VOL += 1 elif Menu.Menu.check_mouse(Menu.Menu(), G.Globals.WIDTH-(self.save_x+20), G.Globals.HEIGHT, self.save_surf.get_width(), self.save_surf.get_height()): G.set_vol() G.Globals.STATE = Options.Options()
def decompose(self): activeObjectQueue=self.getActiveObjectQueue() #loop in the internal Queue. Decompose only if an Entity is of type order # XXX now instead of Order we have OrderDesign for entity in activeObjectQueue: if entity.type=='OrderDesign': self.orderToBeDecomposed=entity.order activeObjectQueue.remove(entity) #remove the order from the internal Queue self.printTrace(entity.id, destroy=self.id) # if the entity is in G.pendingEntities list remove it from there if entity in G.pendingEntities: G.pendingEntities.remove(entity) #append the components in the internal queue for component in entity.order.componentsList: self.createOrderComponent(component) # after the creation of the order's components update each components auxiliary list # if there are auxiliary components if len(entity.order.auxiliaryComponentsList): # for every auxiliary component for auxComponent in entity.order.auxiliaryComponentsList: # run through the componentsList of the order for reqComponent in entity.order.componentsList: # to find the requestingComponent of the auxiliary component if auxComponent.requestingComponent==reqComponent.id: # and add the auxiliary to the requestingComponent auxiliaryList reqComponent.auxiliaryList.append(auxComponent) #if there is an order for decomposition if self.orderToBeDecomposed: import Globals Globals.setWIP(self.newlyCreatedComponents) #set the new components as wip # TODO: consider signalling the receivers if any WIP is set now #reset attributes self.orderToBeDecomposed=None self.newlyCreatedComponents=[]
def SaveTemplateFile(self, name, instrlist): """ This method will write a template file to JOKOSHER_DATA_HOME/templates/. instrlist is a list containing type strings corresponding to each instrument. e.g. ["audiofile", "acousticguitar"]. Parameters: name -- the name of the template file. instrlist -- a list containing the instrument type strings """ doc = xml.Document() head = doc.createElement("JokosherProjectTemplate") doc.appendChild(head) for typeString in instrlist: # create instrument tags for every instrument in the list instrtag = doc.createElement("Instrument") instrtag.setAttribute("type", typeString) head.appendChild(instrtag) if not name.endswith("." + self.TEMPLATE_EXT): name += "." + self.TEMPLATE_EXT namePath = os.path.join(Globals.TEMPLATES_PATH, name) try: try: filename = open(namePath, "w") filename.write(doc.toprettyxml()) except IOError, e: Globals.debug("The template %s does not exist" % namePath) finally: filename.close() self.emit("template-update")
def ToggleEnabled(self, cell, path): """ Enables/disables an Extension. Parameters: cell -- reserved for GTK callbacks, don't use it explicitly. path -- path to the Extension. """ self.model[path][0] = not self.model[path][0] iter = self.model.get_iter(path) name = self.model.get_value(iter, 1) filename = self.model.get_value(iter, 4) if self.model[path][0]: if name in Globals.settings.extensions['extensions_blacklist']: Globals.settings.extensions['extensions_blacklist'] = Globals.settings.extensions['extensions_blacklist'].replace(name, "") Globals.debug("extension-blacklist:", Globals.settings.extensions['extensions_blacklist']) for extension in self.parent.extensionManager.GetExtensions(): if filename == extension['filename']: extension['enabled'] = True self.parent.extensionManager.StartExtension(filename) else: if name not in Globals.settings.extensions['extensions_blacklist']: Globals.settings.extensions['extensions_blacklist'] += name+" " self.parent.extensionManager.StopExtension(filename) for extension in self.parent.extensionManager.GetExtensions(): if filename == extension['filename']: extension['enabled'] = False
def FillLADSPARegistry(self): """ Fill Globals.LADSPA_FACTORY_REGISTRY with effects on the system. This is to ensure that only presets with effects on the current system are listed. """ Globals.debug("Filling LADSPA Registry") ##make sure all the structures are empty before we append to them Globals.LADSPA_NAME_MAP=[] Globals.LADSPA_FACTORY_REGISTRY = None effects = [] ladspaFactoryList = gst.registry_get_default().get_feature_list_by_plugin("ladspa") for factory in ladspaFactoryList: if isinstance(factory, gst.ElementFactory): # from the list of LADSPA effects we check which ones only # have a single sink and a single src so we know they work if factory.get_num_pad_templates() == 2: pads = factory.get_static_pad_templates() sinkpads = len( [pad for pad in pads if pad.direction == gst.PAD_SINK] ) srcpads = len( [pad for pad in pads if pad.direction == gst.PAD_SRC] ) if srcpads == 1 and sinkpads == 1: effects.append(factory.get_name()) Globals.LADSPA_NAME_MAP.append((factory.get_name(), factory.get_longname())) Globals.debug("\t", len(effects), "LADSPA effects loaded") Globals.LADSPA_FACTORY_REGISTRY = set(effects)
def LoadSingleEffect(self, presetName, effectelement): """ Load effect settings from a preset file for a single effect. Parameters: presetName -- the name of the preset to be loaded. effectelement -- the effect element to be loaded. Returns: a settings dictionary with the loaded settings for the effect or False if the preset file doesn't exist. """ filename = self._PresetFilename(effectelement, presetName) presetfile = Globals.EFFECT_PRESETS_PATH + filename Globals.debug(presetfile) if not os.path.exists(presetfile): Globals.debug("preset file does not exist") return False else: xmlfile = open(presetfile, "r") doc = xml.parse(presetfile) settingstags = doc.getElementsByTagName('Effect')[0].getElementsByTagName('Settings')[0] settdict = LoadDictionaryFromXML(settingstags) return settdict
def InitProjectLocation(projecturi): """ Initialises the folder structure on disk for a Project. If no project is provided, a new one is created. Otherwise the given project is essentially moved to the new location. Parameters: projecturi -- the filesystem location for the new Project. Currently, only file:// URIs are considered valid. Returns: the given Project, or the newly created Project object. """ if not projecturi: raise CreateProjectError(4) (scheme, domain,folder, params, query, fragment) = urlparse.urlparse(projecturi, "file", False) folder = PlatformUtils.url2pathname(folder) if scheme != "file": # raise "The URI scheme used is invalid." message raise CreateProjectError(5) filename = "project.jokosher" folder_name_template = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M") projectdir = os.path.join(folder, folder_name_template) try: project = Project.Project() except gst.PluginNotFoundError, e: Globals.debug("Missing Gstreamer plugin:", e) raise CreateProjectError(6, str(e))
def OnEffectsButtonClicked(self, widget): """ Creates and shows the instrument effects dialog if LADSPA is installed. Parameters: widget -- reserved for GTK callbacks, don't use it explicitly. mouse -- reserved for GTK callbacks, don't use it explicitly. """ Globals.debug("props button pressed") if Globals.LADSPA_NAME_MAP: if not self.effectsDialog: self.effectsDialog = InstrumentEffectsDialog.InstrumentEffectsDialog( self.instrument, self.OnEffectsDialogDestroyed, self.mainview.icon) else: self.effectsDialog.BringWindowToFront() else: message = gtk.MessageDialog(parent=None, flags=0, type=gtk.MESSAGE_INFO,buttons=gtk.BUTTONS_OK, message_format=_("You do not have any LADSPA effects plugins installed")) if platform.system() =="Windows": message.format_secondary_text(_("Jokosher does not currently support any LADSPA plugins on Windows")) else: message.format_secondary_text(_("Jokosher requires one or more packages of LADSPA effects to be able to use this feature, please install the relevant package(s) for your distribution.")) message.show_all() response = message.run() if response == gtk.RESPONSE_OK: message.destroy()
def RemoveExtension(self, filename): """ Removes the given Extension. Considerations: This function "unloads" the Extension. It executes the shutdown() function of the Extension and then removes it from loadedExtensions. Parameters: filename -- the name of the file containing the Extension. Returns: True -- the Extension was successfully removed. False -- an error ocurred while trying to remove the Extension. """ self.StopExtension(filename) index = -1 for extension in self.GetExtensions(): index += 1 if extension['filename'] == filename: try: os.remove(filename) self.loadedExtensions.pop(index) except Exception, e: Globals.debug("Failed to remove " + filename) Globals.debug(e) return False
def OnOK(self, button=None): """ This method is called when the ok button in the dialog has been clicked. It will then add the selected instrument into the main jokosher window (JokosherApp). Parameters: button -- reserved for GTK callbacks, don't use it explicity. """ selectedItems = self.tree.get_selected_items() if not self.instr: instrList = [] for i in selectedItems: item = self.model[i[0]] #find the actual instrument using index 1 (the instrument type) #because the name has been wrapped in self.model and can't be used name, type, pixbuf, path = [x for x in Globals.getCachedInstruments() if x[1] == item[1]][0] instrList.append( (name, type) ) self.project.AddInstruments(instrList) else: item = self.model[selectedItems[0][0]] instrItem = [x for x in Globals.getCachedInstruments() if x[1] == item[1]][0] self.instr.ChangeType(instrItem[1], instrItem[0]) self.dlg.destroy()
def LoadEffectChain(self, presetName, instrType): """ Load settings from the preset file for an Instrument's effects chain. Parameters: presetName -- name of the preset to be loaded. Returns: a settings dictionary with the loaded settings for the effects. """ filename = self._PresetFilename(instrType, presetName) presetfile = Globals.EFFECT_PRESETS_PATH + filename if not os.path.exists(presetfile): Globals.debug("preset file does not exist") else: xmlfile = open(presetfile, "r") doc = xml.parse(presetfile) settdict = {} for effect in doc.getElementsByTagName('Effect'): preftags = effect.getElementsByTagName('Parameters')[0] prefs = LoadDictionaryFromXML(preftags) settingstags = effect.getElementsByTagName('Settings')[0] setts = LoadDictionaryFromXML(settingstags) elementname = setts["name"] settdict[str(elementname)] = {'preferences': prefs, 'settings': setts} return settdict
def update(self, game_time): # Track targets, perform interpolation. if self.focus != None: if self.prev_focal_position != None: assert self.shift_start_time >= 0, "Multiple targets assigned to camera without shift time." delta = (game_time - self.shift_start_time) / self.shift_time # If the change hasn't reached the final value, then calculate # the camera position based on linear interpolation between # the targets. if delta < 1: self.fpos[0] = Globals.ease(self.prev_focal_position[0], self.focus.centerx, delta) self.fpos[1] = Globals.ease(self.prev_focal_position[1], self.focus.centery, delta) # Otherwise, if the delta indicates that the transition is over, # set the camera's position to the position of the current target # and stop the transitioning. else: self.fpos[0] = self.focus.centerx self.fpos[1] = self.focus.centery self.prev_focal_position = None self.shift_start_time = -1 # If the camera is attached to one target, simply follow that target # with the camera. else: clamped = PG.Rect(self.follow(self.fpos[0], self.focus.centerx) - self.width/2, self.follow(self.fpos[1], self.focus.centery) - self.height/2, self.width, self.height).clamp(self.border) self.fpos[0] = clamped.centerx self.fpos[1] = clamped.centery self.position[0] = int( self.fpos[0] + self.offset[0] ) self.position[1] = int( self.fpos[1] + self.offset[1] )
def LoadMixdownActionsFromProfile(self, name): """ Called when actions from a profile need to be loaded. This method will return a list of MixdownAction instances associated with the profile name specified. Parameters: name-- the name of a profile to load actions from. Returns: actions -- a list of MixdownAction instances assocated with the profile specified. """ if not name.endswith("." + self.MIXDOWN_EXT): name += "." + self.MIXDOWN_EXT namePath = os.path.join(Globals.MIXDOWN_PROFILES_PATH, name) if os.path.exists(namePath): file = open(namePath, "r") doc = xml.parse(file) actions = [] for node in doc.getElementsByTagName("MixdownActions"): for children in node.childNodes: if children.nodeType == 1: for child in children.childNodes: if child.nodeType == 1: actionObject = self.__LoadMixdownAction(children.nodeName) if actionObject: configActionObject = self.__HandleMixdownActionConfig(actionObject, child) actions.append(configActionObject) return actions else: Globals.debug(_("The mixdown profile %s does not exist" % namePath))
class ErrorTranslationRule(SimpleItem.SimpleItem): __implements__ = IErrorTranslator.IErrorTranslationRule security = AccessControl.ClassSecurityInfo() meta_type = "Error Translation Rule" manage_properties = Globals.HTMLFile('dtml/ErrorTranslationRuleEdit', globals()) title = "" # Regexp to match the error type typeMatch = None # Regexp to match the error value errorMatch = None # Regexp with backreferences to errorMatch for creating the user message msgRule = None # Number of group in errorMatch for the Fielis dname # SPECIAL CASE: if no number, you can write the fieldname in here # (or its alias) brField = None # Number of group in errorMatch for the Value brValue = None # Priority for sorting the rules (0 = lowest, >0 = higher Priority) priority = 100 manage_options = ( {'label':'Properties', 'action':'manage_properties'}, ) # Here comes the Zope specific code def __init__(self, id, REQUEST=None): self.id = id if REQUEST is not None: self.update(REQUEST) security.declareProtected("Change Translation Rules", "manage_edit") def manage_edit(self, REQUEST=None): """ZMI data save method""" if REQUEST is not None: self.update(REQUEST) return Globals.MessageDialog(title="Edited", message="Properties for %s changed." % self.id, action="./manage_properties") security.declareProtected("Change Translation Rules", "update") def update(self, REQUEST): if REQUEST is None: return self.title = REQUEST.title self.typeMatch = REQUEST.typeMatch self.errorMatch = REQUEST.errorMatch self.msgRule = unicode(REQUEST.msgRule, 'iso-8859-1') self.brField = REQUEST.brField or None try: self.brValue = int(REQUEST.brValue) except ValueError: self.brValue = None self.priority = REQUEST.priority def re_typeMatch(self): return re.compile(self.typeMatch, re.MULTILINE + re.DOTALL) re_typeMatch = zope.cachedescriptors.property.CachedProperty( re_typeMatch, 'typeMatch') def re_errorMatch(self): return re.compile(self.errorMatch, re.MULTILINE + re.DOTALL) re_errorMatch = zope.cachedescriptors.property.CachedProperty( re_errorMatch, 'errorMatch') security.declarePublic("isResponsible") def isResponsible(self, error): """returns whether this rule can translate given error error: uhm.. what is error? XXX returns True if rule would be appropriate to use for the translation, False otherwise """ if self.re_typeMatch.search(unicode(error.errortype)) is None: return False if self.re_errorMatch.search(unicode(error.hint)) is None: return False return True security.declarePublic("translate") def translate(self, error): if not self.isResponsible(error): raise ResponsibilityError, "%s is not responsible for this error." % self.id # XXX check for IErrorTranslationHint here brFieldString = '' try: brFieldNo = int(self.brField) except (TypeError, ValueError): brFieldNo = 0 brFieldString = self.brField match = self.re_errorMatch.search(unicode(error.hint)) groups = match.groups() # If the groupcount from the regexp doesn't match, # we don't check for a regexp translation. # XXX probably a debugging note on the server would # be appropriate here. regex_value = (self.brValue <= len(groups)) and self.brValue regex_field = (brFieldNo <= len(groups)) and brFieldNo # Find the Fieldname: if error.field: # The error already knew it's field pass elif regex_field: # We knew how to handle it with a reg. exp. error.field = groups[regex_field-1] elif brFieldString: error.field = brFieldString else: # We need to find the field by Value. if error.value: pass elif regex_value: error.value = groups[regex_value-1] # try to find a field matching the fieldname or alias of the error if error.field is not None and error.form is not None: field_translated = None for item in error.form.objectValues(): if not IWidget.IWidget.isImplementedBy(item): continue if not item.testCondition(): # do not show errors on hidden fields continue name_candidates = (tuple(item.getAliases()) + tuple([item.getName()]) ) if error.field in name_candidates : field_translated = item.getName() break if field_translated: error.field = field_translated else: error.field = ERROR_FIELD_BLANK # Fieldname not existing in form elif error.value is None: error.field = ERROR_FIELD_BLANK # try to find a field matching the fieldvalue if (error.field is None and error.value is not None and error.form is not None): candidate = None for item in error.form.objectValues(): if IWidget.IWidget.isImplementedBy(item) and \ error.value == item.getValue() and not candidate: candidate = item.getName() error.field = candidate # create the translated error message if not error.description: error.description = self.re_errorMatch.sub(self.msgRule, error.hint, 1) security.declareProtected("Access contents information", "getPriority") def getPriority(self): return self.priority
def register(self, extension, filename, directory, local): """ Called from Extension.LoadAllExtensions afer the Extensions module has been imported (and the class instantiated in the case of extensions that are eggs). Parameters: extension -- a reference to the Extension. Either a module or in the case of an Extension imported from an egg, an instance object. filename -- the name of the file containing the Extension. directory -- full path to the directory containing the file. local -- True = the extension is to be copied to the local extension directory after checking False = don't copy the Extension. Returns: True -- the Extension was successfully registered. False -- an error ocurred while trying to register the Extension, or the Extension has been disabled via the ExtensionManagerDialog. """ name = None preferences = False # check if the necessary attributes EXTENSION_NAME, EXTENSION_VERSION # and EXTENSION_DESCRIPTION are present and # refuse to start the extension if they are missing. requiredAttributes = ("EXTENSION_NAME", "EXTENSION_VERSION", "EXTENSION_DESCRIPTION", "startup", "shutdown") missingAttrs = [] for attr in requiredAttributes: if not hasattr(extension, attr): missingAttrs.append(attr) if missingAttrs: Globals.debug("\t" + filename, "missing", ", ".join(missingAttrs)) return False else: name = extension.EXTENSION_NAME version = extension.EXTENSION_VERSION description = extension.EXTENSION_DESCRIPTION # check for preferences attribute if hasattr(extension, "preferences"): preferences = True # check extension is not already loaded for testExtension in self.loadedExtensions: if testExtension["name"] == name: Globals.debug(filename + " extension '" + name + "' already present") return False # find full file name of extension extensionFile = os.path.join(directory, filename) # if we are installing locally first check the file doesn't exist and # then try and copy it if local: extensionFile = os.path.join(Globals.JOKOSHER_DATA_HOME, "extensions", filename) if os.path.exists(extensionFile): Globals.debug("Filename " + extensionFile + " already exists") return False else: try: shutil.copy(os.path.join(directory, filename), extensionFile) except Exception, e: Globals.debug(filename + "Failed copying file: " + str(e)) return False
# check if extension's requirements are met (only if the extension requires it) testResults = (True, "") try: if hasattr(extension, "check_dependencies"): testResults = extension.check_dependencies() except Exception, e: Globals.debug(name + " extension could not check its dependencies") Globals.debug(e) return False # if the system doesn't provide what the extension needs, # fail loading this plugin and set the error message if testResults[0] == False: #TODO: inform the user of the error Globals.debug(name + ": " + testResults[1]) return False # check if the extension is blacklisted, if so, mark it as disabled enabled = True if name in Globals.settings.extensions['extensions_blacklist']: enabled = False # add details to loadedExtensions list self.loadedExtensions.append({ "name": name, "description": description, "version": version, "extension": extension, "enabled": enabled, "preferences": preferences,
if cookie != mskin: resp = req.RESPONSE expires = (DateTime('GMT') + 365).rfc822() resp.setCookie(self.request_varname, mskin, path='/', expires=expires) # Ensure updateSkinCookie() doesn't try again # within this request. req.cookies[self.request_varname] = mskin req[self.request_varname] = mskin return 1 return 0 security.declareProtected(ManagePortal, 'addSkinSelection') def addSkinSelection(self, skinname, skinpath, test=0, make_default=0): ''' Adds a skin selection. ''' sels = self._getSelections() skinpath = str(skinpath) if test: self.testSkinPath(skinpath) sels[str(skinname)] = skinpath if make_default: self.default_skin = skinname Globals.InitializeClass(SkinsTool)
import os.path filepath = os.path.join( 'Tests/DataFilesForTests/', 'MatigsalugDictionaryA.sfm' ) if Globals.verbosityLevel > 2: print( "Using {} as test file...".format( filepath ) ) linesDB = SFMLines() linesDB.read( filepath, ignoreSFMs=('mn','aMU','aMW','cu','cp') ) print( len(linesDB.lines), 'lines read from file', filepath ) for i, r in enumerate(linesDB.lines): print ( i, r) if i>9: break print ( '...\n',len(linesDB.lines)-1, linesDB.lines[-1], '\n') # Display the last record recordsDB = SFMRecords() recordsDB.read( filepath, 'og', ignoreSFMs=('mn','aMU','aMW','cu','cp')) print( len(recordsDB.records), 'records read from file', filepath ) for i, r in enumerate(recordsDB.records): print ( i, r) if i>3: break print( '...\n',len(recordsDB.records)-1, recordsDB.records[-1]) # Display the last record # end of demo if __name__ == '__main__': # Configure basic set-up parser = Globals.setup( ProgName, ProgVersion ) Globals.addStandardOptionsAndProcess( parser ) demo() Globals.closedown( ProgName, ProgVersion ) # end of SFMFile.py
self.invokeFactory( type_name='Folder', id=id ) else: # call it getattr( self, action )( id=id ) ob = self._getOb( id ) ob.setTitle( title ) try: ob.reindexObject() except AttributeError: pass if REQUEST is not None: return self.manage_main(self, REQUEST, update_menu=1) Globals.InitializeClass(PortalFolder) class ContentFilter: """ Represent a predicate against a content object's metadata. """ MARKER = [] filterSubject = [] def __init__( self , Title=MARKER , Creator=MARKER , Subject=MARKER , Description=MARKER , created=MARKER
class ErrorTranslator(Folder.Folder, Persistence.Persistent, Acquisition.Implicit, AccessControl.Role.RoleManager): __implements__ = IErrorTranslator.IErrorTranslator security = AccessControl.ClassSecurityInfo() id = 'ErrorTranslator' title = "Error Translation registry" meta_type = "Error Translator" security.declareProtected('View management screens', 'manage_debug') manage_debug = Globals.HTMLFile('dtml/ErrorTranslatorDebug', globals()) manage_options = Folder.Folder.manage_options + \ ( {'label':'Debug', 'action':'manage_debug'}, ) manage_options = filter(lambda x: x['label'] not in ['View', 'Properties', 'Find'], manage_options) ##### Here comes the ZOPE management stuff def __init__(self): self.__version__ = __version__ def all_meta_types(self): """We only want to add Error Translation Rules here.""" allowedMetaTypes = ["Error Translation Rule", "Error Translation Rule Group"] result = [] import Products for metaType in Products.meta_types: if metaType['name'] in allowedMetaTypes: result.append(metaType) return result security.declarePublic("translateEasy") def translateEasy(self, type=None, value=None, description=None): """ Try a translation when we only got a type and a value. """ hint = ErrorTranslationHint(None, None, type, value, None, description) translated = self.translate(hint) return translated security.declarePublic("translate") def translate(self, error): """Translate the given error. error: ErrorTranslationHint returns: ErrorTranslationHint instance This means the hint will be set to a value useful for the user. The actual work is done by the rules. We only try to find the actual rule that matches this error. Then the rule has to do the work. """ assert IErrorTranslator.IErrorTranslationHint.isImplementedBy(error), \ "ErrorTranslator interface not satisfied" rules = self.discoverRules() is_translated = 0 for rule in rules: if (IErrorTranslator.IErrorTranslationRule.isImplementedBy(rule) and rule.isResponsible(error)): rule.translate(error) is_translated = 1 break if not is_translated and not error.field: zLOG.LOG('ErrorTranslator', zLOG.INFO, 'Untranslated exception occured', str(error)) error.field = ERROR_FIELD_BLANK error.description = error.hint return error security.declarePrivate('discoverRules') def discoverRules(self): stack = self.objectValues() rules = [] while stack: element = stack.pop() # Append rule to the list if isinstance(element, ErrorTranslationRule): rules.append(element) # Check if it could be a container that holds more rules try: new = element.objectValues() stack.extend(new) except AttributeError: pass rules.sort(lambda x,y: cmp(x.getPriority(), y.getPriority())) return rules
raise ValueError, 'Not a valid permission name:' + p self.permissions = self.permissions + (p, ) if REQUEST is not None: return self.manage_permissions( REQUEST, manage_tabs_message='Permission added.') security.declareProtected(ManagePortal, 'delManagedPermissions') def delManagedPermissions(self, ps, REQUEST=None): ''' ''' if ps: l = list(self.permissions) for p in ps: l.remove(p) self.permissions = tuple(l) if REQUEST is not None: return self.manage_permissions( REQUEST, manage_tabs_message='Permission(s) removed.') security.declareProtected(ManagePortal, 'getPossiblePermissions') def getPossiblePermissions(self): ''' ''' # possible_permissions is in AccessControl.Role.RoleManager. return list(self.possible_permissions()) Globals.InitializeClass(WorkflowUIMixin)
m = members[id] # Return a wrapper with self as containment and # the user as context. return m.__of__(self).__of__(u) security.declarePrivate('registerMemberData') def registerMemberData(self, m, id): ''' Adds the given member data to the _members dict. This is done as late as possible to avoid side effect transactions and to reduce the necessary number of entries. ''' self._members[id] = m Globals.InitializeClass(MemberDataTool) class MemberData (SimpleItem): security = ClassSecurityInfo() def __init__(self, tool, id): self.id = id # Make a temporary reference to the tool. # The reference will be removed by notifyModified(). self._tool = tool security.declarePrivate('notifyModified') def notifyModified(self): # Links self to parent for full persistence. tool = getattr(self, '_tool', None)
element = stack.pop() # Append rule to the list if isinstance(element, ErrorTranslationRule): rules.append(element) # Check if it could be a container that holds more rules try: new = element.objectValues() stack.extend(new) except AttributeError: pass rules.sort(lambda x,y: cmp(x.getPriority(), y.getPriority())) return rules Globals.InitializeClass(ErrorTranslator) manage_addErrorTranslationRule = Globals.HTMLFile('dtml/ErrorTranslationRuleAdd', globals()) def createErrorTranslationRule(context, id, REQUEST=None): """A factory for creating a new translation rule.""" context._setObject(id, ErrorTranslationRule(id, REQUEST)) if REQUEST is not None: return context.manage_main(context, REQUEST) class ErrorTranslationRule(SimpleItem.SimpleItem): __implements__ = IErrorTranslator.IErrorTranslationRule security = AccessControl.ClassSecurityInfo() meta_type = "Error Translation Rule"
class FSPropertiesObject(FSObject, PropertyManager): """FSPropertiesObjects simply hold properties.""" meta_type = 'Filesystem Properties Object' manage_options = ({'label': 'Customize', 'action': 'manage_main'}, ) security = ClassSecurityInfo() security.declareProtected(ViewManagementScreens, 'manage_main') manage_main = Globals.DTMLFile('custprops', _dtmldir) # Declare all (inherited) mutating methods private. security.declarePrivate('manage_addProperty') security.declarePrivate('manage_editProperties') security.declarePrivate('manage_delProperties') security.declarePrivate('manage_changeProperties') security.declarePrivate('manage_propertiesForm') security.declarePrivate('manage_propertyTypeForm') security.declarePrivate('manage_changePropertyTypes') security.declareProtected(ViewManagementScreens, 'manage_doCustomize') def manage_doCustomize(self, folder_path, RESPONSE=None): """Makes a ZODB Based clone with the same data. Calls _createZODBClone for the actual work. """ # Overridden here to provide a different redirect target. FSObject.manage_doCustomize(self, folder_path, RESPONSE) if RESPONSE is not None: fpath = tuple(folder_path.split('/')) folder = self.restrictedTraverse(fpath) RESPONSE.redirect('%s/%s/manage_propertiesForm' % (folder.absolute_url(), self.getId())) def _createZODBClone(self): """Create a ZODB (editable) equivalent of this object.""" # Create a Folder to hold the properties. obj = Folder() obj.id = self.getId() map = [] for p in self._properties: # This should be secure since the properties come # from the filesystem. setattr(obj, p['id'], getattr(self, p['id'])) map.append({ 'id': p['id'], 'type': p['type'], 'mode': 'wd', }) obj._properties = tuple(map) return obj def _readFile(self, reparse): """Read the data from the filesystem. Read the file (indicated by exandpath(self._filepath), and parse the data if necessary. """ fp = expandpath(self._filepath) file = open(fp, 'rb') try: lines = file.readlines() finally: file.close() map = [] lino = 0 for line in lines: lino = lino + 1 line = line.strip() if not line or line[0] == '#': continue try: propname, proptv = line.split(':', 1) #XXX multi-line properties? proptype, propvstr = proptv.split('=', 1) propname = propname.strip() proptype = proptype.strip() propvstr = propvstr.strip() converter = get_converter(proptype, lambda x: x) propvalue = converter(propvstr) # Should be safe since we're loading from # the filesystem. setattr(self, propname, propvalue) map.append({ 'id': propname, 'type': proptype, 'mode': '', 'default_value': propvalue, }) except: raise ValueError, ('Error processing line %s of %s:\n%s' % (lino, fp, line)) self._properties = tuple(map) if Globals.DevelopmentMode: # Provide an opportunity to update the properties. def __of__(self, parent): self = Acquisition.ImplicitAcquisitionWrapper(self, parent) self._updateFromFS() return self
if info is not None: info = info.getContents(_dirreg) if info is None: data = {} objects = () else: data, objects = info s = DirectoryViewSurrogate(self, data, objects) res = s.__of__(parent) return res def getId(self): return self.id Globals.InitializeClass(DirectoryView) class DirectoryViewSurrogate(Folder): meta_type = 'Filesystem Directory View' all_meta_types = () _isDirectoryView = 1 security = ClassSecurityInfo() def __init__(self, real, data, objects): d = self.__dict__ d.update(data) d.update(real.__dict__) d['_real'] = real
security.declareProtected(TopicPermissions.ChangeTopics, 'edit') def edit(self, value, direction=''): """ Update the value we match against. """ if type(value) == type('') and (not string.strip(value)): # An empty string was passed in, which evals to None self.value = self.direction = None else: self.value = int(value) self.direction = direction security.declareProtected(CMFCorePermissions.View, 'getCriteriaItems') def getCriteriaItems(self): """ Used by Topic.buildQuery() """ if self.value is None: return () result = ((self.Field(), self.value), ) if self.direction is not None: result = result + ( ('%s_usage' % self.Field(), 'range:%s' % self.direction), ) return result Globals.InitializeClass(SimpleIntCriterion) # Register as a criteria type with the Topic class Topic._criteriaTypes.append(SimpleIntCriterion)
pt = self._getPortalTypeName() return tool.getTypeInfo(pt) # Can return None. # Support for dynamic icons security.declarePublic('getIcon') def getIcon(self, relative_to_portal=0): """ Using this method allows the content class creator to grab icons on the fly instead of using a fixed attribute on the class. """ ti = self.getTypeInfo() if ti is not None: icon = quote(ti.getIcon()) if icon: if relative_to_portal: return icon else: # Need the full path to the icon. portal_url = getPortal(self).absolute_url(relative=1) return portal_url + '/' + icon return 'misc_/OFSP/dtmldoc.gif' security.declarePublic('icon') icon = getIcon # For the ZMI and the catalog. Globals.InitializeClass(DynamicType)
def action(self): g.close_menu()
proptype = proptype.strip() propvstr = propvstr.strip() converter = get_converter(proptype, lambda x: x) propvalue = converter(propvstr) # Should be safe since we're loading from # the filesystem. setattr(self, propname, propvalue) map.append({ 'id': propname, 'type': proptype, 'mode': '', 'default_value': propvalue, }) except: raise ValueError, ('Error processing line %s of %s:\n%s' % (lino, fp, line)) self._properties = tuple(map) if Globals.DevelopmentMode: # Provide an opportunity to update the properties. def __of__(self, parent): self = Acquisition.ImplicitAcquisitionWrapper(self, parent) self._updateFromFS() return self Globals.InitializeClass(FSPropertiesObject) registerFileExtension('props', FSPropertiesObject) registerMetaType('Properties Object', FSPropertiesObject)
def start(self, build_library): start = time.time() print("--> Starting build of the main code base") print("--> Build configuration " + Globals.build_target_ + " : " + Globals.build_parameters_) print("--> Operating System: " + Globals.operating_system_) print("--> Building Library?: " + str(build_library)) self.cmake_compiler_ = ['Unix', 'MinGW' ][Globals.operating_system_ == "windows"] print("--> CMake Compiler: " + self.cmake_compiler_) # Check to see if the third party libraries have been built third_party_dir = "bin/" + Globals.operating_system_ + "/thirdparty" if not os.path.exists(third_party_dir): return Globals.PrintError( "Third-party libraries have not been built. Please build these first with thirdparty argument" ) # Build the Version.h file if Globals.git_path_ != '' and Globals.in_docker_ == '': print('-- Build CASAL2/source/Version.h with git log information') p = subprocess.Popen([ 'git', '--no-pager', 'log', '-n', '1', '--pretty=format:%H%n%h%n%ci' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() lines = out.decode('utf-8').split('\n') if len(lines) != 3: return Globals.PrintError( 'Format printed by git did not meet expectations. Expected 3 lines but got ' + str(len(lines))) time_pieces = lines[2].split(' ') temp = ' '.join(time_pieces) local_time = datetime.strptime(temp, '%Y-%m-%d %H:%M:%S %z') utc_time = local_time.astimezone(pytz.utc) version = '// This file is automatically built by the build system. Do not modify this file\n' version += '#ifndef VERSION_H_\n' version += '#define VERSION_H_\n' version += '#define SOURCE_CONTROL_REVISION ' + lines[0] + '\n' version += '#define SOURCE_CONTROL_DATE "' + utc_time.strftime( '%Y-%m-%d') + '"\n' version += '#define SOURCE_CONTROL_YEAR "' + utc_time.strftime( '%Y') + '"\n' version += '#define SOURCE_CONTROL_MONTH "' + utc_time.strftime( '%B') + '"\n' version += '#define SOURCE_CONTROL_TIME "' + utc_time.strftime( '%H:%M:%S') + '"\n' version += '#define SOURCE_CONTROL_VERSION "' + utc_time.strftime( '%Y-%m-%d %H:%M:%S %Z') + ' (rev. ' + lines[1] + ')"\n' version += '#endif\n' fo = open('../CASAL2/source/Version.h', 'w') fo.write(version) fo.close() self.output_directory_ = "bin/" + Globals.operating_system_ + "/" + Globals.build_target_ if Globals.build_parameters_ != "": self.output_directory_ += "_" + Globals.build_parameters_ if not os.path.exists(self.output_directory_): os.makedirs(self.output_directory_) print("--> Target output directory: " + self.output_directory_) os.chdir(self.output_directory_) print('--> Preparing CMake command') build_string = 'cmake -G "' + self.cmake_compiler_ + ' Makefiles" -D' + Globals.build_target_.upper( ) + '=1' if Globals.build_parameters_ != "": build_string += ' -D' + Globals.build_parameters_.upper() + '=1' build_string += ' ../../..' print("--> CMake command: " + build_string) if os.system(build_string) != EX_OK: return Globals.PrintError( "Failed to execute cmake successfully to rebuild the make files" ) print("--> Build main code base") if Globals.operating_system_ == "windows": if os.system("mingw32-make -j 4") != EX_OK: return Globals.PrintError( "Failed to build code base. Please see above for build error" ) else: if os.system("make -j 4") != EX_OK: return Globals.PrintError( "Failed to build code base. Please see above for build error" ) elapsed = time.time() - start print('Compile finished in ' + str(round(elapsed, 2)) + ' seconds') return True
def action(self): if g.state == "PAUSED" or g.state == "GAME_OVER": g.restart()
def __initTabContextMenu(self): """ Private method to create the tab context menu. """ self.__tabContextMenu = QMenu(self) self.tabContextNewAct = self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("tabNew.png"), self.tr('New Tab'), self.newBrowser) self.__tabContextMenu.addSeparator() self.leftMenuAct = self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("1leftarrow.png"), self.tr('Move Left'), self.__tabContextMenuMoveLeft) self.rightMenuAct = self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("1rightarrow.png"), self.tr('Move Right'), self.__tabContextMenuMoveRight) self.__tabContextMenu.addSeparator() self.tabContextCloneAct = self.__tabContextMenu.addAction( self.tr("Duplicate Page"), self.__tabContextMenuClone) self.__tabContextMenu.addSeparator() self.tabContextCloseAct = self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("tabClose.png"), self.tr('Close'), self.__tabContextMenuClose) self.tabContextCloseOthersAct = self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("tabCloseOther.png"), self.tr("Close Others"), self.__tabContextMenuCloseOthers) self.__tabContextMenu.addAction(self.tr('Close All'), self.closeAllBrowsers) self.__tabContextMenu.addSeparator() self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("printPreview.png"), self.tr('Print Preview'), self.__tabContextMenuPrintPreview) self.__tabContextMenu.addAction(UI.PixmapCache.getIcon("print.png"), self.tr('Print'), self.__tabContextMenuPrint) if Globals.isLinuxPlatform(): self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("printPdf.png"), self.tr('Print as PDF'), self.__tabContextMenuPrintPdf) self.__tabContextMenu.addSeparator() self.__tabContextMenu.addAction(UI.PixmapCache.getIcon("reload.png"), self.tr('Reload All'), self.reloadAllBrowsers) self.__tabContextMenu.addSeparator() self.__tabContextMenu.addAction( UI.PixmapCache.getIcon("addBookmark.png"), self.tr('Bookmark All Tabs'), self.__mainWindow.bookmarkAll) self.__tabBackContextMenu = QMenu(self) self.__tabBackContextMenu.addAction(self.tr('Close All'), self.closeAllBrowsers) self.__tabBackContextMenu.addAction( UI.PixmapCache.getIcon("reload.png"), self.tr('Reload All'), self.reloadAllBrowsers) self.__tabBackContextMenu.addAction( UI.PixmapCache.getIcon("addBookmark.png"), self.tr('Bookmark All Tabs'), self.__mainWindow.bookmarkAll) self.__tabBackContextMenu.addSeparator() self.__restoreClosedTabAct = self.__tabBackContextMenu.addAction( UI.PixmapCache.getIcon("trash.png"), self.tr('Restore Closed Tab'), self.restoreClosedTab) self.__restoreClosedTabAct.setEnabled(False) self.__restoreClosedTabAct.setData(0)
def action(self): if g.menu_open: g.close_menu() else: g.menu()
class FSPageTemplate(FSObject, Script, PageTemplate): "Wrapper for Page Template" meta_type = 'Filesystem Page Template' _owner = None # Unowned manage_options = (( { 'label': 'Customize', 'action': 'manage_main' }, { 'label': 'Test', 'action': 'ZScriptHTML_tryForm' }, ) + Cacheable.manage_options) security = ClassSecurityInfo() security.declareObjectProtected(View) security.declareProtected(ViewManagementScreens, 'manage_main') manage_main = Globals.DTMLFile('dtml/custpt', globals()) # Declare security for unprotected PageTemplate methods. security.declarePrivate('pt_edit', 'write') def __init__(self, id, filepath, fullname=None, properties=None): FSObject.__init__(self, id, filepath, fullname, properties) self.ZBindings_edit(self._default_bindings) def _createZODBClone(self): """Create a ZODB (editable) equivalent of this object.""" obj = ZopePageTemplate(self.getId(), self._text, self.content_type) obj.expand = 0 obj.write(self.read()) return obj # def ZCacheable_isCachingEnabled(self): # return 0 def _readFile(self, reparse): fp = expandpath(self._filepath) file = open(fp, 'rU') # not 'rb', as this is a text file! try: data = file.read() finally: file.close() if reparse: # If we already have a content_type set it must come from a # .metadata file and we should always honor that. The content # type is initialized as text/html by default, so we only # attempt further detection if the default is encountered. # One previous misbehavior remains: It is not possible to # force a text./html type if parsing detects it as XML. if getattr(self, 'content_type', 'text/html') == 'text/html': xml_info = xml_detect_re.match(data) if xml_info: # Smells like xml # set "content_type" from the XML declaration encoding = xml_info.group(1) or 'utf-8' self.content_type = 'text/xml; charset=%s' % encoding self.write(data) security.declarePrivate('read') def read(self): # Tie in on an opportunity to auto-update self._updateFromFS() return FSPageTemplate.inheritedAttribute('read')(self) ### The following is mainly taken from ZopePageTemplate.py ### expand = 0 func_defaults = None func_code = ZopePageTemplate.func_code _default_bindings = ZopePageTemplate._default_bindings security.declareProtected(View, '__call__') def pt_macros(self): # Tie in on an opportunity to auto-reload self._updateFromFS() return FSPageTemplate.inheritedAttribute('pt_macros')(self) def pt_render(self, source=0, extra_context={}): self._updateFromFS() # Make sure the template has been loaded. if not source: # If we have a conditional get, set status 304 and return # no content if _checkConditionalGET(self, extra_context): return '' result = FSPageTemplate.inheritedAttribute('pt_render')(self, source, extra_context) if not source: _setCacheHeaders(self, extra_context) return result security.declareProtected(ViewManagementScreens, 'pt_source_file') def pt_source_file(self): """ Return a file name to be compiled into the TAL code. """ return 'file:%s' % self._filepath security.declarePrivate('_ZPT_exec') _ZPT_exec = ZopePageTemplate._exec.im_func security.declarePrivate('_exec') def _exec(self, bound_names, args, kw): """Call a FSPageTemplate""" try: response = self.REQUEST.RESPONSE except AttributeError: response = None # Read file first to get a correct content_type default value. self._updateFromFS() if not kw.has_key('args'): kw['args'] = args bound_names['options'] = kw try: response = self.REQUEST.RESPONSE if not response.headers.has_key('content-type'): response.setHeader('content-type', self.content_type) except AttributeError: pass security = getSecurityManager() bound_names['user'] = security.getUser() # Retrieve the value from the cache. keyset = None if self.ZCacheable_isCachingEnabled(): # Prepare a cache key. keyset = { # Why oh why? # All this code is cut and paste # here to make sure that we # dont call _getContext and hence can't cache # Annoying huh? 'here': self.aq_parent.getPhysicalPath(), 'bound_names': bound_names } result = self.ZCacheable_get(keywords=keyset) if result is not None: # Got a cached value. return result # Execute the template in a new security context. security.addContext(self) try: result = self.pt_render(extra_context=bound_names) if keyset is not None: # Store the result in the cache. self.ZCacheable_set(result, keywords=keyset) return result finally: security.removeContext(self) return result # Copy over more methods security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = ZopePageTemplate.manage_FTPget.im_func security.declareProtected(View, 'get_size') get_size = ZopePageTemplate.get_size.im_func getSize = get_size security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource.im_func security.declareProtected(ViewManagementScreens, 'document_src') document_src = ZopePageTemplate.document_src.im_func pt_getContext = ZopePageTemplate.pt_getContext.im_func ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams.im_func source_dot_xml = Src()
def start(self): print("--> Starting build of the third party libraries") print("-- Operating System: " + Globals.operating_system_) print("-- Checking if output folder structure exists") self.output_directory_ = os.path.normpath( os.getcwd()) + "/bin/" + Globals.operating_system_ + "/thirdparty" if not os.path.exists(self.output_directory_): print("-- Creating output directory: " + self.output_directory_) os.makedirs(self.output_directory_) self.include_directory = self.output_directory_ + "/include" if not os.path.exists(self.include_directory): print("-- Creating include directory: " + self.include_directory) os.makedirs(self.include_directory) self.lib_directory = self.output_directory_ + "/lib" if not os.path.exists(self.lib_directory): print("-- Creating lib directory: " + self.lib_directory) os.makedirs(self.lib_directory) self.lib_debug_directory = self.lib_directory + "/debug" if not os.path.exists(self.lib_debug_directory): print("-- Creating lib debug directory: " + self.lib_debug_directory) os.makedirs(self.lib_debug_directory) self.lib_release_directory = self.lib_directory + "/release" if not os.path.exists(self.lib_release_directory): print("-- Creating lib release directory: " + self.lib_release_directory) os.makedirs(self.lib_release_directory) self.lib_special_directory = self.lib_directory + "/special" if not os.path.exists(self.lib_special_directory): print("-- Creating lib special directory: " + self.lib_special_directory) os.makedirs(self.lib_special_directory) self.input_directory = "../ThirdParty/" third_party_list = os.listdir(self.input_directory) Globals.target_success_path_ = self.output_directory_ + '/' Globals.target_include_path_ = self.output_directory_ + '/include/' Globals.target_debug_lib_path_ = self.output_directory_ + '/lib/debug/' Globals.target_release_lib_path_ = self.output_directory_ + '/lib/release/' Globals.target_special_lib_path_ = self.output_directory_ + '/lib/special/' cwd = os.path.normpath(os.getcwd()) build_module_name = "build" found_build = False for folder in third_party_list: # Do some simple checks to see if we want to process this folder if folder.startswith("."): continue if Globals.build_parameters_ != "" and Globals.build_parameters_ != folder.lower( ): continue if folder.startswith("test-") and Globals.build_parameters_ == "": print('--> Skipping library ' + folder + ' (test library)') continue # load the version number so we can handle upgrades library_version = str(-1.0) success_file = self.output_directory_ + "/" + folder + ".success" if os.path.exists(success_file): f = open(success_file, "r") library_version = f.readline().lstrip().rstrip().replace( '\n', '') f.close() found_build = True target_folder = "../ThirdParty/" + folder success = False os.chdir(target_folder) sys.path.append(os.path.normpath(os.getcwd())) """ # Handle loading the windows file and building this on windows """ if Globals.operating_system_ == "windows": if not os.path.exists('windows.py'): return Globals.PrintError( 'Third party library ' + folder + ' does not have a windows.py file.\nThis file is required to build this library on Windows' ) import windows as third_party_builder builder = third_party_builder.Builder() if os.path.exists( success_file ) and Globals.build_parameters_ == "" and hasattr( builder, 'version_') and str(library_version) == str( builder.version_ ) and str(library_version) != str(-1.0): print('--> Skipping library ' + folder + ' (version already installed)') success = True else: print("") do_build = False if Globals.build_target_ == "thirdpartylean" and hasattr( builder, 'is_lean') and builder.is_lean(): do_build = True elif Globals.build_target_ == "thirdparty": do_build = True if do_build: print("--> Building Library: " + folder) if not hasattr(builder, 'start'): return Globals.PrintError( 'Third party library ' + folder + ' does not have a valid start() method in windows.py' ) success = builder.start() if success: os.system('echo ' + str(builder.version_) + ' > ' + Globals.target_success_path_ + folder + '.success') print("") else: return Globals.PrintError( 'Third party library ' + folder + ' had an error during the build. Check log files for more information' ) del sys.modules["windows"] else: if not os.path.exists('linux.py'): return Globals.PrintError( 'Third party library ' + folder + ' does not have a linux.py file.\nThis file is required to build this library on Linux' ) import linux as third_party_builder builder = third_party_builder.Builder() if os.path.exists( success_file ) and Globals.build_parameters_ == "" and hasattr( builder, 'version_') and str(library_version) == str( builder.version_ ) and str(library_version) != str(-1.0): print('--> Skipping library ' + folder + ' (version already installed)') success = True else: print("") print("--> Building Library: " + folder) success = builder.start() if success: os.system('echo ' + str(builder.version_) + ' > ' + Globals.target_success_path_ + folder + '.success') print("") else: return Globals.PrintError( 'Third party library ' + folder + ' had an error during the build. Check log files for more information' ) del sys.modules["linux"] sys.path.pop() os.chdir(cwd) if not success: return False if not found_build and Globals.build_parameters_ != "": return Globals.PrintError("Third party library " + Globals.build_parameters_ + " does not exist") print("") print("--> All third party libraries have been built successfully") return True
def ChangeEffectOrder(self, effect, newPosition): """ Move a given GStreamer element inside the effects bin. This method does not swap the element into its new position, it simply shifts all the elements between the effect's current position and the new position down by one. Since a Gstreamer pipeline is essentially a linked list, this "shift" implementation is the fastest way to make one element move to a new position without changing the order of any of the others. For example if this instrument has five effects which are ordered A, B, C, D, E, and I call this method with effect D and a new position of 1 the new order will be: A, D, B, C, E. Parameters: effect -- GStreamer effect to be moved. newPosition -- value of the new position inside the effects bin the effect will have (with 0 as the first position). """ if effect not in self.effects: Globals.debug( "Error: trying to remove an element that is not in the list") return if newPosition >= len(self.effects): Globals.debug( "Error: trying to move effect to position past the end of the list" ) return oldPosition = self.effects.index(effect) if oldPosition == newPosition: #the effect is already in the proper position return # The effect currently at the position we want to move the given effect to newPositionEffect = self.effects[newPosition] for pad in effect.sink_pads(): if pad.is_linked(): previousElement = pad.get_peer().get_parent() break for pad in effect.src_pads(): if pad.is_linked(): nextElement = pad.get_peer().get_parent() break # The src pad on the first element (an audioconvert) in the bin startSrcPad = self.effectsBinConvert.get_pad("src") # check the state and block if we have to state = self.playbackbin.get_state(0)[1] if state == gst.STATE_PAUSED or state == gst.STATE_PLAYING: startSrcPad.set_blocked(True) #here's where we start unlinking and relinking previousElement.unlink(effect) effect.unlink(nextElement) previousElement.link(nextElement) if oldPosition > newPosition: for pad in newPositionEffect.sink_pads(): if pad.is_linked(): newPositionPrevious = pad.get_peer().get_parent() break newPositionPrevious.unlink(newPositionEffect) newPositionPrevious.link(effect) effect.link(newPositionEffect) else: for pad in newPositionEffect.src_pads(): if pad.is_linked(): newPositionNext = pad.get_peer().get_parent() break newPositionEffect.unlink(newPositionNext) newPositionEffect.link(effect) effect.link(newPositionNext) # remove and insert to our own llst so it matches the changes just made del self.effects[oldPosition] self.effects.insert(newPosition, effect) #give it a lambda for a callback that does nothing, so we don't have to wait startSrcPad.set_blocked_async(False, lambda x, y: False) self.emit("effect:reordered")
""" This module contains global constants. """ import Globals NAAYACORE_PRODUCT_NAME = 'NaayaCore' NAAYACORE_PRODUCT_PATH = Globals.package_home(globals()) METATYPE_FOLDER = 'Naaya Folder' PERMISSION_ADD_NAAYACORE_TOOL = 'Add NaayaCore Tool' METATYPE_CATALOGTOOL = 'Naaya Catalog Tool' METATYPE_EDITORTOOL = 'Naaya Editor Tool' METATYPE_GEOMAPTOOL = 'Naaya GeoMap Tool' METATYPE_EMAILTOOL = 'Naaya Email Tool' METATYPE_EMAILTEMPLATE = 'Naaya Email Template' METATYPE_SYNDICATIONTOOL = 'Naaya Syndication Tool' METATYPE_LOCALCHANNEL = 'Naaya Local Channel' METATYPE_SCRIPTCHANNEL = 'Naaya Script Channel' METATYPE_REMOTECHANNEL = 'Naaya Remote Channel' METATYPE_REMOTECHANNELFACADE = 'Naaya Remote Channel Facade' METATYPE_CHANNEL_AGGREGATOR = 'Naaya Channel Aggregator' METATYPE_AUTHENTICATIONTOOL = 'Naaya User Folder' METATYPE_PROPERTIESTOOL = 'Naaya Properties Tool' METATYPE_DYNAMICPROPERTIESTOOL = 'Naaya Dynamic Properties Tool' METATYPE_DYNAMICPROPERTIESITEM = 'Naaya Dynamic Properties Item' METATYPE_PORTLETSTOOL = 'Naaya Portlets Tool' METATYPE_ANALYTICSTOOL = 'Naaya Analytics Tool' METATYPE_PORTLET = 'Naaya Portlet'
# Installation and removal of traversal hooks. def manage_beforeDelete(self, item, container): if item is self: handle = self.meta_type + '/' + self.getId() BeforeTraverse.unregisterBeforeTraverse(container, handle) def manage_afterAdd(self, item, container): if item is self: handle = self.meta_type + '/' + self.getId() container = container.this() nc = BeforeTraverse.NameCaller(self.getId()) BeforeTraverse.registerBeforeTraverse(container, nc, handle) Globals.InitializeClass(CookieCrumbler) class ResponseCleanup: def __init__(self, resp): self.resp = resp def __del__(self): # Free the references. # # No errors of any sort may propagate, and we don't care *what* # they are, even to log them. try: del self.resp.unauthorized except: pass
# Copy over more methods security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = ZopePageTemplate.manage_FTPget.im_func security.declareProtected(View, 'get_size') get_size = ZopePageTemplate.get_size.im_func getSize = get_size security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = ZopePageTemplate.PrincipiaSearchSource.im_func security.declareProtected(ViewManagementScreens, 'document_src') document_src = ZopePageTemplate.document_src.im_func pt_getContext = ZopePageTemplate.pt_getContext.im_func ZScriptHTML_tryParams = ZopePageTemplate.ZScriptHTML_tryParams.im_func source_dot_xml = Src() setattr(FSPageTemplate, 'source.xml', FSPageTemplate.source_dot_xml) setattr(FSPageTemplate, 'source.html', FSPageTemplate.source_dot_xml) Globals.InitializeClass(FSPageTemplate) registerFileExtension('pt', FSPageTemplate) registerFileExtension('zpt', FSPageTemplate) registerFileExtension('html', FSPageTemplate) registerFileExtension('htm', FSPageTemplate) registerMetaType('Page Template', FSPageTemplate)
ve = self.var_exprs if REQUEST is not None: for id in ve.keys(): fname = 'varexpr_%s' % id val = REQUEST[fname] expr = None if val: expr = Expression(str(REQUEST[fname])) ve[id] = expr return self.manage_variables(REQUEST, 'Variables changed.') Globals.InitializeClass(TransitionDefinition) class Transitions(ContainerTab): """A container for transition definitions""" meta_type = 'Workflow Transitions' security = ClassSecurityInfo() security.declareObjectProtected(ManagePortal) all_meta_types = ({ 'name': TransitionDefinition.meta_type, 'action': 'addTransition', }, )
def run(self): while 1: # wait until the router is called self.expectedSignals['isCalled'] = 1 yield self.isCalled transmitter, eventTime = self.isCalled.value self.isCalled = self.env.event() self.printTrace('', '=-' * 15) self.printTrace('', 'router received event') # wait till there are no more events, the machines must be blocked while 1: if self.env.now == self.env.peek(): self.printTrace('', 'there are MORE events for now') yield self.env.timeout(0) else: self.printTrace('', 'there are NO more events for now') break self.printTrace('', '=-' * 15) from Globals import G if self.allocation: #=================================================================== # # XXX wait for the interval time to finish (10 minutes between reassignments #=================================================================== '''not implemented yet''' #=================================================================== # # find stations that are in position to process #=================================================================== self.availableStations = [] for station in G.MachineList: if station.checkIfActive(): self.availableStations.append(station) #=================================================================== # # XXX if the resources are still assigned then un-assign them from the machines they are currently assigned # # the same for all the objects exits #=================================================================== for operator in [ x for x in G.OperatorsList if x.isAssignedTo() ]: operator.unAssign() for object in [x for x in G.ObjList if x.exitIsAssignedTo()]: object.unAssignExit() #=================================================================== # # XXX un-assign all the PBs from their operatorPools #=================================================================== for station in G.MachineList: station.operatorPool.operators = [] #=================================================================== # # XXX calculate the WIP of each station #=================================================================== for station in self.availableStations: station.wip = 1 + (len(station.getActiveObjectQueue()) / station.capacity) for predecessor in station.previous: try: station.wip += float( len(predecessor.getActiveObjectQueue()) / float(predecessor.capacity)) except: # XXX what happens in the case of sources or infinite-capacity-queues pass #=================================================================== # # stations of the line and their corresponding WIP # TODO: the WIP of the stations must be normalised to the max WIP possible on that station #=================================================================== # identify the last time that there was an assignment maxLastAssignment = 0 for record in self.solutionList: if record: maxLastAssignment = record["time"] self.availableStationsDict = {} for station in self.availableStations: lastAssignmentTime = 0 for record in self.solutionList: if station.id in record["allocation"].values(): lastAssignmentTime = record["time"] # normalise the lastAssignmentTime based on the maxLastAssignment. if maxLastAssignment: lastAssignmentTime = 1.0 - float( lastAssignmentTime / float(maxLastAssignment)) # it there is definition of 'technology' to group machines add this if station.technology: self.availableStationsDict[str(station.id)] = { 'stationID': station.technology, 'machineID': station.id, 'WIP': station.wip, 'lastAssignment': lastAssignmentTime } # otherwise add just the id else: self.availableStationsDict[str(station.id)] = { 'stationID': station.id, 'WIP': station.wip, 'lastAssignment': lastAssignmentTime } #=================================================================== # # operators and their skills set #=================================================================== self.operators = {} import Globals for operator in G.OperatorsList: newSkillsList = [] for skill in operator.skillsList: newSkill = skill mach = Globals.findObjectById(skill) # if there is 'technology' defined for the stations send this to the LP solver if mach.technology: newSkill = mach.technology if newSkill not in newSkillsList: newSkillsList.append(newSkill) self.operators[str(operator.id)] = newSkillsList #=================================================================== # # available operators #=================================================================== self.availableOperatorList = [] for operator in G.OperatorsList: if operator.available and operator.onShift and not operator.onBreak: self.availableOperatorList.append(operator.id) LPFlag = True if self.checkCondition: LPFlag = self.checkIfAllocationShouldBeCalled() #=================================================================== # # XXX run the LP assignment algorithm # # should return a list of correspondences # # XXX signal the stations that the assignment is complete # TODO: a constant integer must be added to all WIP before provided to the opAss_LP # as it doesn't support zero WIP levels #=================================================================== import time startLP = time.time() if LPFlag: if self.twoPhaseSearch: # remove all the blocked machines from the available stations # and create another dict only with them machinesForSecondPhaseDict = {} for stationId in self.availableStationsDict.keys(): machine = Globals.findObjectById(stationId) if machine.isBlocked: machinesForSecondPhaseDict[ stationId] = self.availableStationsDict[ stationId] del self.availableStationsDict[stationId] # run the LP method only for the machines that are not blocked solution = opAss_LP( self.availableStationsDict, self.availableOperatorList, self.operators, previousAssignment=self.previousSolution, weightFactors=self.weightFactors, Tool=self.tool) # create a list with the operators that were sent to the LP but did not get allocated operatorsForSecondPhaseList = [] for operatorId in self.availableOperatorList: if operatorId not in solution.keys(): operatorsForSecondPhaseList.append(operatorId) # in case there is some station that did not get operator even if it was not blocked # add them alos for the second fail (XXX do not think there is such case) for stationId in self.availableStationsDict.keys(): if stationId not in solution.values(): machinesForSecondPhaseDict[ stationId] = self.availableStationsDict[ stationId] # if there are machines and operators for the second phase # run again the LP for machines and operators that are not in the former solution if machinesForSecondPhaseDict and operatorsForSecondPhaseList: secondPhaseSolution = opAss_LP( machinesForSecondPhaseDict, operatorsForSecondPhaseList, self.operators, previousAssignment=self.previousSolution, weightFactors=self.weightFactors, Tool=self.tool) # update the solution with the new LP results solution.update(secondPhaseSolution) else: solution = opAss_LP( self.availableStationsDict, self.availableOperatorList, self.operators, previousAssignment=self.previousSolution, weightFactors=self.weightFactors, Tool=self.tool) else: # if the LP is not called keep the previous solution # if there are no available operators though, remove those solution = self.previousSolution for operatorID in solution.keys(): if not operatorID in self.availableOperatorList: del solution[operatorID] # print '-------' # print self.env.now, solution # print 'time needed',time.time()-startLP self.solutionList.append({ "time": self.env.now, "allocation": solution }) # XXX assign the operators to operatorPools # pendingStations/ available stations not yet given operator self.pendingStations = [] from Globals import findObjectById # apply the solution # loop through the stations. If there is a station that should change operator # set the operator dedicated to None and also release operator for station in G.MachineList: # obtain the operator and the station if station.currentOperator: operator = station.currentOperator previousAssignment = self.previousSolution.get( operator.id, None) currentAssignment = solution.get(operator.id, None) if (not previousAssignment == currentAssignment): operator.operatorDedicatedTo = None if not station.isProcessing: station.releaseOperator() # loop through the entries in the solution dictionary for operatorID in solution.keys(): # obtain the operator and the station operator = findObjectById(operatorID) station = findObjectById(solution[operatorID]) if operatorID in self.previousSolution: # if the solution returned the operator that is already in the station # then no signal is needed if not self.previousSolution[operatorID] == solution[ operatorID]: self.toBeSignalled.append(station) else: self.toBeSignalled.append(station) # update the operatorPool of the station station.operatorPool.operators = [operator] # assign the operator to the station operator.assignTo(station) # set that the operator is dedicated to the station operator.operatorDedicatedTo = station # set in every station the operator that it is to get station.operatorToGet = operator # remove the operator id from availableOperatorList self.availableOperatorList.remove(operatorID) #=================================================================== # # XXX signal the stations that the assignment is complete #=================================================================== # if the operator is free the station can be signalled right away stationsProcessingLast = [] toBeSignalled = list(self.toBeSignalled) for station in toBeSignalled: # check if the operator that the station waits for is free operator = station.operatorToGet if operator.workingStation: # if the operator is in a station that is processing or just starts processing then he/she is not free if operator.workingStation.isProcessing or (not ( operator.workingStation.timeLastEntityEntered == self.env.now)): stationsProcessingLast.append( operator.workingStation) continue # signal the station so that it gets the operator self.signalStation(station, operator) # else wait for signals that operator became available and signal the stations self.expectedFinishSignalsDict = {} self.expectedFinishSignals = [] for station in stationsProcessingLast: signal = self.env.event() self.expectedFinishSignalsDict[station.id] = signal self.expectedFinishSignals.append(signal) while self.expectedFinishSignals: receivedEvent = yield self.env.any_of( self.expectedFinishSignals) for signal in self.expectedFinishSignals: if signal in receivedEvent: transmitter, eventTime = signal.value assert eventTime == self.env.now, 'the station finished signal must be received on the time of request' self.expectedFinishSignals.remove(signal) del self.expectedFinishSignalsDict[transmitter.id] # signal also the other stations that should be signalled for id in solution.keys(): operator = findObjectById(id) station = findObjectById(solution[id]) signal = True # signal only the stations in the original list if station not in self.toBeSignalled: signal = False # signal only if the operator is free if operator.workingStation: if operator.workingStation.isProcessing\ or (not (operator.workingStation.timeLastEntityEntered==self.env.now)): signal = False if signal: # signal the station so that it gets the operator self.signalStation(station, operator) #=================================================================== # default behaviour #=================================================================== else: # entry actions self.entryActions() # run the routine that allocates operators to machines self.allocateOperators() # assign operators to stations self.assignOperators() # unAssign exits self.unAssignExits() # signal the stations that ought to be signalled self.signalOperatedStations() self.previousSolution = solution self.printTrace('', 'router exiting') self.printTrace('', '=-' * 20) self.exitActions()
def init_connection_settings(conn): """Tell new conn about log settings and updated globals""" conn.log.Log.setverbosity(Log.verbosity) conn.log.Log.setterm_verbosity(Log.term_verbosity) for setting_name in Globals.changed_settings: conn.Globals.set(setting_name, Globals.get(setting_name))
finally: security.removeContext(self) return result # Copy over more methods security.declareProtected(FTPAccess, 'manage_FTPget') manage_FTPget = ZopeSimplate.manage_FTPget security.declareProtected(View, 'get_size') get_size = ZopeSimplate.get_size getSize = get_size security.declareProtected(ViewManagementScreens, 'PrincipiaSearchSource') PrincipiaSearchSource = ZopeSimplate.PrincipiaSearchSource security.declareProtected(ViewManagementScreens, 'document_src') document_src = ZopeSimplate.document_src simplate_getContext = ZopeSimplate.simplate_getContext ZScriptHTML_tryParams = ZopeSimplate.ZScriptHTML_tryParams Globals.InitializeClass(FSSimplate) registerFileExtension('smpt', FSSimplate) registerFileExtension('smpl', FSSimplate) registerFileExtension('spt', FSSimplate) registerMetaType('Simplate', FSSimplate) registerIcon(FSSimplate, 'www/fssimplate.png', globals())